Created
October 20, 2023 00:13
-
-
Save rot13maxi/1fa230e648bd97b73e3418d17fe11981 to your computer and use it in GitHub Desktop.
standard ctv hash in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Transaction } from '@scure/btc-signer'; | |
import { Buffer } from 'buffer'; // You may need to import the appropriate library for Buffer | |
import { sha256 } from '@noble/hashes/sha256'; | |
function ser_compact_size(l: number): Buffer { | |
let r: Buffer = Buffer.from(''); | |
if (l < 253) { | |
r = Buffer.from([l]); | |
} else if (l < 0x10000) { | |
r = Buffer.concat([Buffer.from([253]), Buffer.from([l & 0xff, (l >> 8) & 0xff])]); | |
} else if (l < 0x100000000) { | |
r = Buffer.concat([ | |
Buffer.from([254]), | |
Buffer.from([l & 0xff, (l >> 8) & 0xff, (l >> 16) & 0xff, (l >> 24) & 0xff]), | |
]); | |
} else { | |
r = Buffer.concat([ | |
Buffer.from([255]), | |
Buffer.from([l & 0xff, (l >> 8) & 0xff, (l >> 16) & 0xff, (l >> 24) & 0xff]), | |
Buffer.from([l >> 32, (l >> 40) & 0xff, (l >> 48) & 0xff, (l >> 56) & 0xff]), | |
]); | |
} | |
return r; | |
} | |
function ser_string(s: Buffer): Buffer { | |
const length = s.length; | |
return Buffer.concat([ser_compact_size(length), s]); | |
} | |
function getStandardTemplateHash(transaction: Transaction, nIn: number): Buffer { | |
let r: Buffer = Buffer.from(''); | |
r = Buffer.concat([r, Buffer.from(transaction.version.toString(), 'binary')]); | |
r = Buffer.concat([r, Buffer.from(transaction.lockTime.toString(), 'binary')]); | |
const inputs = transaction.inputsLength; | |
for (let i = 0; i < inputs; i++) { | |
const input = transaction.getInput(i); | |
if (input.finalScriptSig) { | |
r = Buffer.concat([r, Buffer.from(input.finalScriptSig)]); | |
} | |
r = Buffer.concat([r, Buffer.from(input.sequence!.toString(), 'binary')]); | |
} | |
r = Buffer.concat([r, ser_compact_size(inputs)]); | |
const outputs = transaction.outputsLength; | |
for (let i = 0; i < outputs; i++) { | |
const output = transaction.getOutput(i); | |
r = Buffer.concat([r, Buffer.from(output.amount!.toString(), 'binary')]); | |
r = Buffer.concat([r, ser_string(Buffer.from(output.script!.toString(), 'binary'))]); | |
} | |
r = Buffer.concat([r, ser_compact_size(nIn.toString().length)]); | |
r = Buffer.concat([r, Buffer.from(nIn.toString(), 'binary')]); | |
return Buffer.from(sha256(Buffer.from(r))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment