All files / src/transactions authorization.ts

89.22% Statements 207/232
74.6% Branches 47/63
87.5% Functions 35/40
89.68% Lines 200/223

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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779            12x   12x               12x                         12x                               22x 12x   12x                                 12x 92x 92x       92x           12x 117x           12x 117x 117x 117x     12x 35x         12x                             12x       48x             12x 25x       8x 7x 7x   1x 1x   8x   17x 15x   2x   17x 17x     25x     12x 22x           6x         1x         13x         2x                                                                                     12x             59x 59x       59x                   12x             8x     8x   8x                   12x     313x       49x 49x 49x   49x 38x   11x                   12x     100x 100x 100x 100x 100x 100x 100x 100x     12x     22x 22x 22x 22x 22x   22x 22x   22x   22x 22x     12x       20x 20x 20x   20x       20x           20x 20x                   12x       9x 9x 9x   9x     9x 9x   9x     7x 7x   15x 15x 15x   15x       9x               9x     9x                   12x 122x 100x   22x       12x 29x       29x 20x   9x       12x                       62x   62x             62x   62x       62x                       62x   62x       62x   62x 62x       62x     12x                   49x   49x 49x 49x   49x           12x               13x   13x       13x   13x             18x           18x 18x 18x 18x               10x 8x   2x                 8x                 8x   8x         8x               2x 2x 2x 2x   2x         2x 2x 2x   4x 4x               4x 4x   4x 4x   4x   6x     2x           2x     2x           2x         2x                               12x 74x           12x       31x                 12x 49x     31x   18x                 12x     4x   6x           12x                                 12x                 12x                       12x                       12x                               12x 92x 92x       65x 65x   27x 27x 27x     92x     12x 22x             16x 16x   6x 6x 6x      
import {
  AddressHashMode,
  AuthType,
  MultiSigHashMode,
  PubKeyEncoding,
  SingleSigHashMode,
} from './common/constants';
 
import { leftPadHex, txidFromData } from './common/utils';
 
import {
  addressFromPublicKeys,
  createEmptyAddress,
  createLPList,
  deserializeLPList,
  serializeLPList,
} from './types';
 
import {
  compressPublicKey,
  createStacksPublicKey,
  deserializePublicKey,
  getPublicKeyFromStacksPrivateKey,
  isCompressed,
  publicKeyFromSignature,
  serializePublicKey,
  signWithKey,
  StacksPrivateKey,
  StacksPublicKey,
} from './keys';
 
import {
  BufferArray,
  BufferReader,
  bytesToHex,
  cloneDeep,
  hexToBytes,
  IntegerType,
  writeUInt16BE,
  DeserializationError,
  SerializationError,
  SigningError,
  intToBigInt,
  intToBytes,
  concatByteArrays,
} from 'micro-stacks/common';
import { RECOVERABLE_ECDSA_SIG_LENGTH_BYTES, StacksMessageType } from 'micro-stacks/clarity';
 
export abstract class Deserializable {
  abstract serialize(): Uint8Array;
 
  abstract deserialize(bufferReader: BufferReader): void;
 
  static deserialize<T extends Deserializable>(this: new () => T, bufferReader: BufferReader): T {
    const message = new this();
    message.deserialize(bufferReader);
    return message;
  }
}
 
export interface MessageSignature {
  readonly type: StacksMessageType.MessageSignature;
  data: string;
}
 
export function createMessageSignature(signature: string): MessageSignature {
  const length = hexToBytes(signature).byteLength;
  Iif (length != RECOVERABLE_ECDSA_SIG_LENGTH_BYTES) {
    throw Error('Invalid signature');
  }
 
  return {
    type: StacksMessageType.MessageSignature,
    data: signature,
  };
}
 
export function emptyMessageSignature(): MessageSignature {
  return {
    type: StacksMessageType.MessageSignature,
    data: bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES).fill(0x00)),
  };
}
 
export function serializeMessageSignature(messageSignature: MessageSignature): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.appendHexString(messageSignature.data);
  return bufferArray.concatBuffer();
}
 
export function deserializeMessageSignature(bufferReader: BufferReader): MessageSignature {
  return createMessageSignature(
    bytesToHex(bufferReader.readBuffer(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
  );
}
 
enum AuthFieldType {
  PublicKeyCompressed = 0x00,
  PublicKeyUncompressed = 0x01,
  SignatureCompressed = 0x02,
  SignatureUncompressed = 0x03,
}
 
export type TransactionAuthFieldContents = StacksPublicKey | MessageSignature;
 
export interface TransactionAuthField {
  type: StacksMessageType.TransactionAuthField;
  pubKeyEncoding: PubKeyEncoding;
  contents: TransactionAuthFieldContents;
}
 
export function createTransactionAuthField(
  pubKeyEncoding: PubKeyEncoding,
  contents: TransactionAuthFieldContents
): TransactionAuthField {
  return {
    pubKeyEncoding,
    type: StacksMessageType.TransactionAuthField,
    contents,
  };
}
 
export function serializeTransactionAuthField(field: TransactionAuthField): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
 
  switch (field.contents.type) {
    case StacksMessageType.PublicKey:
      if (field.pubKeyEncoding == PubKeyEncoding.Compressed) {
        bufferArray.appendByte(AuthFieldType.PublicKeyCompressed);
        bufferArray.push(serializePublicKey(field.contents));
      } else {
        bufferArray.appendByte(AuthFieldType.PublicKeyUncompressed);
        bufferArray.push(serializePublicKey(compressPublicKey(field.contents.data)));
      }
      break;
    case StacksMessageType.MessageSignature:
      if (field.pubKeyEncoding == PubKeyEncoding.Compressed) {
        bufferArray.appendByte(AuthFieldType.SignatureCompressed);
      } else {
        bufferArray.appendByte(AuthFieldType.SignatureUncompressed);
      }
      bufferArray.push(serializeMessageSignature(field.contents));
      break;
  }
 
  return bufferArray.concatBuffer();
}
 
export function deserializeTransactionAuthField(bufferReader: BufferReader): TransactionAuthField {
  const authFieldType = bufferReader.readUInt8Enum(AuthFieldType, n => {
    throw new DeserializationError(`Could not read ${n} as AuthFieldType`);
  });
 
  switch (authFieldType) {
    case AuthFieldType.PublicKeyCompressed:
      return createTransactionAuthField(
        PubKeyEncoding.Compressed,
        deserializePublicKey(bufferReader)
      );
    case AuthFieldType.PublicKeyUncompressed:
      return createTransactionAuthField(
        PubKeyEncoding.Uncompressed,
        deserializePublicKey(bufferReader)
      );
    case AuthFieldType.SignatureCompressed:
      return createTransactionAuthField(
        PubKeyEncoding.Compressed,
        deserializeMessageSignature(bufferReader)
      );
    case AuthFieldType.SignatureUncompressed:
      return createTransactionAuthField(
        PubKeyEncoding.Uncompressed,
        deserializeMessageSignature(bufferReader)
      );
    default:
      throw new Error(`Unknown auth field type: ${JSON.stringify(authFieldType)}`);
  }
}
 
export interface SingleSigSpendingCondition {
  hashMode: SingleSigHashMode;
  signer: string;
  nonce: bigint;
  fee: bigint;
  keyEncoding: PubKeyEncoding;
  signature: MessageSignature;
}
 
export interface SingleSigSpendingConditionOpts
  extends Omit<SingleSigSpendingCondition, 'nonce' | 'fee'> {
  nonce: IntegerType;
  fee: IntegerType;
}
 
export interface MultiSigSpendingCondition {
  hashMode: MultiSigHashMode;
  signer: string;
  nonce: bigint;
  fee: bigint;
  fields: TransactionAuthField[];
  signaturesRequired: number;
}
 
export interface MultiSigSpendingConditionOpts
  extends Omit<MultiSigSpendingCondition, 'nonce' | 'fee'> {
  nonce: IntegerType;
  fee: IntegerType;
}
 
export type SpendingCondition = SingleSigSpendingCondition | MultiSigSpendingCondition;
 
export type SpendingConditionOpts = SingleSigSpendingConditionOpts | MultiSigSpendingConditionOpts;
 
export function createSingleSigSpendingCondition(
  hashMode: SingleSigHashMode,
  pubKey: string,
  nonce: IntegerType,
  fee: IntegerType
): SingleSigSpendingCondition {
  // address version arg doesn't matter for signer hash generation
  const signer = addressFromPublicKeys(0, hashMode, 1, [createStacksPublicKey(pubKey)]).hash160;
  const keyEncoding = isCompressed(createStacksPublicKey(pubKey))
    ? PubKeyEncoding.Compressed
    : PubKeyEncoding.Uncompressed;
 
  return {
    hashMode,
    signer,
    nonce: intToBigInt(nonce, false),
    fee: intToBigInt(fee, false),
    keyEncoding,
    signature: emptyMessageSignature(),
  };
}
 
export function createMultiSigSpendingCondition(
  hashMode: MultiSigHashMode,
  numSigs: number,
  pubKeys: string[],
  nonce: IntegerType,
  fee: IntegerType
): MultiSigSpendingCondition {
  const stacksPublicKeys = pubKeys.map(createStacksPublicKey);
 
  // address version arg doesn't matter for signer hash generation
  const signer = addressFromPublicKeys(0, hashMode, numSigs, stacksPublicKeys).hash160;
 
  return {
    hashMode,
    signer,
    nonce: intToBigInt(nonce, false),
    fee: intToBigInt(fee, false),
    fields: [],
    signaturesRequired: numSigs,
  };
}
 
export function isSingleSig(
  condition: SpendingConditionOpts
): condition is SingleSigSpendingConditionOpts {
  return 'signature' in condition;
}
 
function clearCondition(condition: SpendingConditionOpts): SpendingCondition {
  const cloned = cloneDeep(condition);
  cloned.nonce = 0;
  cloned.fee = 0;
 
  if (isSingleSig(cloned)) {
    cloned.signature = emptyMessageSignature();
  } else {
    cloned.fields = [];
  }
 
  return {
    ...cloned,
    nonce: BigInt(0),
    fee: BigInt(0),
  };
}
 
export function serializeSingleSigSpendingCondition(
  condition: SingleSigSpendingConditionOpts
): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.appendByte(condition.hashMode);
  bufferArray.appendHexString(condition.signer);
  bufferArray.push(intToBytes(condition.nonce, false, 8));
  bufferArray.push(intToBytes(condition.fee, false, 8));
  bufferArray.appendByte(condition.keyEncoding);
  bufferArray.push(serializeMessageSignature(condition.signature));
  return bufferArray.concatBuffer();
}
 
export function serializeMultiSigSpendingCondition(
  condition: MultiSigSpendingConditionOpts
): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.appendByte(condition.hashMode);
  bufferArray.appendHexString(condition.signer);
  bufferArray.push(intToBytes(condition.nonce, false, 8));
  bufferArray.push(intToBytes(condition.fee, false, 8));
 
  const fields = createLPList(condition.fields);
  bufferArray.push(serializeLPList(fields));
 
  const numSigs = new Uint8Array(2);
  writeUInt16BE(numSigs, condition.signaturesRequired, 0);
  bufferArray.push(numSigs);
  return bufferArray.concatBuffer();
}
 
export function deserializeSingleSigSpendingCondition(
  hashMode: SingleSigHashMode,
  bufferReader: BufferReader
): SingleSigSpendingCondition {
  const signer = bytesToHex(bufferReader.readBuffer(20));
  const nonce = BigInt('0x' + bytesToHex(bufferReader.readBuffer(8)));
  const fee = BigInt('0x' + bytesToHex(bufferReader.readBuffer(8)));
 
  const keyEncoding = bufferReader.readUInt8Enum(PubKeyEncoding, n => {
    throw new DeserializationError(`Could not parse ${n} as PubKeyEncoding`);
  });
 
  Iif (hashMode === AddressHashMode.SerializeP2WPKH && keyEncoding != PubKeyEncoding.Compressed) {
    throw new DeserializationError(
      'Failed to parse singlesig spending condition: incomaptible hash mode and key encoding'
    );
  }
 
  const signature = deserializeMessageSignature(bufferReader);
  return {
    hashMode,
    signer,
    nonce,
    fee,
    keyEncoding,
    signature,
  };
}
 
export function deserializeMultiSigSpendingCondition(
  hashMode: MultiSigHashMode,
  bufferReader: BufferReader
): MultiSigSpendingCondition {
  const signer = bytesToHex(bufferReader.readBuffer(20));
  const nonce = BigInt('0x' + bytesToHex(bufferReader.readBuffer(8)));
  const fee = BigInt('0x' + bytesToHex(bufferReader.readBuffer(8)));
 
  const fields = deserializeLPList(bufferReader, StacksMessageType.TransactionAuthField)
    .values as TransactionAuthField[];
 
  let haveUncompressed = false;
  let numSigs = 0;
 
  for (const field of fields) {
    switch (field.contents.type) {
      case StacksMessageType.PublicKey:
        Iif (!isCompressed(field.contents)) haveUncompressed = true;
        break;
      case StacksMessageType.MessageSignature:
        if (field.pubKeyEncoding === PubKeyEncoding.Uncompressed) haveUncompressed = true;
        numSigs += 1;
        Iif (numSigs === 65536)
          throw new TypeError('Failed to parse multisig spending condition: too many signatures');
        break;
    }
  }
 
  const signaturesRequired = bufferReader.readUInt16BE();
 
  // Partially signed multi-sig tx can be serialized and deserialized without exception (Incorrect number of signatures)
  // No need to check numSigs !== signaturesRequired to throw Incorrect number of signatures error
 
  // Uncompressed keys are incompatible with BIP067 @see https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki
  // SerializeP2SH would allow it, but it does not follow the standard
  // SerializeP2WSH (segwit) does _not_ allow for it
  Iif (haveUncompressed && hashMode === AddressHashMode.SerializeP2WSH)
    throw new TypeError('Public keys must be compressed for segwit');
 
  return {
    hashMode,
    signer,
    nonce,
    fee,
    fields,
    signaturesRequired,
  };
}
 
export function serializeSpendingCondition(condition: SpendingConditionOpts): Uint8Array {
  if (isSingleSig(condition)) {
    return serializeSingleSigSpendingCondition(condition);
  } else {
    return serializeMultiSigSpendingCondition(condition);
  }
}
 
export function deserializeSpendingCondition(bufferReader: BufferReader): SpendingCondition {
  const hashMode = bufferReader.readUInt8Enum(AddressHashMode, n => {
    throw new DeserializationError(`Could not parse ${n} as AddressHashMode`);
  });
 
  if (hashMode === AddressHashMode.SerializeP2PKH || hashMode === AddressHashMode.SerializeP2WPKH) {
    return deserializeSingleSigSpendingCondition(hashMode, bufferReader);
  } else {
    return deserializeMultiSigSpendingCondition(hashMode, bufferReader);
  }
}
 
export function makeSigHashPreSign(
  curSigHash: string,
  authType: AuthType,
  fee: IntegerType,
  nonce: IntegerType
): string {
  // new hash combines the previous hash and all the new data this signature will add. This
  // includes:
  // * the previous hash
  // * the auth flag
  // * the tx fee (big-endian 8-byte number)
  // * nonce (big-endian 8-byte number)
  const hashLength = 32 + 1 + 8 + 8;
 
  const sigHash = [
    hexToBytes(curSigHash),
    Uint8Array.from([authType]),
    intToBytes(fee, false, 8),
    intToBytes(nonce, false, 8),
  ];
 
  const buff = concatByteArrays(sigHash);
 
  Iif (buff.byteLength !== hashLength) {
    throw Error('Invalid signature hash length');
  }
 
  return txidFromData(buff);
}
 
function makeSigHashPostSign(
  curSigHash: string,
  pubKey: StacksPublicKey,
  signature: MessageSignature
): string {
  // new hash combines the previous hash and all the new data this signature will add.  This
  // includes:
  // * the public key compression flag
  // * the signature
  const hashLength = 32 + 1 + RECOVERABLE_ECDSA_SIG_LENGTH_BYTES;
 
  const pubKeyEncoding = isCompressed(pubKey)
    ? PubKeyEncoding.Compressed
    : PubKeyEncoding.Uncompressed;
 
  const sigHash = curSigHash + leftPadHex(pubKeyEncoding.toString(16)) + signature.data;
 
  const sigHashBuffer = hexToBytes(sigHash);
  Iif (sigHashBuffer.byteLength > hashLength) {
    throw Error('Invalid signature hash length');
  }
 
  return txidFromData(sigHashBuffer);
}
 
export async function nextSignature(
  curSigHash: string,
  authType: AuthType,
  fee: IntegerType,
  nonce: IntegerType,
  privateKey: StacksPrivateKey
): Promise<{
  nextSig: MessageSignature;
  nextSigHash: string;
}> {
  const sigHashPreSign = makeSigHashPreSign(curSigHash, authType, fee, nonce);
 
  const signature = await signWithKey(privateKey, sigHashPreSign);
  const publicKey = getPublicKeyFromStacksPrivateKey(privateKey);
  const nextSigHash = makeSigHashPostSign(sigHashPreSign, publicKey, signature);
 
  return {
    nextSig: signature,
    nextSigHash,
  };
}
 
