All files / src/transactions types.ts

82.55% Statements 123/149
73.77% Branches 45/61
95.83% Functions 23/24
82.19% Lines 120/146

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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 42312x   12x   12x   12x               12x                       12x             12x 12x                                   12x                             12x     20x       43x   77x   1x   27x   1x   1x   7x   25x           12x             1x       1x       1x   4x   1x   7x                         12x 18x             12x 87x             12x               1x   1x                     2x   2x                     12x         6x 6x     12x           81x       81x 69x         81x 2x 3x               68x   1x   11x   1x                         12x     1x 1x 1x           12x 8x             12x       5x               12x 27x 27x 27x 27x 8x   27x     12x 9x     9x 9x 7x   2x 2x               12x 3x               12x 28x     28x     12x 77x 77x 77x 77x 77x     12x 23x 23x 23x 23x               12x 1x 1x     12x         5x               12x 12x 12x 12x 12x 12x     12x 4x                           12x       89x             12x 115x 115x 115x 115x 53x   115x     12x         32x 32x 32x     5x 5x                     5x 5x         22x 22x     32x    
import { AddressHashMode } from './common/constants';
 
import { deserializePublicKey, isCompressed, serializePublicKey, StacksPublicKey } from './keys';
 
import { rightPadHexToLength } from './common/utils';
 
import { deserializePayload, Payload, serializePayload } from './payload';
import {
  deserializeMessageSignature,
  deserializeTransactionAuthField,
  MessageSignature,
  serializeMessageSignature,
  serializeTransactionAuthField,
  TransactionAuthField,
} from './authorization';
import {
  BufferArray,
  BufferReader,
  bytesToHex,
  bytesToUtf8,
  DeserializationError,
  hexStringToInt,
  hexToBytes,
  intToHexString,
  TransactionVersion,
  utf8ToBytes,
} from 'micro-stacks/common';
import {
  hashP2PKH,
  hashP2SH,
  hashP2WPKH,
  hashP2WSH,
  StacksNetworkVersion,
} from 'micro-stacks/crypto';
import { deserializePostCondition, PostCondition, serializePostCondition } from './postcondition';
import {
  Address,
  AssetInfo,
  ContractPrincipal,
  createAddress,
  createLPString,
  deserializeAddress,
  deserializeLPString,
  exceedsMaxLengthBytes,
  LengthPrefixedString,
  MEMO_MAX_LENGTH_BYTES,
  PostConditionPrincipal,
  PostConditionPrincipalID,
  serializeAddress,
  serializeLPString,
  StacksMessageType,
  StandardPrincipal,
} from 'micro-stacks/clarity';
 
export type StacksMessage =
  | Address
  | PostConditionPrincipal
  | LengthPrefixedString
  | LengthPrefixedList
  | Payload
  | MemoString
  | AssetInfo
  | PostCondition
  | StacksPublicKey
  | TransactionAuthField
  | MessageSignature;
 
export function serializeStacksMessage(message: StacksMessage): Uint8Array {
  switch (message.type) {
    case StacksMessageType.Address:
      return serializeAddress(message);
    case StacksMessageType.Principal:
      return serializePrincipal(message);
    case StacksMessageType.LengthPrefixedString:
      return serializeLPString(message);
    case StacksMessageType.MemoString:
      return serializeMemoString(message);
    case StacksMessageType.AssetInfo:
      return serializeAssetInfo(message);
    case StacksMessageType.PostCondition:
      return serializePostCondition(message);
    case StacksMessageType.PublicKey:
      return serializePublicKey(message);
    case StacksMessageType.LengthPrefixedList:
      return serializeLPList(message);
    case StacksMessageType.Payload:
      return serializePayload(message);
    case StacksMessageType.TransactionAuthField:
      return serializeTransactionAuthField(message);
    case StacksMessageType.MessageSignature:
      return serializeMessageSignature(message);
  }
}
 
export function deserializeStacksMessage(
  bufferReader: BufferReader,
  type: StacksMessageType,
  listType?: StacksMessageType
): StacksMessage {
  switch (type) {
    case StacksMessageType.Address:
      return deserializeAddress(bufferReader);
    case StacksMessageType.Principal:
      return deserializePrincipal(bufferReader);
    case StacksMessageType.LengthPrefixedString:
      return deserializeLPString(bufferReader);
    case StacksMessageType.MemoString:
      return deserializeMemoString(bufferReader);
    case StacksMessageType.AssetInfo:
      return deserializeAssetInfo(bufferReader);
    case StacksMessageType.PostCondition:
      return deserializePostCondition(bufferReader);
    case StacksMessageType.PublicKey:
      return deserializePublicKey(bufferReader);
    case StacksMessageType.Payload:
      return deserializePayload(bufferReader);
    case StacksMessageType.LengthPrefixedList:
      Iif (!listType) {
        throw new DeserializationError('No List Type specified');
      }
      return deserializeLPList(bufferReader, listType);
    case StacksMessageType.MessageSignature:
      return deserializeMessageSignature(bufferReader);
    default:
      throw new Error('Could not recognize StacksMessageType');
  }
}
 
