Created
September 10, 2023 11:14
-
-
Save jdh7190/37edfef1c4c75bb79b3a636d781ed204 to your computer and use it in GitHub Desktop.
Unlock from hodlocker
This file contains 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
const getUTXO = (rawtx, idx) => { | |
const bsvtx = new bsv.Transaction(rawtx); | |
return { | |
satoshis: bsvtx.outputs[idx].satoshis, | |
vout: idx, | |
txid: bsvtx.hash, | |
script: bsvtx.outputs[idx].script.toHex() | |
} | |
} | |
const getRawtx = async txid => { | |
const r = await fetch(`https://api.whatsonchain.com/v1/bsv/main/tx/${txid}/hex`); | |
const raw = await r.text(); | |
return raw; | |
} | |
const unlockToken = (txHex, inputIndex, lockTokenScript, satoshis, privkey) => { | |
const tx = new bsv.Transaction(txHex); | |
const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID; | |
const scriptCode = bsv.Script.fromHex(lockTokenScript); | |
const value = new bsv.crypto.BN(satoshis); | |
// create preImage of current transaction with valid nLockTime | |
const preimg = bsv.Transaction.sighash.sighashPreimage(tx, sighashType, inputIndex, scriptCode, value).toString('hex'); | |
let s; | |
if (privkey) { // sign transaction with private key tied to public key locked in script | |
s = bsv.Transaction.sighash.sign(tx, privkey, sighashType, inputIndex, scriptCode, value).toTxFormat(); | |
} | |
return bsv.Script.fromASM(`${s.toString('hex')} ${privkey.toPublicKey().toHex()} ${preimg}`).toHex(); | |
} | |
const unlockLock = async() => { | |
const txid = ''; | |
const rawtx = await getRawtx(txid); | |
const oIdx = 0; | |
const lockedUTXO = getUTXO(rawtx, oIdx); | |
const bsvtx = bsv.Transaction();; | |
bsvtx.addInput(new bsv.Transaction.Input({ | |
prevTxId: txid, | |
outputIndex: oIdx, | |
script: new bsv.Script() | |
}), bsv.Script(lockedUTXO.script), lockedUTXO.satoshis); | |
bsvtx.lockUntilBlockHeight(); // populate with block height after locked height | |
bsvtx.to('', lockedUTXO.satoshis - 1); // set receive address here | |
// WIF is m/0’/236’/0’/0/0 of RelayX Mnemonic | |
const solution = unlockToken(bsvtx.toString(), oIdx, lockedUTXO.script, lockedUTXO.satoshis, bsv.PrivateKey.fromWIF('')); | |
bsvtx.inputs[oIdx].setScript(solution) | |
console.log(bsvtx.toString()) | |
return bsvtx.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires bsv legacy library - https://github.com/moneybutton/bsv/tree/bsv-legacy