export function nextVerification(
  initialSigHash: string,
  authType: AuthType,
  fee: IntegerType,
  nonce: IntegerType,
  pubKeyEncoding: PubKeyEncoding,
  signature: MessageSignature
) {
  const sigHashPreSign = makeSigHashPreSign(initialSigHash, authType, fee, nonce);
 
  const publicKey = createStacksPublicKey(
    publicKeyFromSignature(sigHashPreSign, signature, pubKeyEncoding)
  );
 
  const nextSigHash = makeSigHashPostSign(sigHashPreSign, publicKey, signature);
 
  return {
    pubKey: publicKey,
    nextSigHash,
  };
}
 
function newInitialSigHash(): SpendingCondition {
  const spendingCondition = createSingleSigSpendingCondition(
    AddressHashMode.SerializeP2PKH,
    '',
    0,
    0
  );
  spendingCondition.signer = createEmptyAddress().hash160;
  spendingCondition.keyEncoding = PubKeyEncoding.Compressed;
  spendingCondition.signature = emptyMessageSignature();
  return spendingCondition;
}
 
function verify(
  condition: SpendingConditionOpts,
  initialSigHash: string,
  authType: AuthType
): string {
  if (isSingleSig(condition)) {
    return verifySingleSig(condition, initialSigHash, authType);
  } else {
    return verifyMultiSig(condition, initialSigHash, authType);
  }
}
 
function verifySingleSig(
  condition: SingleSigSpendingConditionOpts,
  initialSigHash: string,
  authType: AuthType
): string {
  const { nextSigHash, pubKey } = nextVerification(
    initialSigHash,
    authType,
    condition.fee,
    condition.nonce,
    condition.keyEncoding,
    condition.signature
  );
 
  const addrBytes = addressFromPublicKeys(0, condition.hashMode, 1, [pubKey]).hash160;
 
  Iif (addrBytes !== condition.signer)
    throw new TypeError(
      `Signer hash does not equal hash of public key(s): ${addrBytes} != ${condition.signer}`
    );
 
  return nextSigHash;
}
 
function verifyMultiSig(
  condition: MultiSigSpendingConditionOpts,
  initialSigHash: string,
  authType: AuthType
): string {
  const publicKeys: StacksPublicKey[] = [];
  let curSigHash = initialSigHash;
  let haveUncompressed = false;
  let numSigs = 0;
 
  for (const field of condition.fields) {
    let foundPubKey: StacksPublicKey;
 
    switch (field.contents.type) {
      case StacksMessageType.PublicKey:
        if (!isCompressed(field.contents)) haveUncompressed = true;
        foundPubKey = field.contents;
        break;
      case StacksMessageType.MessageSignature:
        if (field.pubKeyEncoding === PubKeyEncoding.Uncompressed) haveUncompressed = true;
        const { pubKey, nextSigHash } = nextVerification(
          curSigHash,
          authType,
          condition.fee,
          condition.nonce,
          field.pubKeyEncoding,
          field.contents
        );
        curSigHash = nextSigHash;
        foundPubKey = pubKey;
 
        numSigs += 1;
        Iif (numSigs === 65536) throw new TypeError('Too many signatures');
 
        break;
    }
    publicKeys.push(foundPubKey);
  }
 
  Iif (numSigs !== condition.signaturesRequired)
    throw new TypeError('Incorrect number of signatures');
 
  // Uncompressed keys are incompatible with BIP067 @see https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki
  // SerializeP2SH would allow it, but it does not follow the standard
  // SerializeP2WSH (segwit) does _not_ allow for it
  Iif (haveUncompressed && condition.hashMode === AddressHashMode.SerializeP2WSH)
    throw new TypeError('Uncompressed keys are not allowed in this hash mode');
 
  const addrBytes = addressFromPublicKeys(
    0,
    condition.hashMode,
    condition.signaturesRequired,
    publicKeys
  ).hash160;
  Iif (addrBytes !== condition.signer)
    throw new TypeError(
      `Signer hash does not equal hash of public key(s): ${addrBytes} != ${condition.signer}`
    );
 
  return curSigHash;
}
 
export type Authorization = StandardAuthorization | SponsoredAuthorization;
 
export interface StandardAuthorization {
  authType: AuthType.Standard;
  spendingCondition: SpendingCondition;
}
 
export interface SponsoredAuthorization {
  authType: AuthType.Sponsored;
  spendingCondition: SpendingCondition;
  sponsorSpendingCondition: SpendingCondition;
}
 
export function createStandardAuth(spendingCondition: SpendingCondition): StandardAuthorization {
  return {
    authType: AuthType.Standard,
    spendingCondition,
  };
}
 
