github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/docs/source/smartcontract/smartcontract.md (about)

     1  # Smart Contracts and Chaincode
     2  
     3  **Audience**: Architects, application and smart contract developers,
     4  administrators
     5  
     6  From an application developer's perspective, a **smart contract**, together with
     7  the [ledger](../ledger/ledger.html), form the heart of a Hechain
     8  blockchain system. Whereas a ledger holds facts about the current and historical
     9  state of a set of business objects, a **smart contract** defines the executable
    10  logic that generates new facts that are added to the ledger. A **chaincode**
    11  is typically used by administrators to group related smart contracts for
    12  deployment, but can also be used for low level system programming of Fabric. In
    13  this topic, we'll focus on why both **smart contracts** and **chaincode** exist,
    14  and how and when to use them.
    15  
    16  In this topic, we'll cover:
    17  
    18  - [Smart Contracts and Chaincode](#smart-contracts-and-chaincode)
    19    - [Smart contract](#smart-contract)
    20    - [Terminology](#terminology)
    21    - [Ledger](#ledger)
    22    - [Development](#development)
    23    - [Endorsement](#endorsement)
    24    - [Valid transactions](#valid-transactions)
    25    - [Channels](#channels)
    26    - [Intercommunication](#intercommunication)
    27    - [System chaincode](#system-chaincode)
    28  
    29  ## Smart contract
    30  
    31  Before businesses can transact with each other, they must define a common set of
    32  contracts covering common terms, data, rules, concept definitions, and
    33  processes. Taken together, these contracts lay out the **business model** that
    34  govern all of the interactions between transacting parties.
    35  
    36  ![smart.diagram1](./smartcontract.diagram.01.png) *A smart contract defines the
    37  rules between different organizations in executable code. Applications invoke a
    38  smart contract to generate transactions that are recorded on the ledger.*
    39  
    40  Using a blockchain network, we can turn these contracts into executable programs
    41  -- known in the industry as **smart contracts** -- to open up a wide variety of
    42  new possibilities. That's because a smart contract can implement the governance
    43  rules for **any** type of business object, so that they can be automatically
    44  enforced when the smart contract is executed. For example, a smart contract
    45  might ensure that a new car delivery is made within a specified timeframe, or
    46  that funds are released according to prearranged terms, improving the flow of
    47  goods or capital respectively. Most importantly however, the execution of a
    48  smart contract is much more efficient than a manual human business process.
    49  
    50  In the [diagram above](#smart-contract), we can see how two organizations,
    51  `ORG1` and `ORG2` have defined a `car` smart contract to `query`, `transfer` and
    52  `update` cars.  Applications from these organizations invoke this smart contract
    53  to perform an agreed step in a business process, for example to transfer
    54  ownership of a specific car from `ORG1` to `ORG2`.
    55  
    56  
    57  ## Terminology
    58  
    59  Hechain users often use the terms **smart contract** and
    60  **chaincode** interchangeably. In general, a smart contract defines the
    61  **transaction logic** that controls the lifecycle of a business object contained
    62  in the world state. It is then packaged into a chaincode which is then deployed
    63  to a blockchain network.  Think of smart contracts as governing transactions,
    64  whereas chaincode governs how smart contracts are packaged for deployment.
    65  
    66  ![smart.diagram2](./smartcontract.diagram.02.png) *A smart contract is defined
    67  within a chaincode.  Multiple smart contracts can be defined within the same
    68  chaincode. When a chaincode is deployed, all smart contracts within it are made
    69  available to applications.*
    70  
    71  In the diagram, we can see a `vehicle` chaincode that contains three smart
    72  contracts: `cars`, `boats` and `trucks`.  We can also see an `insurance`
    73  chaincode that contains four smart contracts: `policy`, `liability`,
    74  `syndication` and `securitization`.  In both cases these contracts cover key
    75  aspects of the business process relating to vehicles and insurance. In this
    76  topic, we will use the `car` contract as an example. We can see that a smart
    77  contract is a domain specific program which relates to specific business
    78  processes, whereas a chaincode is a technical container of a group of related
    79  smart contracts.
    80  
    81  
    82  ## Ledger
    83  
    84  At the simplest level, a blockchain immutably records transactions which update
    85  states in a ledger. A smart contract programmatically accesses two distinct
    86  pieces of the ledger -- a **blockchain**, which immutably records the history of
    87  all transactions, and a **world state** that holds a cache of the current value
    88  of these states, as it's the current value of an object that is usually
    89  required.
    90  
    91  Smart contracts primarily **put**, **get** and **delete** states in the world
    92  state, and can also query the immutable blockchain record of transactions.
    93  
    94  * A **get** typically represents a query to retrieve information about the
    95    current state of a business object.
    96  * A **put** typically creates a new business object or modifies an existing one
    97    in the ledger world state.
    98  * A **delete** typically represents the removal of a business object from the
    99    current state of the ledger, but not its history.
   100  
   101  Smart contracts have many
   102  [APIs](../developapps/transactioncontext.html#structure) available to them.
   103  Critically, in all cases, whether transactions create, read, update or delete
   104  business objects in the world state, the blockchain contains an [immutable
   105  record](../ledger/ledger.html) of these changes.
   106  
   107  ## Development
   108  
   109  Smart contracts are the focus of application development, and as we've seen, one
   110  or more smart contracts can be defined within a single chaincode.  Deploying a
   111  chaincode to a network makes all its smart contracts available to the
   112  organizations in that network. It means that only administrators need to worry
   113  about chaincode; everyone else can think in terms of smart contracts.
   114  
   115  At the heart of a smart contract is a set of `transaction` definitions. For
   116  example, look at assetTransfer.js
   117  [here](https://github.com/hyperledger/fabric-samples/blob/{BRANCH}/asset-transfer-basic/chaincode-javascript/lib/assetTransfer.js#L67),
   118  where you can see a smart contract transaction that creates a new asset:
   119  
   120  ```javascript
   121      async CreateAsset(ctx, id, color, size, owner, appraisedValue) {
   122          const asset = {
   123              ID: id,
   124              Color: color,
   125              Size: size,
   126              Owner: owner,
   127              AppraisedValue: appraisedValue,
   128          };
   129          return ctx.stub.putState(id, Buffer.from(JSON.stringify(asset)));
   130      }
   131  ```
   132  
   133  You can learn more about the **Basic** smart contract in the [Running a Fabric Application](../write_first_app.html) tutorial.
   134  
   135  A smart contract can describe an almost infinite array of business use cases
   136  relating to immutability of data in multi-organizational decision making. The
   137  job of a smart contract developer is to take an existing business process that
   138  might govern financial prices or delivery conditions, and express it as
   139  a smart contract in a programming language such as JavaScript, Go, or Java.
   140  The legal and technical skills required to convert centuries of legal language
   141  into programming language is increasingly practiced by **smart contract
   142  auditors**. You can learn about how to design and develop a smart contract in
   143  the [Developing applications
   144  topic](../developapps/developing_applications.html).
   145  
   146  
   147  ## Endorsement
   148  
   149  Associated with every chaincode is an endorsement policy that applies to all of
   150  the smart contracts defined within it. An endorsement policy is very important;
   151  it indicates which organizations in a blockchain network must sign a transaction
   152  generated by a given smart contract in order for that transaction to be declared
   153  **valid**.
   154  
   155  ![smart.diagram3](./smartcontract.diagram.03.png) *Every smart contract has an
   156  endorsement policy associated with it. This endorsement policy identifies which
   157  organizations must approve transactions generated by the smart contract before
   158  those transactions can be identified as valid.*
   159  
   160  An example endorsement policy might define that three of the four organizations
   161  participating in a blockchain network must sign a transaction before it is
   162  considered **valid**. All transactions, whether **valid** or **invalid** are
   163  added to a distributed ledger, but only **valid** transactions update the world
   164  state.
   165  
   166  If an endorsement policy specifies that more than one organization must sign a
   167  transaction, then the smart contract must be executed by a sufficient set of
   168  organizations in order for a valid transaction to be generated. In the example
   169  [above](#endorsement), a smart contract transaction to `transfer` a car would
   170  need to be executed and signed by both `ORG1` and `ORG2` for it to be valid.
   171  
   172  Endorsement policies are what make Hechain different to other
   173  blockchains like Ethereum or Bitcoin. In these systems valid transactions can be
   174  generated by any node in the network. Hechain more realistically
   175  models the real world; transactions must be validated by trusted organizations
   176  in a network. For example, a government organization must sign a valid
   177  `issueIdentity` transaction, or both the `buyer` and `seller` of a car must sign
   178  a `car` transfer transaction. Endorsement policies are designed to allow
   179  Hechain to better model these types of real-world interactions.
   180  
   181  Finally, endorsement policies are just one example of
   182  [policy](../access_control.html#policies) in Hechain. Other policies
   183  can be defined to identify who can query or update the ledger, or add or remove
   184  participants from the network. In general, policies should be agreed in advance
   185  by the consortium of organizations in a blockchain network, although they are
   186  not set in stone. Indeed, policies themselves can define the rules by which they
   187  can be changed. And although an advanced topic, it is also possible to define
   188  [custom endorsement policy](../pluggable_endorsement_and_validation.html) rules
   189  over and above those provided by Fabric.
   190  
   191  ## Valid transactions
   192  
   193  When a smart contract executes, it runs on a peer node owned by an organization
   194  in the blockchain network. The contract takes a set of input parameters called
   195  the **transaction proposal** and uses them in combination with its program logic
   196  to read and write the ledger. Changes to the world state are captured as a
   197  **transaction proposal response** (or just **transaction response**) which
   198  contains a **read-write set** with both the states that have been read, and the
   199  new states that are to be written if the transaction is valid. Notice that the
   200  world state **is not updated when the smart contract is executed**!
   201  
   202  ![smart.diagram4](./smartcontract.diagram.04.png) *All transactions have an
   203  identifier, a proposal, and a response signed by a set of organizations. All
   204  transactions are recorded on the blockchain, whether valid or invalid, but only
   205  valid transactions contribute to the world state.*
   206  
   207  Examine the `car transfer` transaction. You can see a transaction `t3` for a car
   208  transfer between `ORG1` and `ORG2`. See how the transaction has input `{CAR1,
   209  ORG1, ORG2}` and output `{CAR1.owner=ORG1, CAR1.owner=ORG2}`, representing the
   210  change of owner from `ORG1` to `ORG2`. Notice how the input is signed by the
   211  application's organization `ORG1`, and the output is signed by *both*
   212  organizations identified by the endorsement policy, `ORG1` and `ORG2`.  These
   213  signatures were generated by using each actor's private key, and mean that
   214  anyone in the network can verify that all actors in the network are in agreement
   215  about the transaction details.
   216  
   217  A transaction that is distributed to all peer nodes in the network is
   218  **validated** in two phases by each peer. Firstly, the transaction is checked to
   219  ensure it has been signed by sufficient organizations according to the endorsement
   220  policy. Secondly, it is checked to ensure that the current value of the world state
   221  matches the read set of the transaction when it was signed by the endorsing peer
   222  nodes; that there has been no intermediate update. If a transaction passes both
   223  these tests, it is marked as **valid**. All transactions are added to the
   224  blockchain history, whether **valid** or **invalid**, but only **valid**
   225  transactions result in an update to the world state.
   226  
   227  In our example, `t3` is a valid transaction, so the owner of `CAR1` has been
   228  updated to `ORG2`. However, `t4` (not shown) is an invalid transaction, so while
   229  it was recorded in the ledger, the world state was not updated, and `CAR2`
   230  remains owned by `ORG2`.
   231  
   232  Finally, to understand how to use a smart contract or chaincode with world
   233  state, read the [chaincode namespace
   234  topic](../developapps/chaincodenamespace.html).
   235  
   236  ## Channels
   237  
   238  Hechain allows an organization to simultaneously participate in
   239  multiple, separate blockchain networks via **channels**. By joining multiple
   240  channels, an organization can participate in a so-called **network of networks**.
   241  Channels provide an efficient sharing of infrastructure while maintaining data
   242  and communications privacy. They are independent enough to help organizations
   243  separate their work traffic with different counterparties, but integrated enough
   244  to allow them to coordinate independent activities when necessary.
   245  
   246  ![smart.diagram5](./smartcontract.diagram.05.png) *A channel provides a
   247  completely separate communication mechanism between a set of organizations. When
   248  a chaincode definition is committed to a channel, all the smart contracts within
   249  the chaincode are made available to the applications on that channel.*
   250  
   251  While the smart contract code is installed inside a chaincode package on an
   252  organizations peers, channel members can only execute a smart contract after
   253  the chaincode has been defined on a channel. The **chaincode definition** is a
   254  struct that contains the parameters that govern how a chaincode operates. These
   255  parameters include the chaincode name, version, and the endorsement policy.
   256  Each channel member agrees to the parameters of a chaincode by approving a
   257  chaincode definition for their organization. When a sufficient number of
   258  organizations (a majority by default) have approved to the same chaincode
   259  definition, the definition can be committed to the channel. The smart contracts
   260  inside the chaincode can then be executed by channel members, subject to the
   261  endorsement policy specified in the chaincode definition. The endorsement policy
   262  applies equally to all smart contracts defined within the same chaincode.
   263  
   264  In the example [above](#channels), a `car` contract is defined on the `VEHICLE`
   265  channel, and an `insurance` contract is defined on the `INSURANCE` channel.
   266  The chaincode definition of `car` specifies an endorsement policy that requires
   267  both `ORG1` and `ORG2` to sign transactions before they can be considered valid.
   268  The chaincode definition of the `insurance` contract specifies that only `ORG3`
   269  is required to endorse a transaction. `ORG1` participates in two networks, the
   270  `VEHICLE` channel and the `INSURANCE` network, and can coordinate activity with
   271  `ORG2` and `ORG3` across these two networks.
   272  
   273  The chaincode definition provides a way for channel members to agree on the
   274  governance of a chaincode before they start using the smart contract to
   275  transact on the channel. Building on the example above, both `ORG1` and `ORG2`
   276  want to endorse transactions that invoke the `car` contract. Because the default
   277  policy requires that a majority of organizations approve a chaincode definition,
   278  both organizations need to approve an endorsement policy of `AND{ORG1,ORG2}`.
   279  Otherwise, `ORG1` and `ORG2` would approve different chaincode definitions and
   280  would be unable to commit the chaincode definition to the channel as a result.
   281  This process guarantees that a transaction from the `car` smart contract needs
   282  to be approved by both organizations.
   283  
   284  ## Intercommunication
   285  
   286  A Smart Contract can call other smart contracts both within the same
   287  channel and across different channels. It this way, they can read and write
   288  world state data to which they would not otherwise have access due to smart
   289  contract namespaces.
   290  
   291  There are limitations to this inter-contract communication, which are described
   292  fully in the [chaincode namespace](../developapps/chaincodenamespace.html#cross-chaincode-access) topic.
   293  
   294  ## System chaincode
   295  
   296  The smart contracts defined within a chaincode encode the domain dependent rules
   297  for a business process agreed between a set of blockchain organizations.
   298  However, a chaincode can also define low-level program code which corresponds to
   299  domain independent *system* interactions, unrelated to these smart contracts
   300  for business processes.
   301  
   302  The following are the different types of system chaincodes and their associated
   303  abbreviations:
   304  
   305  * `_lifecycle` runs in all peers and manages the installation of chaincode on
   306    your peers, the approval of chaincode definitions for your organization, and
   307    the committing of chaincode definitions to channels. You can read more about
   308    how `_lifecycle` implements the Fabric chaincode lifecycle [process](../chaincode_lifecycle.html).
   309  
   310  * Lifecycle system chaincode (LSCC) manages the chaincode lifecycle for the
   311    1.x releases of Fabric. This version of lifecycle required that chaincode be
   312    instantiated or upgraded on channels. You can still use LSCC to manage your
   313    chaincode if you have the channel application capability set to V1_4_x or below.
   314  
   315  * **Configuration system chaincode (CSCC)** runs in all peers to handle changes to a
   316    channel configuration, such as a policy update.  You can read more about this
   317    process in the following chaincode
   318    [topic](../configtx.html#configuration-updates).
   319  
   320  * **Query system chaincode (QSCC)** runs in all peers to provide ledger APIs which
   321    include block query, transaction query etc. You can read more about these
   322    ledger APIs in the transaction context
   323    [topic](../developapps/transactioncontext.html).
   324  
   325  * **Endorsement system chaincode (ESCC)** runs in endorsing peers to
   326    cryptographically sign a transaction response. You can read more about how
   327    the ESCC implements this [process](../peers/peers.html#phase-1-proposal).
   328  
   329  * **Validation system chaincode (VSCC)** validates a transaction, including checking
   330    endorsement policy and read-write set versioning. You can read more about the
   331    VSCC implements this [process](../peers/peers.html#phase-3-validation).
   332  
   333  It is possible for low level Fabric developers and administrators to modify
   334  these system chaincodes for their own uses. However, the development and
   335  management of system chaincodes is a specialized activity, quite separate from
   336  the development of smart contracts, and is not normally necessary. Changes to
   337  system chaincodes must be handled with extreme care as they are fundamental to
   338  the correct functioning of a Hechain network. For example, if a
   339  system chaincode is not developed correctly, one peer node may update its copy
   340  of the world state or blockchain differently compared to another peer node. This
   341  lack of consensus is one form of a **ledger fork**, a very undesirable situation.
   342  
   343  <!--- Licensed under Creative Commons Attribution 4.0 International License
   344  https://creativecommons.org/licenses/by/4.0/ -->