All files / src/transactions transaction.ts

81.9% Statements 86/105
67.92% Branches 36/53
83.33% Functions 15/18
81.73% Lines 85/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 307 308 309 310 311 312 313 314 315                            92x   10x                                   10x   10x               10x   10x   10x 10x   10x                                   56x 56x 56x           13x   56x 56x 56x   56x 50x                     6x 6x             39x 39x 39x       10x 10x 10x       2x 2x 2x     2x   2x       10x       40x     40x     40x       7x 7x           7x             5x 5x 5x 5x                                 47x             47x 32x   15x 15x               47x       49x 49x       10x       10x                 3x                 1x                                 92x     92x     92x     92x     92x       92x   92x 92x   92x 92x 92x 92x 92x 92x   92x             10x   22x 5x 1x   4x   17x 1x   16x   22x     22x 22x   22x     22x     22x 22x   22x                    
import {
  BufferArray,
  BufferReader,
  bytesToHex,
  hexToBytes,
  writeUInt32BE,
  IntegerType,
  intToBigInt,
  cloneDeep,
  SerializationError,
  SigningError,
  ChainID,
  DEFAULT_CHAIN_ID,
  TransactionVersion,
} from 'micro-stacks/common';
 
import { AnchorMode, AuthType, PostConditionMode, PubKeyEncoding } from './common/constants';
 
import {
  Authorization,
  createMessageSignature,
  createTransactionAuthField,
  intoInitialSighashAuth,
  isSingleSig,
  nextSignature,
  setFee,
  setNonce,
  setSponsorNonce,
  setSponsor,
  SingleSigSpendingCondition,
  SpendingConditionOpts,
  verifyOrigin,
  serializeAuthorization,
  deserializeAuthorization,
} from './authorization';
 
import { txidFromData } from './common/utils';
 
import {
  deserializePayload,
  Payload,
  PayloadInput,
  PayloadType,
  serializePayload,
} from './payload';
 
import { createLPList, deserializeLPList, LengthPrefixedList, serializeLPList } from './types';
 
import { isCompressed, isPrivateKeyCompressed, StacksPrivateKey, StacksPublicKey } from './keys';
import { StacksMessageType } from 'micro-stacks/clarity';
 
export class StacksTransaction {
  version: TransactionVersion;
  chainId: ChainID;
  auth: Authorization;
  anchorMode: AnchorMode;
  payload: Payload;
  postConditionMode: PostConditionMode;
  postConditions: LengthPrefixedList;
 
  constructor(
    version: TransactionVersion,
    auth: Authorization,
    payload: PayloadInput,
    postConditions?: LengthPrefixedList,
    postConditionMode?: PostConditionMode,
    anchorMode?: AnchorMode,
    chainId?: ChainID
  ) {
    this.version = version;
    this.auth = auth;
    if ('amount' in payload) {
      this.payload = {
        ...payload,
        amount: intToBigInt(payload.amount, false),
      };
    } else {
      this.payload = payload;
    }
    this.chainId = chainId ?? DEFAULT_CHAIN_ID;
    this.postConditionMode = postConditionMode ?? PostConditionMode.Deny;
    this.postConditions = postConditions ?? createLPList([]);
 
    if (anchorMode) {
      this.anchorMode = anchorMode;
    } else {
      switch (payload.payloadType) {
        case PayloadType.Coinbase:
        case PayloadType.PoisonMicroblock: {
          this.anchorMode = AnchorMode.OnChainOnly;
          break;
        }
        case PayloadType.ContractCall:
        case PayloadType.SmartContract:
        case PayloadType.TokenTransfer: {
          this.anchorMode = AnchorMode.Any;
          break;
        }
      }
    }
  }
 
  signBegin() {
    const tx = cloneDeep(this);
    tx.auth = intoInitialSighashAuth(tx.auth);
    return tx.txid();
  }
 
  verifyBegin() {
    const tx = cloneDeep(this);
    tx.auth = intoInitialSighashAuth(tx.auth);
    return tx.txid();
  }
 
  createTxWithSignature(signature: string | Uint8Array): StacksTransaction {
    const parsedSig = typeof signature === 'string' ? signature : bytesToHex(signature);
    const tx = cloneDeep<StacksTransaction>(this);
    Iif (!tx.auth.spendingCondition) {
      throw new Error('Cannot set signature on transaction without spending condition');
    }
    (tx.auth.spendingCondition as SingleSigSpendingCondition).signature =
      createMessageSignature(parsedSig);
    return tx;
  }
 
  verifyOrigin(): string {
    return verifyOrigin(this.auth, this.verifyBegin());
  }
 
  async signNextOrigin(sigHash: string, privateKey: StacksPrivateKey): Promise<string> {
    Iif (this.auth.spendingCondition === undefined) {
      throw new Error('"auth.spendingCondition" is undefined');
    }
    Iif (this.auth.authType === undefined) {
      throw new Error('"auth.authType" is undefined');
    }
    return this.signAndAppend(this.auth.spendingCondition, sigHash, AuthType.Standard, privateKey);
  }
 