export function createSponsoredAuth(
  spendingCondition: SpendingCondition,
  sponsorSpendingCondition?: SpendingCondition
): Authorization {
  return {
    authType: AuthType.Sponsored,
    spendingCondition,
    sponsorSpendingCondition: sponsorSpendingCondition
      ? sponsorSpendingCondition
      : createSingleSigSpendingCondition(AddressHashMode.SerializeP2PKH, '0'.repeat(66), 0, 0),
  };
}
 
export function intoInitialSighashAuth(auth: Authorization): Authorization {
  if (auth.spendingCondition) {
    switch (auth.authType) {
      case AuthType.Standard:
        return createStandardAuth(clearCondition(auth.spendingCondition));
      case AuthType.Sponsored:
        return createSponsoredAuth(clearCondition(auth.spendingCondition), newInitialSigHash());
      default:
        throw new SigningError('Unexpected authorization type for signing');
    }
  }
 
  throw new Error('Authorization missing SpendingCondition');
}
 
export function verifyOrigin(auth: Authorization, initialSigHash: string): string {
  switch (auth.authType) {
    case AuthType.Standard:
      return verify(auth.spendingCondition, initialSigHash, AuthType.Standard);
    case AuthType.Sponsored:
      return verify(auth.spendingCondition, initialSigHash, AuthType.Standard);
    default:
      throw new SigningError('Invalid origin auth type');
  }
}
 
export function setFee(auth: Authorization, amount: IntegerType): Authorization {
  switch (auth.authType) {
    case AuthType.Standard:
      const spendingCondition = {
        ...auth.spendingCondition,
        fee: intToBigInt(amount, false),
      };
      return { ...auth, spendingCondition };
    case AuthType.Sponsored:
      const sponsorSpendingCondition = {
        ...auth.sponsorSpendingCondition,
        fee: intToBigInt(amount, false),
      };
      return { ...auth, sponsorSpendingCondition };
  }
}
 
export function getFee(auth: Authorization): bigint {
  switch (auth.authType) {
    case AuthType.Standard:
      return auth.spendingCondition.fee;
    case AuthType.Sponsored:
      return auth.sponsorSpendingCondition.fee;
  }
}
 
export function setNonce(auth: Authorization, nonce: IntegerType): Authorization {
  const spendingCondition = {
    ...auth.spendingCondition,
    nonce: intToBigInt(nonce, false),
  };
 
  return {
    ...auth,
    spendingCondition,
  };
}
 
export function setSponsorNonce(auth: SponsoredAuthorization, nonce: IntegerType): Authorization {
  const sponsorSpendingCondition = {
    ...auth.sponsorSpendingCondition,
    nonce: intToBigInt(nonce, false),
  };
 
  return {
    ...auth,
    sponsorSpendingCondition,
  };
}
 
export function setSponsor(
  auth: SponsoredAuthorization,
  sponsorSpendingCondition: SpendingConditionOpts
): Authorization {
  const sc = {
    ...sponsorSpendingCondition,
    nonce: intToBigInt(sponsorSpendingCondition.nonce, false),
    fee: intToBigInt(sponsorSpendingCondition.fee, false),
  };
 
  return {
    ...auth,
    sponsorSpendingCondition: sc,
  };
}
 
export function serializeAuthorization(auth: Authorization): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.appendByte(auth.authType);
 
  switch (auth.authType) {
    case AuthType.Standard:
      bufferArray.push(serializeSpendingCondition(auth.spendingCondition));
      break;
    case AuthType.Sponsored:
      bufferArray.push(serializeSpendingCondition(auth.spendingCondition));
      bufferArray.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
      break;
  }
 
  return bufferArray.concatBuffer();
}
 
export function deserializeAuthorization(bufferReader: BufferReader) {
  const authType = bufferReader.readUInt8Enum(AuthType, n => {
    throw new DeserializationError(`Could not parse ${n} as AuthType`);
  });
 
  let spendingCondition;
  switch (authType) {
    case AuthType.Standard:
      spendingCondition = deserializeSpendingCondition(bufferReader);
      return createStandardAuth(spendingCondition);
    case AuthType.Sponsored:
      spendingCondition = deserializeSpendingCondition(bufferReader);
      const sponsorSpendingCondition = deserializeSpendingCondition(bufferReader);
      return createSponsoredAuth(spendingCondition, sponsorSpendingCondition);
  }
}