Bitcoin Programming: Signing & Verification

Signing & Verification
================

Previously i had to read 2-3 times the chapter 03 of this book 
*link*. Since i still dont quite to follow how to generate a Signature
over what i had learned on *Day 1*.

Ok, now i got it. That 4 informations will be shared are :
a. Signer, take the given message hash it, then signed it.
    secp256k1_sign(msg, private_key) the result is signature(r,s)
b. Verifier, secp256k1_verify(msg, signature(r,s), pub_key(x,y) )
c. validation would be the signature.r equals to calculation result
    of secp256k1_verify(msg, signature(r,s), pub_key(x,y) ).coordinate.x

In details:

# import everything and define a test runner function
from importlib import reload
from helper import run
import ecc
import helper
from ecc import FieldElement, Point
from ecc import S256Point, G, N
from helper import hash256

# Known by the recipent
e = int.from_bytes(hash256(b'BigF15h Bitcoin!'), 'big') 
pub_key = e*G
print("e", e)
print("G", G)
print("Pub Key", pub_key)

# coming from transaction/Verifier
z = int.from_bytes(hash256(b'Programming Bitcoin! !@#123'), 'big')

# recipent will give the coming transaction with signature of msg
k = int.from_bytes(hash256(b'salty!!!'), 'big')
r = (k*G).x.num

# calculate s ((z+re)/k)
k_inv = pow(k, N-2, N)
s = ((z + (r * e)) * k_inv) % N
signature = (r,s)
print("Signature", (r,s))

# verifier will take the signature and calc the X coordinate 
s_inv = pow(s, N-2, N)
u = z * s_inv % N
v = r * s_inv % N
print("Result %s -VS- %s" %((u*G + v*pub_key).x.num , r))
print((u*G + v*pub_key).x.num == r )

Output is:
e 63327681577723562747769265545410297333202711653950128229625713060151960359784
G S256Point(79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8)
Pub Key S256Point(7f2e6be75e81498579b9d4a9cc6b083e213a1451ccfa829905c7956677941512, 5f62a5fa67c5473f488b2e3b9cd441db920d6bed0bff7a75a75e4411a78f6035)
Signature (25505610420842915873925203803422491003907117588587179664204560073366201235605, 93778784595566421588754932431954263390104111319740456620902920392216802088652)
Result 25505610420842915873925203803422491003907117588587179664204560073366201235605 -VS- 25505610420842915873925203803422491003907117588587179664204560073366201235605
True

*/ jupyter notebook is hosted here 

Comments