  async signNextSponsor(sigHash: string, privateKey: StacksPrivateKey): Promise<string> {
    if (this.auth.authType === AuthType.Sponsored) {
      const sig = await this.signAndAppend(
        this.auth.sponsorSpendingCondition,
        sigHash,
        AuthType.Sponsored,
        privateKey
      );
      return sig;
    } else E{
      throw new Error('"auth.sponsorSpendingCondition" is undefined');
    }
  }
 
  appendPubkey(publicKey: StacksPublicKey) {
    const cond = this.auth.spendingCondition;
    if (cond && !isSingleSig(cond)) {
      const compressed = isCompressed(publicKey);
      cond.fields.push(
        createTransactionAuthField(
          compressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
          publicKey
        )
      );
    } else E{
      throw new Error(`Can't append public key to a singlesig condition`);
    }
  }
 
  async signAndAppend(
    condition: SpendingConditionOpts,
    curSigHash: string,
    authType: AuthType,
    privateKey: StacksPrivateKey
  ): Promise<string> {
    const { nextSig, nextSigHash } = await nextSignature(
      curSigHash,
      authType,
      condition.fee,
      condition.nonce,
      privateKey
    );
    if (isSingleSig(condition)) {
      condition.signature = nextSig;
    } else {
      const compressed = privateKey.compressed || isPrivateKeyCompressed(privateKey.data);
      condition.fields.push(
        createTransactionAuthField(
          compressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
          nextSig
        )
      );
    }
 
    return nextSigHash;
  }
 
  txid(): string {
    const serialized = this.serialize();
    return txidFromData(serialized);
  }
 
  setSponsor(sponsorSpendingCondition: SpendingConditionOpts) {
    Iif (this.auth.authType != AuthType.Sponsored) {
      throw new SigningError('Cannot sponsor sign a non-sponsored transaction');
    }
 
    this.auth = setSponsor(this.auth, sponsorSpendingCondition);
  }
 
  /**
   * Set the total fee to be paid for this transaction
   *
   * @param fee - the fee amount in microstacks
   */
  setFee(amount: IntegerType) {
    this.auth = setFee(this.auth, amount);
  }
 
  /**
   * Set the transaction nonce
   *
   * @param nonce - the nonce value
   */
  setNonce(nonce: IntegerType) {
    this.auth = setNonce(this.auth, nonce);
  }
 
  /**
   * Set the transaction sponsor nonce
   *
   * @param nonce - the sponsor nonce value
   */
  setSponsorNonce(nonce: IntegerType) {
    Iif (this.auth.authType != AuthType.Sponsored) {
      throw new SigningError('Cannot sponsor sign a non-sponsored transaction');
    }
 
    this.auth = setSponsorNonce(this.auth, nonce);
  }
 
  serialize(): Uint8Array {
    Iif (this.version === undefined) {
      throw new SerializationError('"version" is undefined');
    }
    Iif (this.chainId === undefined) {
      throw new SerializationError('"chainId" is undefined');
    }
    Iif (this.auth === undefined) {
      throw new SerializationError('"auth" is undefined');
    }
    Iif (this.anchorMode === undefined) {
      throw new SerializationError('"anchorMode" is undefined');
    }
    Iif (this.payload === undefined) {
      throw new SerializationError('"payload" is undefined');
    }
 
    const bufferArray: BufferArray = new BufferArray();
 
    bufferArray.appendByte(this.version);
    const chainIdBuffer = new Uint8Array(4);
    writeUInt32BE(chainIdBuffer, this.chainId, 0);
    bufferArray.push(chainIdBuffer);
    bufferArray.push(serializeAuthorization(this.auth));
    bufferArray.appendByte(this.anchorMode);
    bufferArray.appendByte(this.postConditionMode);
    bufferArray.push(serializeLPList(this.postConditions));
    bufferArray.push(serializePayload(this.payload));
 
    return bufferArray.concatBuffer();
  }
}
 
/**
 * @param data Buffer or hex string
 */
export function deserializeTransaction(data: BufferReader | Uint8Array | string) {
  let bufferReader: BufferReader;
  if (typeof data === 'string') {
    if (data.slice(0, 2).toLowerCase() === '0x') {
      bufferReader = new BufferReader(hexToBytes(data.slice(2)));
    } else {
      bufferReader = new BufferReader(hexToBytes(data));
    }
  } else if (data instanceof Uint8Array) {
    bufferReader = new BufferReader(data);
  } else {
    bufferReader = data;
  }
  const version = bufferReader.readUInt8Enum(TransactionVersion, n => {
    throw new Error(`Could not parse ${n} as TransactionVersion`);
  });
  const chainId = bufferReader.readUInt32BE();
  const auth = deserializeAuthorization(bufferReader);
 
  const anchorMode = bufferReader.readUInt8Enum(AnchorMode, n => {
    throw new Error(`Could not parse ${n} as AnchorMode`);
  });
  const postConditionMode = bufferReader.readUInt8Enum(PostConditionMode, n => {
    throw new Error(`Could not parse ${n} as PostConditionMode`);
  });
  const postConditions = deserializeLPList(bufferReader, StacksMessageType.PostCondition);
  const payload = deserializePayload(bufferReader);
 
  return new StacksTransaction(
    version,
    auth,
    payload,
    postConditions,
    postConditionMode,
    anchorMode,
    chainId
  );
}