Add convenience method for signing transaction

This commit is contained in:
Mark Spanbroek 2021-06-29 15:17:53 +02:00
parent 1a0a96705b
commit b0babf9962
2 changed files with 9 additions and 0 deletions

View File

@ -67,6 +67,9 @@ func toBytes*(transaction: Transaction): seq[byte] =
func hash*(transaction: Transaction): TxHash = func hash*(transaction: Transaction): TxHash =
TxHash(sha256.digest(transaction.toBytes)) TxHash(sha256.digest(transaction.toBytes))
func sign*(key: PrivateKey, transaction: var Transaction) =
transaction.add(key.sign(transaction.hash.toBytes))
func hasValidSignature*(transaction: Transaction): bool = func hasValidSignature*(transaction: Transaction): bool =
if transaction.inputs.len == 0: if transaction.inputs.len == 0:
return false return false

View File

@ -55,6 +55,12 @@ suite "Transactions":
transaction.add(sig2) transaction.add(sig2)
check transaction.signature == aggregate(sig1, sig2) check transaction.signature == aggregate(sig1, sig2)
test "transaction can be signed by a private key":
let key = PrivateKey.example
var transaction = Transaction.example
key.sign(transaction)
check transaction.signature == key.sign(transaction.hash.toBytes)
test "transaction signature can be checked for validity": test "transaction signature can be checked for validity":
let genesis = !Transaction.init({alice: 32.u256, bob: 10.u256}) let genesis = !Transaction.init({alice: 32.u256, bob: 10.u256})
check not genesis.hasValidSignature() check not genesis.hasValidSignature()