github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/database/contract_view.go (about)

     1  package database
     2  
     3  import (
     4  	"bytes"
     5  
     6  	dbm "github.com/bytom/bytom/database/leveldb"
     7  	"github.com/bytom/bytom/errors"
     8  	"github.com/bytom/bytom/protocol/state"
     9  )
    10  
    11  // CalcContractKey calculate contract key
    12  func CalcContractKey(hash [32]byte) []byte {
    13  	return append(ContractPrefix, hash[:]...)
    14  }
    15  
    16  func saveContractView(db dbm.DB, batch dbm.Batch, view *state.ContractViewpoint) error {
    17  	for hash, value := range view.AttachEntries {
    18  		data := db.Get(CalcContractKey(hash))
    19  		// contract is not exist
    20  		if data == nil {
    21  			// key:"c:sha256(program.Code)" value:"txID+program.Code"
    22  			batch.Set(CalcContractKey(hash), value)
    23  		}
    24  		// contract is deleted in the same batch
    25  		if v, ok := view.DetachEntries[hash]; ok && bytes.Equal(data, v) {
    26  			batch.Set(CalcContractKey(hash), value)
    27  		}
    28  	}
    29  	return nil
    30  }
    31  
    32  func deleteContractView(db dbm.DB, batch dbm.Batch, view *state.ContractViewpoint) error {
    33  	for hash, value := range view.DetachEntries {
    34  		// rollback is forbidden if contract register transaction id is different
    35  		if bytes.Equal(db.Get(CalcContractKey(hash)), value) {
    36  			batch.Delete(CalcContractKey(hash))
    37  		}
    38  	}
    39  	return nil
    40  }
    41  
    42  func getContract(db dbm.DB, hash [32]byte) ([]byte, error) {
    43  	data := db.Get(CalcContractKey(hash))
    44  	if data == nil {
    45  		return nil, errors.New("can't find the registered contract by contract hash")
    46  	}
    47  
    48  	// data:"txID+program.Code" len(txID) == 32
    49  	if len(data) <= 32 {
    50  		return nil, errors.New("registered contract format error")
    51  	}
    52  
    53  	return data[32:], nil
    54  }