|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright the fabric-chaincode-python contributors. All rights reserved. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +""" |
| 6 | +Token Chaincode Example (CCAAS) |
| 7 | +
|
| 8 | +This is a simple token transfer chaincode that demonstrates: |
| 9 | +- Token initialization (minting) |
| 10 | +- Balance queries |
| 11 | +- Token transfers between accounts |
| 12 | +- State management with the Fabric ledger |
| 13 | +
|
| 14 | +Deploy this as a Chaincode-as-a-Service (CCAAS) in Fabric. |
| 15 | +""" |
| 16 | + |
| 17 | +import sys |
| 18 | +import logging |
| 19 | + |
| 20 | +from src.fabric_shim.interfaces import Chaincode, ChaincodeStubInterface |
| 21 | +from src.fabric_shim.server import start |
| 22 | +from src.fabric_shim.response import ResponseCode |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | +logging.basicConfig(level=logging.DEBUG) |
| 26 | + |
| 27 | + |
| 28 | +class TokenChaincode(Chaincode): |
| 29 | + """Simple token management chaincode""" |
| 30 | + |
| 31 | + async def init(self, stub: ChaincodeStubInterface): |
| 32 | + """ |
| 33 | + Chaincode initialization - issues initial tokens to accounts |
| 34 | + |
| 35 | + Args: |
| 36 | + stub: ChaincodeStubInterface for ledger access |
| 37 | + |
| 38 | + Returns: |
| 39 | + Success or error response |
| 40 | + """ |
| 41 | + logger.info("=== TokenChaincode Init ===") |
| 42 | + try: |
| 43 | + # Initialize token balances for test accounts |
| 44 | + await stub.put_state('tommy', b'1000') # Issue 1000 tokens to tommy |
| 45 | + await stub.put_state('jerry', b'1000') # Issue 1000 tokens to jerry |
| 46 | + |
| 47 | + logger.info("Token initialization successful") |
| 48 | + return ResponseCode.SUCCESS, b'init ok' |
| 49 | + except Exception as e: |
| 50 | + logger.error(f"Error during init: {str(e)}") |
| 51 | + return ResponseCode.ERROR, str(e).encode() |
| 52 | + |
| 53 | + async def invoke(self, stub: ChaincodeStubInterface): |
| 54 | + """ |
| 55 | + Chaincode invocation handler - routes to appropriate function |
| 56 | + |
| 57 | + Args: |
| 58 | + stub: ChaincodeStubInterface for ledger access |
| 59 | + |
| 60 | + Returns: |
| 61 | + Response from the invoked function |
| 62 | + """ |
| 63 | + logger.info("=== TokenChaincode Invoke ===") |
| 64 | + try: |
| 65 | + fcn, args = stub.get_function_and_parameters() |
| 66 | + logger.info(f"Invoking function: {fcn} with args: {args}") |
| 67 | + |
| 68 | + if fcn == 'reset': |
| 69 | + return await self.init(stub) |
| 70 | + elif fcn == 'balance': |
| 71 | + if len(args) < 1: |
| 72 | + return ResponseCode.ERROR, b'balance requires 1 argument: account' |
| 73 | + return await self.balance(stub, args[0]) |
| 74 | + elif fcn == 'transfer': |
| 75 | + if len(args) < 3: |
| 76 | + return ResponseCode.ERROR, b'transfer requires 3 arguments: from, to, amount' |
| 77 | + return await self.transfer(stub, args[0], args[1], args[2]) |
| 78 | + else: |
| 79 | + return ResponseCode.ERROR, f'method {fcn} not supported'.encode() |
| 80 | + |
| 81 | + except Exception as e: |
| 82 | + logger.error(f"Error during invoke: {str(e)}") |
| 83 | + return ResponseCode.ERROR, str(e).encode() |
| 84 | + |
| 85 | + async def balance(self, stub: ChaincodeStubInterface, account: str): |
| 86 | + """ |
| 87 | + Query the balance of an account |
| 88 | + |
| 89 | + Args: |
| 90 | + stub: ChaincodeStubInterface for ledger access |
| 91 | + account: Account name to query |
| 92 | + |
| 93 | + Returns: |
| 94 | + Balance information |
| 95 | + """ |
| 96 | + logger.info(f"Querying balance for account: {account}") |
| 97 | + try: |
| 98 | + value = await stub.get_state(account) |
| 99 | + if not value: |
| 100 | + return ResponseCode.ERROR, f'account {account} not found'.encode() |
| 101 | + |
| 102 | + logger.info(f"Balance for {account}: {value.decode()}") |
| 103 | + return ResponseCode.SUCCESS, b'balance => ' + value |
| 104 | + except Exception as e: |
| 105 | + logger.error(f"Error querying balance: {str(e)}") |
| 106 | + return ResponseCode.ERROR, str(e).encode() |
| 107 | + |
| 108 | + async def transfer(self, stub: ChaincodeStubInterface, owner: str, to: str, value: str): |
| 109 | + """ |
| 110 | + Transfer tokens from one account to another |
| 111 | + |
| 112 | + Args: |
| 113 | + stub: ChaincodeStubInterface for ledger access |
| 114 | + owner: Source account |
| 115 | + to: Destination account |
| 116 | + value: Amount to transfer |
| 117 | + |
| 118 | + Returns: |
| 119 | + Success or error response |
| 120 | + """ |
| 121 | + logger.info(f"Transferring {value} tokens from {owner} to {to}") |
| 122 | + try: |
| 123 | + value = int(value) |
| 124 | + |
| 125 | + # Get owner balance |
| 126 | + owner_balance_bytes = await stub.get_state(owner) |
| 127 | + if not owner_balance_bytes: |
| 128 | + return ResponseCode.ERROR, f'account {owner} not found'.encode() |
| 129 | + |
| 130 | + owner_balance = int(owner_balance_bytes.decode()) |
| 131 | + |
| 132 | + # Check sufficient balance |
| 133 | + if owner_balance < value: |
| 134 | + return ResponseCode.ERROR, f'insufficient balance: {owner_balance} < {value}'.encode() |
| 135 | + |
| 136 | + # Get recipient balance |
| 137 | + to_balance_bytes = await stub.get_state(to) |
| 138 | + if not to_balance_bytes: |
| 139 | + return ResponseCode.ERROR, f'account {to} not found'.encode() |
| 140 | + |
| 141 | + to_balance = int(to_balance_bytes.decode()) |
| 142 | + |
| 143 | + # Update balances |
| 144 | + owner_balance -= value |
| 145 | + to_balance += value |
| 146 | + |
| 147 | + # Write updated balances to ledger |
| 148 | + await stub.put_state(owner, str(owner_balance).encode()) |
| 149 | + await stub.put_state(to, str(to_balance).encode()) |
| 150 | + |
| 151 | + logger.info(f"Transfer successful: {owner} ({owner_balance}), {to} ({to_balance})") |
| 152 | + return ResponseCode.SUCCESS, b'transfer ok' |
| 153 | + except ValueError: |
| 154 | + return ResponseCode.ERROR, f'invalid amount: {value}'.encode() |
| 155 | + except Exception as e: |
| 156 | + logger.error(f"Error during transfer: {str(e)}") |
| 157 | + return ResponseCode.ERROR, str(e).encode() |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == '__main__': |
| 161 | + # Start the chaincode server |
| 162 | + logger.info("Starting TokenChaincode server...") |
| 163 | + start(TokenChaincode()) |
0 commit comments