Created
October 31, 2021 21:06
-
-
Save chafreaky/09296ff58b937056d362b69c2ef59a47 to your computer and use it in GitHub Desktop.
DESO - Sign a transaction in nodejs given a seedHex and a txnHex
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
// 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