Skip to content

Instantly share code, notes, and snippets.

@chafreaky
Created October 31, 2021 21:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chafreaky/09296ff58b937056d362b69c2ef59a47 to your computer and use it in GitHub Desktop.
Save chafreaky/09296ff58b937056d362b69c2ef59a47 to your computer and use it in GitHub Desktop.
DESO - Sign a transaction in nodejs given a seedHex and a txnHex
// Do `npm i elliptic sha256` before hand
const EC = require('elliptic').ec;
const sha256 = require('sha256');
function seedHexToPrivateKey(seedHex) {
const ec = new EC('secp256k1');
return ec.keyFromPrivate(seedHex);
}
const uvarint64ToBuf = (uint) => {
const result = [];
while (uint >= 0x80) {
result.push((uint & 0xff) | 0x80);
uint >>>= 7;
}
result.push(uint | 0);
return new Buffer.from(result);
};
function signTransaction(seedHex, transactionHex) {
const privateKey = seedHexToPrivateKey(seedHex);
const transactionBytes = new Buffer.from(transactionHex, 'hex');
const transactionHash = new Buffer.from(sha256.x2(transactionBytes), 'hex');
const signature = privateKey.sign(transactionHash);
const signatureBytes = new Buffer.from(signature.toDER());
const signatureLength = uvarint64ToBuf(signatureBytes.length);
const signedTransactionBytes = Buffer.concat([
transactionBytes.slice(0, -1),
signatureLength,
signatureBytes,
]);
return signedTransactionBytes.toString('hex');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment