Skip to content

Instantly share code, notes, and snippets.

@nakov
Created March 7, 2018 10:32
Show Gist options
  • Save nakov/85b1815d074a0e8bd01688002b53bcad to your computer and use it in GitHub Desktop.
Save nakov/85b1815d074a0e8bd01688002b53bcad to your computer and use it in GitHub Desktop.
Sign a transaction in JS
const CryptoJS = require("crypto-js");
const EC = require('elliptic').ec;
const secp256k1 = new EC('secp256k1');
function signData(data, privKey) {
let keyPair = secp256k1.keyFromPrivate(privKey);
let signature = keyPair.sign(data);
return [signature.r.toString(16), signature.s.toString(16)];
}
function verifySignature(data, publicKey, signature) {
let key = secp256k1.keyFromPublic(publicKey, 'hex');
let valid = key.verify(msg, {r: signature[0], s: signature[1]});
return valid;
}
class Transaction {
constructor(from,
to,
value,
fee,
dateCreated,
senderPubKey,
transactionDataHash,
senderSignature,
minedInBlockIndex,
transferSuccessful)
{
this.from = from; // Sender address: 40 hex digits
this.to = to; // Recipient address: 40 hex digits
this.value = value; // Transfer value: integer
this.fee = fee; // Mining fee: integer
this.dateCreated = dateCreated; // ISO-8601 string
this.senderPubKey = senderPubKey; // 65 hex digits
this.transactionDataHash = transactionDataHash; // 64 hex digits
// Calculate the transaction data hash if it is missing
if (this.transactionDataHash === undefined)
this.calculateDataHash();
this.senderSignature = senderSignature; // hex_number[2][64]
this.minedInBlockIndex = minedInBlockIndex; // integer
this.transferSuccessful = transferSuccessful; // bool
}
calculateDataHash() {
let tranData = {
'from': this.from,
'to': this.to,
'senderPubKey': this.senderPubKey,
'value': this.value,
'fee': this.fee,
'dateCreated': this.dateCreated
};
let tranDataJSON = JSON.stringify(tranData);
this.transactionDataHash = CryptoJS.SHA256(tranDataJSON).toString();
}
sign(privateKey) {
this.senderSignature = signData(
this.transactionDataHash, privateKey);
}
verifySignature() {
return verifySignature(this.transactionDataHash,
this.senderPubKey, this.senderSignature);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment