Python Blockchain - Client Class


The Client class generates the private and public keys by using the built-in Python RSA algorithm. The interested reader may refer to this tutorial for the implementation of RSA. During the object initialization, we create private and public keys and store their values in the instance variable.

self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()

Note that you should never lose your private key. For record keeping, the generated private key may be copied on a secured external storage or you may simply write down the ASCII representation of it on a piece of paper.

The generated public key will be used as the client’s identity. For this, we define a property called identity that returns the HEX representation of the public key.

@property
   def identity(self):
      return
binascii.hexlify(self._public_key.exportKey(format='DER'))
.decode('ascii')

The identity is unique to each client and can be made publicly available. Anybody would be able to send virtual currency to you using this identity and it will get added to your wallet.

The full code for the Client class is shown here −

class Client:
   def __init__(self):
      random = Crypto.Random.new().read
      self._private_key = RSA.generate(1024, random)
      self._public_key = self._private_key.publickey()
      self._signer = PKCS1_v1_5.new(self._private_key)

   @property
   def identity(self):
      return
binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')

Testing Client

Now, we will write code that will illustrate how to use the Client class −

Dinesh = Client()
print (Dinesh.identity)

The above code creates an instance of Client and assigns it to the variable Dinesh. We print the public key of Dinesh by calling its identity method. The output is shown here −

30819f300d06092a864886f70d010101050003818d0030818902818100b547fafceeb131e07
0166a6b23fec473cce22c3f55c35ce535b31d4c74754fecd820aa94c1166643a49ea5f49f72
3181ff943eb3fdc5b2cb2db12d21c06c880ccf493e14dd3e93f3a9e175325790004954c34d3
c7bc2ccc9f0eb5332014937f9e49bca9b7856d351a553d9812367dc8f2ac734992a4e6a6ff6
6f347bd411d07f0203010001

Now, we let us move on to create a transaction in the next chapter.

Advertisements