js-bigchaindb-driver/src/transaction/signTransaction.js

36 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-06-12 16:57:29 +02:00
import { Buffer } from 'buffer'
import base58 from 'bs58'
import cc from 'five-bells-condition'
import clone from 'clone'
2017-04-26 15:58:19 +02:00
2017-06-12 16:57:29 +02:00
import serializeTransactionIntoCanonicalString from './serializeTransactionIntoCanonicalString'
2017-04-26 15:58:19 +02:00
/**
2017-05-03 01:02:50 +02:00
* @public
2017-04-26 15:58:19 +02:00
* Sign the given `transaction` with the given `privateKey`s, returning a new copy of `transaction`
* that's been signed.
* Note: Only generates Ed25519 Fulfillments. Thresholds and other types of Fulfillments are left as
* an exercise for the user.
* @param {object} transaction Transaction to sign. `transaction` is not modified.
* @param {...string} privateKeys Private keys associated with the issuers of the `transaction`.
* Looped through to iteratively sign any Input Fulfillments found in
* the `transaction`.
* @returns {object} The signed version of `transaction`.
*/
export default function signTransaction(transaction, ...privateKeys) {
2017-06-12 16:57:29 +02:00
const signedTx = clone(transaction)
2017-04-26 15:58:19 +02:00
signedTx.inputs.forEach((input, index) => {
2017-06-12 16:57:29 +02:00
const privateKey = privateKeys[index]
const privateKeyBuffer = new Buffer(base58.decode(privateKey))
const serializedTransaction = serializeTransactionIntoCanonicalString(transaction)
const ed25519Fulfillment = new cc.Ed25519Sha256()
2017-06-12 16:57:29 +02:00
ed25519Fulfillment.sign(new Buffer(serializedTransaction), privateKeyBuffer)
const fulfillmentUri = ed25519Fulfillment.serializeUri()
2017-04-26 15:58:19 +02:00
2017-06-12 16:57:29 +02:00
input.fulfillment = fulfillmentUri
})
2017-04-26 15:58:19 +02:00
2017-06-12 16:57:29 +02:00
return signedTx
2017-04-26 15:58:19 +02:00
}