All files / src/trxTypes BaseTx.ts

94.96% Statements 113/119
88.89% Branches 56/63
95.45% Functions 21/22
94.83% Lines 110/116
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 3071x 1x 1x 1x   1x 1x 1x                                     1x       1463x                       1463x                 6154x 3077x 3077x 3077x 3077x 3077x   3077x   3077x       3077x 2400x         2400x 19200x     677x 5416x         3077x   3077x 1206x 45018x       3077x 1740x     3077x 301x   3077x       3077x     1x   1341x 1341x 302x 302x   1039x     1341x 1x   1340x 3x 1x   2x     1339x 2x   1337x       1337x 1337x   1337x 301x     1337x 1337x           1x 3077x             1x 7102x 7102x     1x 1003x     1x 700x     1x 1003x     1x 303x     1x 1003x     1x 1003x           1x 1440x 1x   1439x 102x     1439x                           1439x 1138x   1439x               1x 1638x 1638x         1x 2x     2x               110x 109x   1x       1x 2x       5x 1x   4x 3x   1x       1x                     1x 1439x 1439x 1439x 11512x   1439x                             1x                 1x 5118x   5118x 229088x     1x  
import BigNumber from 'bignumber.js';
import * as ByteBuffer from 'bytebuffer';
import * as empty from 'is-empty';
import {api as sodium} from 'sodium';
 
import {bigNumberFromBuffer, bigNumberToBuffer} from '../utils/bignumber';
import {toSha256} from '../utils/sha256';
import {GenericWallet} from '../wallet';
 
export interface ITransaction<AssetType = {}> {
  recipientId: string;
  amount: number;
  senderPublicKey: string;
  requesterPublicKey: string;
  timestamp: number;
  fee: number;
  asset: AssetType;
  type: number;
  id: string;
  signature: string;
  signSignature?: string;
}
 
/**
 * Base transaction class.
 */
export abstract class BaseTx<T = {}> {
  public recipientId: string;
  public amount: number;
  public senderPublicKey: string;
  public requesterPublicKey: string = null;
  public timestamp: number;
  public fee: number;
  protected abstract type: number;
  // Transients
  // tslint:disable variable-name
  protected _signature: string;
  protected _secondSignature?: string;
  protected _id: string;
 
  // tslint:enable variable-name
 
  constructor(public asset?: T) {
  }
 
  /**
   * Calculates bytes of tx.
   * @param {boolean} skipSignature=false true if you don't want to account signature
   * @param {boolean} skipSecondSign=false true if you don't want to account second signature
   * @returns {Buffer}
   */
  public getBytes(EskipSignature: boolean = false, EskipSecondSign: boolean = false): Buffer {
    const childBytes = this.getChildBytes(skipSignature, skipSecondSign);
    const assetSize  = empty(childBytes) ? 0 : childBytes.length;
    const bb         = new ByteBuffer(1 + 4 + 32 + 32 + 8 + 8 + 64 + 64 + assetSize, true);
    bb.writeByte(this.type);
    bb.writeInt(this.timestamp);
 
    BaseTx.hexKeyInByteBuffer(this.senderPublicKey, bb);
 
    Iif (!empty(this.requesterPublicKey)) {
      BaseTx.hexKeyInByteBuffer(this.requesterPublicKey, bb);
    }
 
    if (!empty(this.recipientId)) {
      const recipient = bigNumberToBuffer(
        new BigNumber(this.recipientId.slice(0, -1)),
        { size: 8 }
      );
 
      for (let i = 0; i < 8; i++) {
        bb.writeByte(recipient[i] || 0);
      }
    } else {
      for (let i = 0; i < 8; i++) {
        bb.writeByte(0);
      }
    }
 
    // tslint:disable-next-line no-string-literal
    bb['writeLong'](this.amount);
 
    if (assetSize > 0) {
      for (let i = 0; i < assetSize; i++) {
        bb.writeByte(childBytes[i]);
      }
    }
 
    if (!skipSignature && !empty(this._signature)) {
      BaseTx.hexKeyInByteBuffer(this._signature, bb);
    }
 
    if (!skipSecondSign && !empty(this._secondSignature)) {
      BaseTx.hexKeyInByteBuffer(this._secondSignature, bb);
    }
    bb.flip();
 
    // TODO: Check? this returns an array buffer which does not
    // inherit from buffer (according to ts types).
    return new Buffer(bb.toBuffer());
  }
 
  public sign(signingPrivKey: string | GenericWallet, signingSecondPrivKey?: string): ITransaction<T> {
    let privKey: string;
    let wallet: GenericWallet = null;
    if (signingPrivKey instanceof GenericWallet) {
      privKey = signingPrivKey.privKey;
      wallet  = signingPrivKey;
    } else {
      privKey = signingPrivKey;
    }
 
    if (empty(this.type) && this.type !== 0) {
      throw new Error(`Unknown transaction type ${this.type}`);
    }
    if (empty(this.senderPublicKey)) {
      if (wallet === null) {
        throw new Error('Sender Public Key is empty');
      }
      this.senderPublicKey = wallet.publicKey;
    }
 
    if ((empty(this.timestamp) && this.timestamp !== 0 ) || this.timestamp < 0) {
      throw new Error('Invalid timestamp provided');
    }
    Iif (empty(this.fee)) {
      throw new Error('No fees specified');
    }
 
    this.innerCreate();
    this._signature = this.createSignature(privKey).toString('hex');
 
    if (!empty(signingSecondPrivKey)) {
      this._secondSignature = this.createSignature(signingSecondPrivKey).toString('hex');
    }
 
    this._id = this.calcId();
    return this.toObj();
  }
 
  /**
   * Gets raw hash of current tx
   */
  public getHash(): Buffer {
    return toSha256(this.getBytes());
  }
 
  // chain style utilities.
  public set(key: 'type' | 'fee' | 'amount' | 'timestamp', value: number): this;
  public set(key: 'senderPublicKey' | 'recipientId' | 'requesterPublicKey', value: string): this;
  public set(key: 'asset', value: T): this;
  public set(key: string, value: any): this {
    this[key] = value;
    return this;
  }
 
  public withRecipientId(recipientId: string): this {
    return this.set('recipientId', recipientId);
  }
 
  public withAmount(amount: number): this {
    return this.set('amount', amount);
  }
 
  public withSenderPublicKey(senderPublicKey: string): this {
    return this.set('senderPublicKey', senderPublicKey);
  }
 
  public withRequesterPublicKey(senderPublicKey: string): this {
    return this.set('requesterPublicKey', senderPublicKey);
  }
 
  public withTimestamp(timestamp: number): this {
    return this.set('timestamp', timestamp);
  }
 
  public withFees(fees: number): this {
    return this.set('fee', fees);
  }
 
  /**
   * Returns plain object representation of tx (if not signed error will be thrown)
   */
  public toObj(): ITransaction<T> {
    if (empty(this._signature)) {
      throw new Error('Signature must be set before calling toObj');
    }
    if (empty(this._id)) {
      this._id = this.calcId();
    }
    // tslint:disable object-literal-sort-keys
    const toRet = {
      id                : this._id,
      fee               : this.fee,
      type              : this.type,
      recipientId       : this.recipientId,
      amount            : this.amount,
      senderPublicKey   : this.senderPublicKey,
      requesterPublicKey: this.requesterPublicKey,
      timestamp         : this.timestamp,
      signature         : this._signature,
      signSignature     : this._secondSignature || undefined,
      asset             : this.asset,
    };
    // tslint:enable object-literal-sort-keys
    if (empty(toRet.signSignature)) {
      delete toRet.signSignature;
    }
    return toRet;
  }
 
  /**
   * Generate signature from given private key.
   * @param {string} privKey
   * @returns {Buffer}
   */
  protected createSignature(privKey: string) {
    const hash = this.getHash();
    return sodium.crypto_sign_detached(
      hash,
      new Buffer(privKey, 'hex'));
  }
 
  get signature() {
    Iif (empty(this._signature)) {
      throw new Error('Call create first');
    }
    return this._signature;
  }
 
  /**
   * Set signature
   * @param {string | Buffer} signature
   */
  set signature(signature: string | Buffer) {
    this._signature = (signature instanceof Buffer ? signature : new Buffer(signature, 'hex')).toString('hex');
    if (this._signature.length !== 128) {
      // Signature should have 64 bytes!
      throw new Error('Signature is not having a correct lengthness');
    }
  }
 
  get secondSignature() {
    return this._secondSignature;
  }
 
  set secondSignature(signature: string | Buffer) {
    if (empty(this._signature)) {
      throw new Error('Did you set signature first? Most likely you did not calculated 2nd Signature on correct bytes');
    }
    this._secondSignature = (signature instanceof Buffer ? signature : new Buffer(signature, 'hex')).toString('hex');
    if (this._secondSignature.length !== 128) {
      // Signature should have 64 bytes!
      throw new Error('Signature is not having a correct lengthness');
    }
  }
 
  get id() {
    if (empty(this._id)) {
      throw new Error('Call create first');
    }
    return this._id;
  }
 
  /**
   * Calculates Tx id!
   * @returns {string}
   */
  protected calcId(): string {
    const hash = this.getHash();
    const temp = new Buffer(8);
    for (let i = 0; i < 8; i++) {
      temp[i] = hash[7 - i];
    }
    return bigNumberFromBuffer(temp).toString();
  }
 
  /**
   * Override to calculate asset bytes.
   * @param {boolean} skipSignature
   * @param {boolean} skipSecondSign
   */
  protected abstract getChildBytes(skipSignature: boolean, skipSecondSign: boolean): Buffer;
 
  /**
   * override this to allow asset and other fields creations.
   * for different tx types.
   */
  // tslint:disable-next-line no-empty
  protected innerCreate() {
  }
 
  /**
   * Utility to copy an hex string to a bytebuffer
   * @param {string} hex
   * @param {ByteBuffer} bb
   */
  // tslint:disable-next-line member-ordering
  public static hexKeyInByteBuffer(hex: string, bb: ByteBuffer) {
    const buf = Buffer.from(hex, 'hex');
    // tslint:disable-next-line prefer-for-of
    for (let i = 0; i < buf.length; i++) {
      bb.writeByte(buf[i]);
    }
  }
}