Skip to content

Instantly share code, notes, and snippets.

@jdh7190
Created September 10, 2023 11:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdh7190/37edfef1c4c75bb79b3a636d781ed204 to your computer and use it in GitHub Desktop.
Save jdh7190/37edfef1c4c75bb79b3a636d781ed204 to your computer and use it in GitHub Desktop.
Unlock from hodlocker
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();
}
@jdh7190
Copy link
Author

jdh7190 commented Sep 10, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment