Skip to main content

BSN PCN Gateway SDK for Python - Chainmaker blockchain framework support

Project description

SDK Direction for calling

SDK in Python

Installation Guide

Requirements

  • Python Version: Python 3.8 or higher
  • Check your Python version:
python --version

Using venv (Built-in Virtual Environment)

  1. Create a virtual environment:
python -m venv myenv
  1. Activate the virtual environment:

    • Linux/macOS:
    source myenv/bin/activate
    
    • Windows:
    myenv\Scripts\activate
    
  2. Upgrade pip (recommended):

python -m pip install --upgrade pip
  1. Install dependencies:
pip install -r requirements.txt
  1. Deactivate the virtual environment (when done):
deactivate

1. Before calling

DApp Parameters

DApp parameters are obtained from the Service Detail Page after the user participates in the app. Some parameters are set locally, which includes,

  • PCN gateway interface address: the calling address of the PCN (public city node) gateway
  • User number: the number of the user
  • Application number: number of participating applications
  • Public key: the public key of PCN gateway downloaded after the user participates in the DApp
  • Private key: A public key will be generated by BSN when DApps under Key-Trust Mode connects to the BSN successfully, and a private key will be generated corresponding to the public key uploaded for DApps under Public-Key-Upload Mode
  • Https certificate: the Https certificate used when the Https gateway interface is invoked
  • Organization ID (org_id): Organization ID for chainmaker, optional in Public mode

Local Parameters

  • Certificate Directory (mspDir): the directory used to store the user's private key and certificate generated by DApps under Public-Key-Upload Mode when the user's certificate registration is invoked. This parameter is used for non-trust mode transactions to store on-chain keys.

2. Preparation

Import the SDK package

Introduce the following package

from bsn_sdk_py.client.config import Config
from bsn_sdk_py.client.chainmaker import ChainmakerClient

Initialize config

An object can be initialized to store all the configuration information, which should be introduced at the time of invocation after being configured or read by the caller. In config 'Init', the basic information of DApp is retrieved. Please do not call this operation frequently because this interface will occupy your TPS and traffic. You can use a static object to store 'config' in the project when you need it.
When configuring the certificate, the certificate applied (that is, the certificate used for signing and verifying) is the direct certificate path, while the certificate for Https is the certificate root for the project. The file path to the directory is consistent with the previous example code.

	nodeApi = "" // PCN gateway address
	user_code:="" //User code
	app_code :="" //DApp code
	app_public_cert_path :="" //Public key path
	user_private_cert_path :="" //Private key path
	mspDir:="" //cert directory (used for non-trust mode transactions to store on-chain keys)
	httpcert :="" //httpscert
	org_id:="" //Organization ID (for chainmaker, optional in Public mode)
	c = Config(user_code, app_code, nodeApi, mspDir, httpcert,
                 app_public_cert_path, user_private_cert_path, org_id=org_id)

Initialize Client

Use the generated configuration object and call the following code to create a Client object to invoke the PCN gateway

    client = ChainmakerClient()
    client.set_config(c)

Call interface

Each gateway interface has encapsulated the parameter object of the request and response, which can be directly called just by assigning the value, and the operation of signing and verifying the signature has been realized in the function. The following is the call operation for the registered sub-user, and others are the same.

    # 密钥托管模式:用户注册
    client.user_register('hll4')
    
    # 密钥托管模式:交易
    client.req_chain_code(
        userName='hll4',
        contractAddress='contract001',
        funcName='set',
        funcParam='["key", "value"]'
    )
    
    # 公钥上传模式:用户注册
    client.user_enroll('hll4')
    
    # 公钥上传模式:交易
    client.sdk_trans(
        contractAddress='balance001',
        funcName='updateBalance',
        funcParam=[{"uint256": "10000"},{"address": "0xa166c92f4c8118905ad984919dc683a7bdb295c1"}],
        isQuery=False,
    )

Log

To get a more detailed processing log, configure a logger.

        import logging
        FORMAT = "%(asctime)s %(thread)d %(message)s"
        logging.basicConfig(filename='bsn_test.log', filemode='w',level=logging.INFO, format=FORMAT, datefmt="[%Y-%m-%d %H:%M:%S]")

3.Other instructions

Description of the user identity certificate for DApp under Public-Key-Upload Mode

Since the user certificate needed by DApp under Public-Key-Upload Mode when calling the PCN gateway for transaction needs to be generated by the user himself locally, the process is: registered user -> registered user certificate. In the operation of registering a user certificate, a pair of keys are generated locally. A CSR file (the certificate or the application file) can be exported through the key. Call the user certificate, acquire a valid certificate via the registraion interface to process the transaction initiated by DApp under the Key-Trust Mode. When setting CN in the CSR file, do not register Name directly, the Name is assembled by Name and AppCode in the format of 'nam@appcode'.
This operation is made in the function of GetCertificateRequest in bsn_sdk_py.client.chainmaker.entity.user_enroll.UserEnroll .

Storage of certificates only in the form of local files at present,

Naming rules:

      __stored cert__+ '\keystore\' + Name@AppCode + '_private.pem' 
      __stored cert__+ '\keystore\' + Name@AppCode + '_cert.pem'

About encryption

In order to facilitate data encryption and decryption in the on-BSN operation of data transaction, a symmetric encryption 'AES' algorithm is implemented in the SDK Symmetric encryption for 'AES' is specifically called as follows:

	secret = '9999999999999999'
	t = "hello world"
    bsn = BsnAES(secret)
    e = bsn.encrypt(t)  # Encryption
    d = bsn.decrypt(e)  # Decryption
    assert t == d

About private key

In BSN, the encryption algorithm of 'chainmaker' framework is ECDSA secp256r1. When a uer participates in the DApp under Public-Key-Upload Mode, a key of the corresponding encryption algorithm needs to be generated and uploaded.

Next is the description of how the key is generated. Keys are generated using 'openssl'.

Note: the following commands are executed in a Linux environment.

How the keys of ECDSA(secp256r1) are generated
  • Generate a private key.
openssl ecparam -name prime256v1 -genkey -out key.pem
  • Export the public key.
openssl ec -in key.pem -pubout -out pub.pem
  • Export the private key in pkcs8 format

Since it is convenient to use the key of pkcs8 format in some languages, you can export the pkcs8 format private key following the command below The private key used in this SDK is in the format of pkcs8

openssl pkcs8 -topk8 -inform PEM -in key.pem -outform PEM -nocrypt -out key_pkcs8.pem

Three files can be generated from the command above.
key.pem :Private key
pub.pem :Public key
key_pkcs8.pem :Private key in pkcs8 format

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bsn_chainmaker_sdk_py-1.0.0.tar.gz (48.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bsn_chainmaker_sdk_py-1.0.0-py3-none-any.whl (65.5 kB view details)

Uploaded Python 3

File details

Details for the file bsn_chainmaker_sdk_py-1.0.0.tar.gz.

File metadata

  • Download URL: bsn_chainmaker_sdk_py-1.0.0.tar.gz
  • Upload date:
  • Size: 48.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.8.0

File hashes

Hashes for bsn_chainmaker_sdk_py-1.0.0.tar.gz
Algorithm Hash digest
SHA256 155b39fafb40d5a114d8e18754f9bfef0621d97a004f3c15b53148e10d023b18
MD5 31d55e64a2d54ced0cc844d67d703110
BLAKE2b-256 0d4b64fb29157bdb02a738f0c754f569b142b23f338709d212f7c91030a4c8d4

See more details on using hashes here.

File details

Details for the file bsn_chainmaker_sdk_py-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for bsn_chainmaker_sdk_py-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b9848f3d8a81f6e735ed989c834fc3cd70d17e8ddb2e460ce96d4f00b37c3e99
MD5 4cd81d63cd1c90ebe804c6c7455a3b53
BLAKE2b-256 f8be46b74b3b500331fddda115373d650b2e951b36160561726c071985eed27e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page