github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/protocol/state/contract_view.go (about) 1 package state 2 3 import ( 4 "github.com/bytom/bytom/consensus/bcrp" 5 "github.com/bytom/bytom/crypto/sha3pool" 6 "github.com/bytom/bytom/protocol/bc/types" 7 ) 8 9 // ContractViewpoint represents a view into the set of registered contract 10 type ContractViewpoint struct { 11 AttachEntries map[[32]byte][]byte 12 DetachEntries map[[32]byte][]byte 13 } 14 15 // NewContractViewpoint returns a new empty contract view. 16 func NewContractViewpoint() *ContractViewpoint { 17 return &ContractViewpoint{ 18 AttachEntries: make(map[[32]byte][]byte), 19 DetachEntries: make(map[[32]byte][]byte), 20 } 21 } 22 23 // ApplyBlock apply block contract to contract view 24 func (view *ContractViewpoint) ApplyBlock(block *types.Block) error { 25 for _, tx := range block.Transactions { 26 for _, output := range tx.Outputs { 27 if program := output.ControlProgram; bcrp.IsBCRPScript(program) { 28 contract, err := bcrp.ParseContract(program) 29 if err != nil { 30 return err 31 } 32 33 var hash [32]byte 34 sha3pool.Sum256(hash[:], contract) 35 if _, ok := view.AttachEntries[hash]; !ok { 36 view.AttachEntries[hash] = append(tx.ID.Bytes(), contract...) 37 } 38 } 39 } 40 } 41 return nil 42 } 43 44 // DetachBlock detach block contract to contract view 45 func (view *ContractViewpoint) DetachBlock(block *types.Block) error { 46 for i := len(block.Transactions) - 1; i >= 0; i-- { 47 for _, output := range block.Transactions[i].Outputs { 48 if program := output.ControlProgram; bcrp.IsBCRPScript(program) { 49 contract, err := bcrp.ParseContract(program) 50 if err != nil { 51 return err 52 } 53 54 var hash [32]byte 55 sha3pool.Sum256(hash[:], contract) 56 view.DetachEntries[hash] = append(block.Transactions[i].ID.Bytes(), contract...) 57 } 58 } 59 } 60 return nil 61 }