bsn-chainmaker-sdk-py 1.0.0
BSN PCN Gateway SDK for Python - Chainmaker blockchain framework support
License: MIT
Requires Python: >=3.8
Keywords: bsn, chainmaker, bsnbase, bsn_sdk_py, bsn_sdk_python, blockchain, pcn, gateway

# SDK Direction for calling


## SDK in Python

## Installation Guide

### Requirements

- **Python Version:** Python 3.8 or higher
- Check your Python version:
```bash
python --version
```

### Using venv (Built-in Virtual Environment)

1. Create a virtual environment:
```bash
python -m venv myenv
```

2. Activate the virtual environment:
   - **Linux/macOS:**
   ```bash
   source myenv/bin/activate
   ```
   - **Windows:**
   ```bash
   myenv\Scripts\activate
   ```

3. Upgrade pip (recommended):
```bash
python -m pip install --upgrade pip
```

4. Install dependencies:
```bash
pip install -r requirements.txt
```

5. Deactivate the virtual environment (when done):
```bash
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