export function createEmptyAddress(): Address {
  return {
    type: StacksMessageType.Address,
    version: StacksNetworkVersion.mainnetP2PKH,
    hash160: '0'.repeat(40),
  };
}
 
export function addressFromVersionHash(version: StacksNetworkVersion, hash: string): Address {
  return { type: StacksMessageType.Address, version, hash160: hash };
}
 
/**
 * Translates the tx auth hash mode to the corresponding address version.
 * @see https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#transaction-authorization
 */
export function addressHashModeToVersion(
  hashMode: AddressHashMode,
  txVersion: TransactionVersion
): StacksNetworkVersion {
  switch (hashMode) {
    case AddressHashMode.SerializeP2PKH:
      switch (txVersion) {
        case TransactionVersion.Mainnet:
          return StacksNetworkVersion.mainnetP2PKH;
        case TransactionVersion.Testnet:
          return StacksNetworkVersion.testnetP2PKH;
        default:
          throw new Error(
            `Unexpected txVersion ${JSON.stringify(txVersion)} for hashMode ${hashMode}`
          );
      }
    case AddressHashMode.SerializeP2SH:
    case AddressHashMode.SerializeP2WPKH:
    case AddressHashMode.SerializeP2WSH:
      switch (txVersion) {
        case TransactionVersion.Mainnet:
          return StacksNetworkVersion.mainnetP2SH;
        case TransactionVersion.Testnet:
          return StacksNetworkVersion.testnetP2SH;
        default:
          throw new Error(
            `Unexpected txVersion ${JSON.stringify(txVersion)} for hashMode ${hashMode}`
          );
      }
    default:
      throw new Error(`Unexpected hashMode ${JSON.stringify(hashMode)}`);
  }
}
 
export function addressFromHashMode(
  hashMode: AddressHashMode,
  txVersion: TransactionVersion,
  data: string
): Address {
  const version = addressHashModeToVersion(hashMode, txVersion);
  return addressFromVersionHash(version, data);
}
 
export function addressFromPublicKeys(
  version: StacksNetworkVersion,
  hashMode: AddressHashMode,
  numSigs: number,
  publicKeys: StacksPublicKey[]
): Address {
  Iif (publicKeys.length === 0) {
    throw Error('Invalid number of public keys');
  }
 
  if (hashMode === AddressHashMode.SerializeP2PKH || hashMode === AddressHashMode.SerializeP2WPKH) {
    Iif (publicKeys.length !== 1 || numSigs !== 1) {
      throw Error('Invalid number of public keys or signatures');
    }
  }
 
  if (hashMode === AddressHashMode.SerializeP2WPKH || hashMode === AddressHashMode.SerializeP2WSH) {
    for (let i = 0; i < publicKeys.length; i++) {
      Iif (!isCompressed(publicKeys[i])) {
        throw Error('Public keys must be compressed for segwit');
      }
    }
  }
 
  switch (hashMode) {
    case AddressHashMode.SerializeP2PKH:
      return addressFromVersionHash(version, hashP2PKH(publicKeys[0].data));
    case AddressHashMode.SerializeP2WPKH:
      return addressFromVersionHash(version, hashP2WPKH(publicKeys[0].data));
    case AddressHashMode.SerializeP2SH:
      return addressFromVersionHash(version, hashP2SH(numSigs, publicKeys.map(serializePublicKey)));
    case AddressHashMode.SerializeP2WSH:
      return addressFromVersionHash(
        version,
        hashP2WSH(numSigs, publicKeys.map(serializePublicKey))
      );
  }
}
 
/**
 * Parses a principal string for either a standard principal or contract principal.
 * @param principalString - String in the format `{address}.{contractName}`
 * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G.example-contract"
 * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G"
 */
export function parsePrincipalString(
  principalString: string
): StandardPrincipal | ContractPrincipal {
  if (principalString.includes('.')) {
    const [address, contractName] = principalString.split('.');
    return createContractPrincipal(address, contractName);
  } else E{
    return createStandardPrincipal(principalString);
  }
}
 
export function createStandardPrincipal(addressString: string): StandardPrincipal {
  return {
    type: StacksMessageType.Principal,
    prefix: PostConditionPrincipalID.Standard,
    address: createAddress(addressString),
  };
}
 
export function createContractPrincipal(
  addressString: string,
  contractName: string
): ContractPrincipal {
  return {
    type: StacksMessageType.Principal,
    prefix: PostConditionPrincipalID.Contract,
    contractName: createLPString(contractName),
    address: createAddress(addressString),
  };
}
 
export function serializePrincipal(principal: PostConditionPrincipal): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.push(Uint8Array.from([principal.prefix]));
  bufferArray.push(serializeAddress(principal.address));
  if (principal.prefix === PostConditionPrincipalID.Contract) {
    bufferArray.push(serializeLPString(principal.contractName));
  }
  return bufferArray.concatBuffer();
}
 
export function deserializePrincipal(bufferReader: BufferReader): PostConditionPrincipal {
  const prefix = bufferReader.readUInt8Enum(PostConditionPrincipalID, _ => {
    throw new DeserializationError('Unexpected Principal payload type: ${n}');
  });
  const address = deserializeAddress(bufferReader);
  if (prefix === PostConditionPrincipalID.Standard) {
    return { type: StacksMessageType.Principal, prefix, address } as StandardPrincipal;
  }
  const contractName = deserializeLPString(bufferReader);
  return {
    type: StacksMessageType.Principal,
    prefix,
    address,
    contractName,
  } as ContractPrincipal;
}
 
export function codeBodyString(content: string): LengthPrefixedString {
  return createLPString(content, 4, 100000);
}
 
export interface MemoString {
  readonly type: StacksMessageType.MemoString;
  readonly content: string;
}
 
export function createMemoString(content: string): MemoString {
  Iif (content && exceedsMaxLengthBytes(content, MEMO_MAX_LENGTH_BYTES)) {
    throw new Error(`Memo exceeds maximum length of ${MEMO_MAX_LENGTH_BYTES.toString()} bytes`);
  }
  return { type: StacksMessageType.MemoString, content };
}
 
export function serializeMemoString(memoString: MemoString): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  const contentBuffer = utf8ToBytes(memoString.content);
  const paddedContent = rightPadHexToLength(bytesToHex(contentBuffer), MEMO_MAX_LENGTH_BYTES * 2);
  bufferArray.push(hexToBytes(paddedContent));
  return bufferArray.concatBuffer();
}
 
export function deserializeMemoString(bufferReader: BufferReader): MemoString {
  const buff = bufferReader.readBuffer(MEMO_MAX_LENGTH_BYTES);
  const indexOfEmpty = buff.indexOf(0x00);
  const content = bytesToUtf8(buff.slice(0, indexOfEmpty));
  return { type: StacksMessageType.MemoString, content };
}
 
/**
 * Parse a fully qualified string that identifies the token type.
 * @param id - String in the format `{address}.{contractName}::{assetName}`
 * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G.example-contract::example-token"
 */
export function parseAssetInfoString(id: string): AssetInfo {
  const [assetAddress, assetContractName, assetTokenName] = id.split(/\.|::/);
  return createAssetInfo(assetAddress, assetContractName, assetTokenName);
}
 
export function createAssetInfo(
  addressString: string,
  contractName: string,
  assetName: string
): AssetInfo {
  return {
    type: StacksMessageType.AssetInfo,
    address: createAddress(addressString),
    contractName: createLPString(contractName),
    assetName: createLPString(assetName),
  };
}
 
export function serializeAssetInfo(info: AssetInfo): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.push(serializeAddress(info.address));
  bufferArray.push(serializeLPString(info.contractName));
  bufferArray.push(serializeLPString(info.assetName));
  return bufferArray.concatBuffer();
}
 
export function deserializeAssetInfo(bufferReader: BufferReader): AssetInfo {
  return {
    type: StacksMessageType.AssetInfo,
    address: deserializeAddress(bufferReader),
    contractName: deserializeLPString(bufferReader),
    assetName: deserializeLPString(bufferReader),
  };
}
 
export interface LengthPrefixedList {
  readonly type: StacksMessageType.LengthPrefixedList;
  readonly lengthPrefixBytes: number;
  readonly values: StacksMessage[];
}
 
export function createLPList<T extends StacksMessage>(
  values: T[],
  lengthPrefixBytes?: number
): LengthPrefixedList {
  return {
    type: StacksMessageType.LengthPrefixedList,
    lengthPrefixBytes: lengthPrefixBytes || 4,
    values,
  };
}
 
export function serializeLPList(lpList: LengthPrefixedList): Uint8Array {
  const list = lpList.values;
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.appendHexString(intToHexString(list.length, lpList.lengthPrefixBytes));
  for (let index = 0; index < list.length; index++) {
    bufferArray.push(serializeStacksMessage(list[index]));
  }
  return bufferArray.concatBuffer();
}
 
export function deserializeLPList(
  bufferReader: BufferReader,
  type: StacksMessageType,
  lengthPrefixBytes?: number
): LengthPrefixedList {
  const length = hexStringToInt(bytesToHex(bufferReader.readBuffer(lengthPrefixBytes || 4)));
  const l: StacksMessage[] = [];
  for (let index = 0; index < length; index++) {
    switch (type) {
      case StacksMessageType.Address:
        l.push(deserializeAddress(bufferReader));
        break;
      case StacksMessageType.LengthPrefixedString:
        l.push(deserializeLPString(bufferReader));
        break;
      case StacksMessageType.MemoString:
        l.push(deserializeMemoString(bufferReader));
        break;
      case StacksMessageType.AssetInfo:
        l.push(deserializeAssetInfo(bufferReader));
        break;
      case StacksMessageType.PostCondition:
        l.push(deserializePostCondition(bufferReader));
        break;
      case StacksMessageType.PublicKey:
        l.push(deserializePublicKey(bufferReader));
        break;
      case StacksMessageType.TransactionAuthField:
        l.push(deserializeTransactionAuthField(bufferReader));
        break;
    }
  }
  return createLPList(l, lengthPrefixBytes);
}