diff --git a/core/types/suave_structs.go b/core/types/suave_structs.go index f7922dd967..718de03177 100755 --- a/core/types/suave_structs.go +++ b/core/types/suave_structs.go @@ -1,22 +1,13 @@ // Code generated by suave/gen. DO NOT EDIT. -// Hash: cdc3a0bf9b0cd1b4a4b17e6245d7e942f42ffc5f7333bc11a220abbc67d6587b +// Hash: 80e00d3e46ad61ee6925143b317f91c0ad551d66908d0ab20e244db63b40ff40 package types import "github.com/ethereum/go-ethereum/common" -type BidId [16]byte +type DataId [16]byte // Structs -type Bid struct { - Id BidId - Salt BidId - DecryptionCondition uint64 - AllowedPeekers []common.Address - AllowedStores []common.Address - Version string -} - type BuildBlockArgs struct { Slot uint64 ProposerPubkey []byte @@ -29,6 +20,15 @@ type BuildBlockArgs struct { Extra []byte } +type DataRecord struct { + Id DataId + Salt DataId + DecryptionCondition uint64 + AllowedPeekers []common.Address + AllowedStores []common.Address + Version string +} + type HttpRequest struct { Url string Method string diff --git a/core/vm/contracts_suave.go b/core/vm/contracts_suave.go index 8f4c94b55b..0fb504a1b4 100644 --- a/core/vm/contracts_suave.go +++ b/core/vm/contracts_suave.go @@ -34,15 +34,15 @@ func (b *suaveRuntime) confidentialInputs() ([]byte, error) { /* Confidential store precompiles */ -func (b *suaveRuntime) confidentialStore(bidId types.BidId, key string, data []byte) error { - bid, err := b.suaveContext.Backend.ConfidentialStore.FetchBidById(bidId) +func (b *suaveRuntime) confidentialStore(dataId types.DataId, key string, data []byte) error { + record, err := b.suaveContext.Backend.ConfidentialStore.FetchRecordByID(dataId) if err != nil { - return suave.ErrBidNotFound + return suave.ErrRecordNotFound } - log.Info("confStore", "bidId", bidId, "key", key) + log.Debug("confStore", "dataId", dataId, "key", key) - caller, err := checkIsPrecompileCallAllowed(b.suaveContext, confidentialStoreAddr, bid) + caller, err := checkIsPrecompileCallAllowed(b.suaveContext, confidentialStoreAddr, record) if err != nil { return err } @@ -51,7 +51,7 @@ func (b *suaveRuntime) confidentialStore(bidId types.BidId, key string, data []b confStorePrecompileStoreMeter.Mark(int64(len(data))) } - _, err = b.suaveContext.Backend.ConfidentialStore.Store(bidId, caller, key, data) + _, err = b.suaveContext.Backend.ConfidentialStore.Store(dataId, caller, key, data) if err != nil { return err } @@ -59,18 +59,18 @@ func (b *suaveRuntime) confidentialStore(bidId types.BidId, key string, data []b return nil } -func (b *suaveRuntime) confidentialRetrieve(bidId types.BidId, key string) ([]byte, error) { - bid, err := b.suaveContext.Backend.ConfidentialStore.FetchBidById(bidId) +func (b *suaveRuntime) confidentialRetrieve(dataId types.DataId, key string) ([]byte, error) { + record, err := b.suaveContext.Backend.ConfidentialStore.FetchRecordByID(dataId) if err != nil { - return nil, suave.ErrBidNotFound + return nil, suave.ErrRecordNotFound } - caller, err := checkIsPrecompileCallAllowed(b.suaveContext, confidentialRetrieveAddr, bid) + caller, err := checkIsPrecompileCallAllowed(b.suaveContext, confidentialRetrieveAddr, record) if err != nil { return nil, err } - data, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(bidId, caller, key) + data, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(dataId, caller, key) if err != nil { return []byte(err.Error()), err } @@ -82,36 +82,36 @@ func (b *suaveRuntime) confidentialRetrieve(bidId types.BidId, key string) ([]by return data, nil } -/* Bid precompiles */ +/* Data Record precompiles */ -func (b *suaveRuntime) newBid(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, BidType string) (types.Bid, error) { +func (b *suaveRuntime) newDataRecord(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, RecordType string) (types.DataRecord, error) { if b.suaveContext.ConfidentialComputeRequestTx == nil { - panic("newBid: source transaction not present") + panic("newRecord: source transaction not present") } - bid, err := b.suaveContext.Backend.ConfidentialStore.InitializeBid(types.Bid{ - Salt: suave.RandomBidId(), + record, err := b.suaveContext.Backend.ConfidentialStore.InitRecord(types.DataRecord{ + Salt: suave.RandomDataRecordId(), DecryptionCondition: decryptionCondition, AllowedPeekers: allowedPeekers, AllowedStores: allowedStores, - Version: BidType, // TODO : make generic + Version: RecordType, // TODO : make generic }) if err != nil { - return types.Bid{}, err + return types.DataRecord{}, err } - return bid, nil + return record, nil } -func (b *suaveRuntime) fetchBids(targetBlock uint64, namespace string) ([]types.Bid, error) { - bids1 := b.suaveContext.Backend.ConfidentialStore.FetchBidsByProtocolAndBlock(targetBlock, namespace) +func (b *suaveRuntime) fetchDataRecords(targetBlock uint64, namespace string) ([]types.DataRecord, error) { + records1 := b.suaveContext.Backend.ConfidentialStore.FetchRecordsByProtocolAndBlock(targetBlock, namespace) - bids := make([]types.Bid, 0, len(bids1)) - for _, bid := range bids1 { - bids = append(bids, bid.ToInnerBid()) + records := make([]types.DataRecord, 0, len(records1)) + for _, record := range records1 { + records = append(records, record.ToInnerRecord()) } - return bids, nil + return records, nil } func mustParseAbi(data string) abi.ABI { diff --git a/core/vm/contracts_suave_eth.go b/core/vm/contracts_suave_eth.go index 38d62583f2..bfca64caf7 100644 --- a/core/vm/contracts_suave_eth.go +++ b/core/vm/contracts_suave_eth.go @@ -110,71 +110,71 @@ func (b *suaveRuntime) ethcall(contractAddr common.Address, input []byte) ([]byt return b.suaveContext.Backend.ConfidentialEthBackend.Call(context.Background(), contractAddr, input) } -func (b *suaveRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, bidId types.BidId, namespace string) ([]byte, []byte, error) { - bidIds := [][16]byte{} - // first check for merged bid, else assume regular bid - if mergedBidsBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(bidId, buildEthBlockAddr, "default:v0:mergedBids"); err == nil { - unpacked, err := bidIdsAbi.Inputs.Unpack(mergedBidsBytes) +func (b *suaveRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, dataID types.DataId, namespace string) ([]byte, []byte, error) { + dataIDs := [][16]byte{} + // first check for merged record, else assume regular record + if mergedDataRecordsBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(dataID, buildEthBlockAddr, "default:v0:mergedDataRecords"); err == nil { + unpacked, err := dataIDsAbi.Inputs.Unpack(mergedDataRecordsBytes) if err != nil { - return nil, nil, fmt.Errorf("could not unpack merged bid ids: %w", err) + return nil, nil, fmt.Errorf("could not unpack merged record ids: %w", err) } - bidIds = unpacked[0].([][16]byte) + dataIDs = unpacked[0].([][16]byte) } else { - bidIds = append(bidIds, bidId) + dataIDs = append(dataIDs, dataID) } - var bidsToMerge = make([]types.Bid, len(bidIds)) - for i, bidId := range bidIds { + var recordsToMerge = make([]types.DataRecord, len(dataIDs)) + for i, dataID := range dataIDs { var err error - bid, err := b.suaveContext.Backend.ConfidentialStore.FetchBidById(bidId) + record, err := b.suaveContext.Backend.ConfidentialStore.FetchRecordByID(dataID) if err != nil { - return nil, nil, fmt.Errorf("could not fetch bid id %v: %w", bidId, err) + return nil, nil, fmt.Errorf("could not fetch record id %v: %w", dataID, err) } - if _, err := checkIsPrecompileCallAllowed(b.suaveContext, buildEthBlockAddr, bid); err != nil { + if _, err := checkIsPrecompileCallAllowed(b.suaveContext, buildEthBlockAddr, record); err != nil { return nil, nil, err } - bidsToMerge[i] = bid.ToInnerBid() + recordsToMerge[i] = record.ToInnerRecord() } var mergedBundles []types.SBundle - for _, bid := range bidsToMerge { - switch bid.Version { - case "mevshare:v0:matchBids": + for _, record := range recordsToMerge { + switch record.Version { + case "mevshare:v0:matchDataRecords": // fetch the matched ids and merge the bundle - matchedBundleIdsBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(bid.Id, buildEthBlockAddr, "mevshare:v0:mergedBids") + matchedBundleIdsBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(record.Id, buildEthBlockAddr, "mevshare:v0:mergedDataRecords") if err != nil { - return nil, nil, fmt.Errorf("could not retrieve bid ids data for bid %v, from cdas: %w", bid, err) + return nil, nil, fmt.Errorf("could not retrieve record ids data for record %v, from cdas: %w", record, err) } - unpackedBidIds, err := bidIdsAbi.Inputs.Unpack(matchedBundleIdsBytes) + unpackeddataIDs, err := dataIDsAbi.Inputs.Unpack(matchedBundleIdsBytes) if err != nil { - return nil, nil, fmt.Errorf("could not unpack bid ids data for bid %v, from cdas: %w", bid, err) + return nil, nil, fmt.Errorf("could not unpack record ids data for record %v, from cdas: %w", record, err) } - matchBidIds := unpackedBidIds[0].([][16]byte) + matchdataIDs := unpackeddataIDs[0].([][16]byte) - userBundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(matchBidIds[0], buildEthBlockAddr, "mevshare:v0:ethBundles") + userBundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(matchdataIDs[0], buildEthBlockAddr, "mevshare:v0:ethBundles") if err != nil { - return nil, nil, fmt.Errorf("could not retrieve bundle data for bidId %v: %w", matchBidIds[0], err) + return nil, nil, fmt.Errorf("could not retrieve bundle data for dataID %v: %w", matchdataIDs[0], err) } var userBundle types.SBundle if err := json.Unmarshal(userBundleBytes, &userBundle); err != nil { - return nil, nil, fmt.Errorf("could not unmarshal user bundle data for bidId %v: %w", matchBidIds[0], err) + return nil, nil, fmt.Errorf("could not unmarshal user bundle data for dataID %v: %w", matchdataIDs[0], err) } - matchBundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(matchBidIds[1], buildEthBlockAddr, "mevshare:v0:ethBundles") + matchBundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(matchdataIDs[1], buildEthBlockAddr, "mevshare:v0:ethBundles") if err != nil { - return nil, nil, fmt.Errorf("could not retrieve match bundle data for bidId %v: %w", matchBidIds[1], err) + return nil, nil, fmt.Errorf("could not retrieve match bundle data for dataID %v: %w", matchdataIDs[1], err) } var matchBundle types.SBundle if err := json.Unmarshal(matchBundleBytes, &matchBundle); err != nil { - return nil, nil, fmt.Errorf("could not unmarshal match bundle data for bidId %v: %w", matchBidIds[1], err) + return nil, nil, fmt.Errorf("could not unmarshal match bundle data for dataID %v: %w", matchdataIDs[1], err) } userBundle.Txs = append(userBundle.Txs, matchBundle.Txs...) @@ -182,29 +182,29 @@ func (b *suaveRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, bidId types mergedBundles = append(mergedBundles, userBundle) case "mevshare:v0:unmatchedBundles": - bundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(bid.Id, buildEthBlockAddr, "mevshare:v0:ethBundles") + bundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(record.Id, buildEthBlockAddr, "mevshare:v0:ethBundles") if err != nil { - return nil, nil, fmt.Errorf("could not retrieve bundle data for bidId %v, from cdas: %w", bid.Id, err) + return nil, nil, fmt.Errorf("could not retrieve bundle data for dataID %v, from cdas: %w", record.Id, err) } var bundle types.SBundle if err := json.Unmarshal(bundleBytes, &bundle); err != nil { - return nil, nil, fmt.Errorf("could not unmarshal bundle data for bidId %v, from cdas: %w", bid.Id, err) + return nil, nil, fmt.Errorf("could not unmarshal bundle data for dataID %v, from cdas: %w", record.Id, err) } mergedBundles = append(mergedBundles, bundle) case "default:v0:ethBundles": - bundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(bid.Id, buildEthBlockAddr, "default:v0:ethBundles") + bundleBytes, err := b.suaveContext.Backend.ConfidentialStore.Retrieve(record.Id, buildEthBlockAddr, "default:v0:ethBundles") if err != nil { - return nil, nil, fmt.Errorf("could not retrieve bundle data for bidId %v, from cdas: %w", bid.Id, err) + return nil, nil, fmt.Errorf("could not retrieve bundle data for dataID %v, from cdas: %w", record.Id, err) } var bundle types.SBundle if err := json.Unmarshal(bundleBytes, &bundle); err != nil { - return nil, nil, fmt.Errorf("could not unmarshal bundle data for bidId %v, from cdas: %w", bid.Id, err) + return nil, nil, fmt.Errorf("could not unmarshal bundle data for dataID %v, from cdas: %w", record.Id, err) } mergedBundles = append(mergedBundles, bundle) default: - return nil, nil, fmt.Errorf("unknown bid version %s", bid.Version) + return nil, nil, fmt.Errorf("unknown record version %s", record.Version) } } @@ -255,7 +255,7 @@ func (b *suaveRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, bidId types builderSigningDomain := ssz.ComputeDomain(ssz.DomainTypeAppBuilder, genesisForkVersion, phase0.Root{}) signature, err := ssz.SignMessage(&blockBidMsg, builderSigningDomain, b.suaveContext.Backend.EthBlockSigningKey) if err != nil { - return nil, nil, fmt.Errorf("could not sign builder bid: %w", err) + return nil, nil, fmt.Errorf("could not sign builder record: %w", err) } bidRequest := builderCapella.SubmitBlockRequest{ @@ -266,7 +266,7 @@ func (b *suaveRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, bidId types bidBytes, err := bidRequest.MarshalJSON() if err != nil { - return nil, nil, fmt.Errorf("could not marshal builder bid request: %w", err) + return nil, nil, fmt.Errorf("could not marshal builder record request: %w", err) } envelopeBytes, err := json.Marshal(envelope) @@ -375,58 +375,67 @@ func (c *suaveRuntime) submitBundleJsonRPC(url string, method string, params []b return nil, nil } -func (c *suaveRuntime) fillMevShareBundle(bidId types.BidId) ([]byte, error) { - bid, err := c.suaveContext.Backend.ConfidentialStore.FetchBidById(bidId) +func (c *suaveRuntime) fillMevShareBundle(dataID types.DataId) ([]byte, error) { + record, err := c.suaveContext.Backend.ConfidentialStore.FetchRecordByID(dataID) if err != nil { + fmt.Println(err.Error()) return nil, err } - if _, err := checkIsPrecompileCallAllowed(c.suaveContext, fillMevShareBundleAddr, bid); err != nil { + if _, err := checkIsPrecompileCallAllowed(c.suaveContext, fillMevShareBundleAddr, record); err != nil { + fmt.Println(err.Error()) return nil, err } - matchedBundleIdsBytes, err := c.confidentialRetrieve(bidId, "mevshare:v0:mergedBids") + matchedBundleIdsBytes, err := c.confidentialRetrieve(dataID, "mevshare:v0:mergedDataRecords") if err != nil { + fmt.Println(err.Error()) return nil, err } - unpackedBidIds, err := bidIdsAbi.Inputs.Unpack(matchedBundleIdsBytes) + unpackedDataIDs, err := dataIDsAbi.Inputs.Unpack(matchedBundleIdsBytes) if err != nil { - return nil, fmt.Errorf("could not unpack bid ids data for bid %v, from cdas: %w", bid, err) + fmt.Println(err.Error()) + return nil, fmt.Errorf("could not unpack record ids data for record %v, from cdas: %w", record, err) } - matchBidIds := unpackedBidIds[0].([][16]byte) + matchDataIDs := unpackedDataIDs[0].([][16]byte) - userBundleBytes, err := c.confidentialRetrieve(matchBidIds[0], "mevshare:v0:ethBundles") + userBundleBytes, err := c.confidentialRetrieve(matchDataIDs[0], "mevshare:v0:ethBundles") if err != nil { - return nil, fmt.Errorf("could not retrieve bundle data for bidId %v: %w", matchBidIds[0], err) + fmt.Println(err.Error()) + return nil, fmt.Errorf("could not retrieve bundle data for dataID %v: %w", matchDataIDs[0], err) } var userBundle types.SBundle if err := json.Unmarshal(userBundleBytes, &userBundle); err != nil { - return nil, fmt.Errorf("could not unmarshal user bundle data for bidId %v: %w", matchBidIds[0], err) + fmt.Println(err.Error()) + return nil, fmt.Errorf("could not unmarshal user bundle data for dataID %v: %w", matchDataIDs[0], err) } - matchBundleBytes, err := c.confidentialRetrieve(matchBidIds[1], "mevshare:v0:ethBundles") + matchBundleBytes, err := c.confidentialRetrieve(matchDataIDs[1], "mevshare:v0:ethBundles") if err != nil { - return nil, fmt.Errorf("could not retrieve match bundle data for bidId %v: %w", matchBidIds[1], err) + fmt.Println(err.Error()) + return nil, fmt.Errorf("could not retrieve match bundle data for dataID %v: %w", matchDataIDs[1], err) } var matchBundle types.SBundle if err := json.Unmarshal(matchBundleBytes, &matchBundle); err != nil { - return nil, fmt.Errorf("could not unmarshal match bundle data for bidId %v: %w", matchBidIds[1], err) + fmt.Println(err.Error()) + return nil, fmt.Errorf("could not unmarshal match bundle data for dataID %v: %w", matchDataIDs[1], err) } shareBundle := &types.RPCMevShareBundle{ Version: "v0.1", } - shareBundle.Inclusion.Block = hexutil.EncodeUint64(bid.DecryptionCondition) - shareBundle.Inclusion.MaxBlock = hexutil.EncodeUint64(bid.DecryptionCondition + 25) // Assumes 25 block inclusion range + shareBundle.Inclusion.Block = hexutil.EncodeUint64(record.DecryptionCondition) + shareBundle.Inclusion.MaxBlock = hexutil.EncodeUint64(record.DecryptionCondition + 25) // Assumes 25 block inclusion range for _, tx := range append(userBundle.Txs, matchBundle.Txs...) { txBytes, err := tx.MarshalBinary() if err != nil { + fmt.Println(err.Error()) return nil, fmt.Errorf("could not marshal transaction: %w", err) } diff --git a/core/vm/contracts_suave_runtime_adapter.go b/core/vm/contracts_suave_runtime_adapter.go index 6c09958793..d42579bc7d 100644 --- a/core/vm/contracts_suave_runtime_adapter.go +++ b/core/vm/contracts_suave_runtime_adapter.go @@ -1,5 +1,5 @@ // Code generated by suave/gen. DO NOT EDIT. -// Hash: cdc3a0bf9b0cd1b4a4b17e6245d7e942f42ffc5f7333bc11a220abbc67d6587b +// Hash: 80e00d3e46ad61ee6925143b317f91c0ad551d66908d0ab20e244db63b40ff40 package vm import ( @@ -17,16 +17,16 @@ var ( ) type SuaveRuntime interface { - buildEthBlock(blockArgs types.BuildBlockArgs, bidId types.BidId, namespace string) ([]byte, []byte, error) + buildEthBlock(blockArgs types.BuildBlockArgs, dataId types.DataId, namespace string) ([]byte, []byte, error) confidentialInputs() ([]byte, error) - confidentialRetrieve(bidId types.BidId, key string) ([]byte, error) - confidentialStore(bidId types.BidId, key string, data1 []byte) error + confidentialRetrieve(dataId types.DataId, key string) ([]byte, error) + confidentialStore(dataId types.DataId, key string, data1 []byte) error doHTTPRequest(request types.HttpRequest) ([]byte, error) ethcall(contractAddr common.Address, input1 []byte) ([]byte, error) extractHint(bundleData []byte) ([]byte, error) - fetchBids(cond uint64, namespace string) ([]types.Bid, error) - fillMevShareBundle(bidId types.BidId) ([]byte, error) - newBid(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, bidType string) (types.Bid, error) + fetchDataRecords(cond uint64, namespace string) ([]types.DataRecord, error) + fillMevShareBundle(dataId types.DataId) ([]byte, error) + newDataRecord(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, dataType string) (types.DataRecord, error) signEthTransaction(txn []byte, chainId string, signingKey string) ([]byte, error) simulateBundle(bundleData []byte) (uint64, error) submitBundleJsonRPC(url string, method string, params []byte) ([]byte, error) @@ -41,9 +41,9 @@ var ( doHTTPRequestAddr = common.HexToAddress("0x0000000000000000000000000000000043200002") ethcallAddr = common.HexToAddress("0x0000000000000000000000000000000042100003") extractHintAddr = common.HexToAddress("0x0000000000000000000000000000000042100037") - fetchBidsAddr = common.HexToAddress("0x0000000000000000000000000000000042030001") + fetchDataRecordsAddr = common.HexToAddress("0x0000000000000000000000000000000042030001") fillMevShareBundleAddr = common.HexToAddress("0x0000000000000000000000000000000043200001") - newBidAddr = common.HexToAddress("0x0000000000000000000000000000000042030000") + newDataRecordAddr = common.HexToAddress("0x0000000000000000000000000000000042030000") signEthTransactionAddr = common.HexToAddress("0x0000000000000000000000000000000040100001") simulateBundleAddr = common.HexToAddress("0x0000000000000000000000000000000042100000") submitBundleJsonRPCAddr = common.HexToAddress("0x0000000000000000000000000000000043000001") @@ -51,7 +51,7 @@ var ( ) var addrList = []common.Address{ - buildEthBlockAddr, confidentialInputsAddr, confidentialRetrieveAddr, confidentialStoreAddr, doHTTPRequestAddr, ethcallAddr, extractHintAddr, fetchBidsAddr, fillMevShareBundleAddr, newBidAddr, signEthTransactionAddr, simulateBundleAddr, submitBundleJsonRPCAddr, submitEthBlockBidToRelayAddr, + buildEthBlockAddr, confidentialInputsAddr, confidentialRetrieveAddr, confidentialStoreAddr, doHTTPRequestAddr, ethcallAddr, extractHintAddr, fetchDataRecordsAddr, fillMevShareBundleAddr, newDataRecordAddr, signEthTransactionAddr, simulateBundleAddr, submitBundleJsonRPCAddr, submitEthBlockBidToRelayAddr, } type SuaveRuntimeAdapter struct { @@ -81,14 +81,14 @@ func (b *SuaveRuntimeAdapter) run(addr common.Address, input []byte) ([]byte, er case extractHintAddr: return b.extractHint(input) - case fetchBidsAddr: - return b.fetchBids(input) + case fetchDataRecordsAddr: + return b.fetchDataRecords(input) case fillMevShareBundleAddr: return b.fillMevShareBundle(input) - case newBidAddr: - return b.newBid(input) + case newDataRecordAddr: + return b.newDataRecord(input) case signEthTransactionAddr: return b.signEthTransaction(input) @@ -124,7 +124,7 @@ func (b *SuaveRuntimeAdapter) buildEthBlock(input []byte) (res []byte, err error var ( blockArgs types.BuildBlockArgs - bidId types.BidId + dataId types.DataId namespace string ) @@ -133,7 +133,7 @@ func (b *SuaveRuntimeAdapter) buildEthBlock(input []byte) (res []byte, err error return } - if err = mapstructure.Decode(unpacked[1], &bidId); err != nil { + if err = mapstructure.Decode(unpacked[1], &dataId); err != nil { err = errFailedToDecodeField return } @@ -145,7 +145,7 @@ func (b *SuaveRuntimeAdapter) buildEthBlock(input []byte) (res []byte, err error output2 []byte ) - if output1, output2, err = b.impl.buildEthBlock(blockArgs, bidId, namespace); err != nil { + if output1, output2, err = b.impl.buildEthBlock(blockArgs, dataId, namespace); err != nil { return } @@ -204,11 +204,11 @@ func (b *SuaveRuntimeAdapter) confidentialRetrieve(input []byte) (res []byte, er } var ( - bidId types.BidId - key string + dataId types.DataId + key string ) - if err = mapstructure.Decode(unpacked[0], &bidId); err != nil { + if err = mapstructure.Decode(unpacked[0], &dataId); err != nil { err = errFailedToDecodeField return } @@ -219,7 +219,7 @@ func (b *SuaveRuntimeAdapter) confidentialRetrieve(input []byte) (res []byte, er output1 []byte ) - if output1, err = b.impl.confidentialRetrieve(bidId, key); err != nil { + if output1, err = b.impl.confidentialRetrieve(dataId, key); err != nil { return } @@ -244,12 +244,12 @@ func (b *SuaveRuntimeAdapter) confidentialStore(input []byte) (res []byte, err e } var ( - bidId types.BidId - key string - data1 []byte + dataId types.DataId + key string + data1 []byte ) - if err = mapstructure.Decode(unpacked[0], &bidId); err != nil { + if err = mapstructure.Decode(unpacked[0], &dataId); err != nil { err = errFailedToDecodeField return } @@ -259,7 +259,7 @@ func (b *SuaveRuntimeAdapter) confidentialStore(input []byte) (res []byte, err e var () - if err = b.impl.confidentialStore(bidId, key, data1); err != nil { + if err = b.impl.confidentialStore(dataId, key, data1); err != nil { return } @@ -382,7 +382,7 @@ func (b *SuaveRuntimeAdapter) extractHint(input []byte) (res []byte, err error) } -func (b *SuaveRuntimeAdapter) fetchBids(input []byte) (res []byte, err error) { +func (b *SuaveRuntimeAdapter) fetchDataRecords(input []byte) (res []byte, err error) { var ( unpacked []interface{} result []byte @@ -391,7 +391,7 @@ func (b *SuaveRuntimeAdapter) fetchBids(input []byte) (res []byte, err error) { _ = unpacked _ = result - unpacked, err = artifacts.SuaveAbi.Methods["fetchBids"].Inputs.Unpack(input) + unpacked, err = artifacts.SuaveAbi.Methods["fetchDataRecords"].Inputs.Unpack(input) if err != nil { err = errFailedToUnpackInput return @@ -406,14 +406,14 @@ func (b *SuaveRuntimeAdapter) fetchBids(input []byte) (res []byte, err error) { namespace = unpacked[1].(string) var ( - bid []types.Bid + dataRecords []types.DataRecord ) - if bid, err = b.impl.fetchBids(cond, namespace); err != nil { + if dataRecords, err = b.impl.fetchDataRecords(cond, namespace); err != nil { return } - result, err = artifacts.SuaveAbi.Methods["fetchBids"].Outputs.Pack(bid) + result, err = artifacts.SuaveAbi.Methods["fetchDataRecords"].Outputs.Pack(dataRecords) if err != nil { err = errFailedToPackOutput return @@ -438,10 +438,10 @@ func (b *SuaveRuntimeAdapter) fillMevShareBundle(input []byte) (res []byte, err } var ( - bidId types.BidId + dataId types.DataId ) - if err = mapstructure.Decode(unpacked[0], &bidId); err != nil { + if err = mapstructure.Decode(unpacked[0], &dataId); err != nil { err = errFailedToDecodeField return } @@ -450,7 +450,7 @@ func (b *SuaveRuntimeAdapter) fillMevShareBundle(input []byte) (res []byte, err encodedBundle []byte ) - if encodedBundle, err = b.impl.fillMevShareBundle(bidId); err != nil { + if encodedBundle, err = b.impl.fillMevShareBundle(dataId); err != nil { return } @@ -459,7 +459,7 @@ func (b *SuaveRuntimeAdapter) fillMevShareBundle(input []byte) (res []byte, err } -func (b *SuaveRuntimeAdapter) newBid(input []byte) (res []byte, err error) { +func (b *SuaveRuntimeAdapter) newDataRecord(input []byte) (res []byte, err error) { var ( unpacked []interface{} result []byte @@ -468,7 +468,7 @@ func (b *SuaveRuntimeAdapter) newBid(input []byte) (res []byte, err error) { _ = unpacked _ = result - unpacked, err = artifacts.SuaveAbi.Methods["newBid"].Inputs.Unpack(input) + unpacked, err = artifacts.SuaveAbi.Methods["newDataRecord"].Inputs.Unpack(input) if err != nil { err = errFailedToUnpackInput return @@ -478,23 +478,23 @@ func (b *SuaveRuntimeAdapter) newBid(input []byte) (res []byte, err error) { decryptionCondition uint64 allowedPeekers []common.Address allowedStores []common.Address - bidType string + dataType string ) decryptionCondition = unpacked[0].(uint64) allowedPeekers = unpacked[1].([]common.Address) allowedStores = unpacked[2].([]common.Address) - bidType = unpacked[3].(string) + dataType = unpacked[3].(string) var ( - bid types.Bid + dataRecord types.DataRecord ) - if bid, err = b.impl.newBid(decryptionCondition, allowedPeekers, allowedStores, bidType); err != nil { + if dataRecord, err = b.impl.newDataRecord(decryptionCondition, allowedPeekers, allowedStores, dataType); err != nil { return } - result, err = artifacts.SuaveAbi.Methods["newBid"].Outputs.Pack(bid) + result, err = artifacts.SuaveAbi.Methods["newDataRecord"].Outputs.Pack(dataRecord) if err != nil { err = errFailedToPackOutput return diff --git a/core/vm/contracts_suave_runtime_adapter_test.go b/core/vm/contracts_suave_runtime_adapter_test.go index dde519b234..cc131f403e 100644 --- a/core/vm/contracts_suave_runtime_adapter_test.go +++ b/core/vm/contracts_suave_runtime_adapter_test.go @@ -15,7 +15,7 @@ var _ SuaveRuntime = &mockRuntime{} type mockRuntime struct { } -func (m *mockRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, bidId types.BidId, namespace string) ([]byte, []byte, error) { +func (m *mockRuntime) buildEthBlock(blockArgs types.BuildBlockArgs, dataId types.DataId, namespace string) ([]byte, []byte, error) { return []byte{0x1}, []byte{0x1}, nil } @@ -23,11 +23,11 @@ func (m *mockRuntime) confidentialInputs() ([]byte, error) { return []byte{0x1}, nil } -func (m *mockRuntime) confidentialRetrieve(bidId types.BidId, key string) ([]byte, error) { +func (m *mockRuntime) confidentialRetrieve(dataId types.DataId, key string) ([]byte, error) { return []byte{0x1}, nil } -func (m *mockRuntime) confidentialStore(bidId types.BidId, key string, data1 []byte) error { +func (m *mockRuntime) confidentialStore(dataId types.DataId, key string, data1 []byte) error { return nil } @@ -39,16 +39,16 @@ func (m *mockRuntime) extractHint(bundleData []byte) ([]byte, error) { return []byte{0x1}, nil } -func (m *mockRuntime) fetchBids(cond uint64, namespace string) ([]types.Bid, error) { - return []types.Bid{{}}, nil +func (m *mockRuntime) fetchDataRecords(cond uint64, namespace string) ([]types.DataRecord, error) { + return []types.DataRecord{{}}, nil } -func (m *mockRuntime) fillMevShareBundle(bidId types.BidId) ([]byte, error) { +func (m *mockRuntime) fillMevShareBundle(dataId types.DataId) ([]byte, error) { return []byte{0x1}, nil } -func (m *mockRuntime) newBid(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, bidType string) (types.Bid, error) { - return types.Bid{}, nil +func (m *mockRuntime) newDataRecord(decryptionCondition uint64, allowedPeekers []common.Address, allowedStores []common.Address, dataType string) (types.DataRecord, error) { + return types.DataRecord{}, nil } func (m *mockRuntime) signEthTransaction(txn []byte, chainId string, signingKey string) ([]byte, error) { diff --git a/core/vm/contracts_suave_test.go b/core/vm/contracts_suave_test.go index 995c088c86..6bc50ca33e 100644 --- a/core/vm/contracts_suave_test.go +++ b/core/vm/contracts_suave_test.go @@ -20,31 +20,31 @@ type mockSuaveBackend struct { func (m *mockSuaveBackend) Start() error { return nil } func (m *mockSuaveBackend) Stop() error { return nil } -func (m *mockSuaveBackend) InitializeBid(bid suave.Bid) error { +func (m *mockSuaveBackend) InitializeBid(record suave.DataRecord) error { return nil } -func (m *mockSuaveBackend) Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { - return suave.Bid{}, nil +func (m *mockSuaveBackend) Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { + return suave.DataRecord{}, nil } -func (m *mockSuaveBackend) Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) { +func (m *mockSuaveBackend) Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) { return nil, nil } -func (m *mockSuaveBackend) SubmitBid(types.Bid) error { +func (m *mockSuaveBackend) SubmitBid(types.DataRecord) error { return nil } -func (m *mockSuaveBackend) FetchEngineBidById(suave.BidId) (suave.Bid, error) { - return suave.Bid{}, nil +func (m *mockSuaveBackend) FetchEngineBidById(suave.DataId) (suave.DataRecord, error) { + return suave.DataRecord{}, nil } -func (m *mockSuaveBackend) FetchBidById(suave.BidId) (suave.Bid, error) { - return suave.Bid{}, nil +func (m *mockSuaveBackend) FetchBidById(suave.DataId) (suave.DataRecord, error) { + return suave.DataRecord{}, nil } -func (m *mockSuaveBackend) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { +func (m *mockSuaveBackend) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { return nil } @@ -68,7 +68,7 @@ func (m *mockSuaveBackend) Publish(cstore.DAMessage) {} func newTestBackend(t *testing.T) *suaveRuntime { confStore := cstore.NewLocalConfidentialStore() - confEngine := cstore.NewConfidentialStoreEngine(confStore, &cstore.MockTransport{}, cstore.MockSigner{}, cstore.MockChainSigner{}) + confEngine := cstore.NewEngine(confStore, &cstore.MockTransport{}, cstore.MockSigner{}, cstore.MockChainSigner{}) require.NoError(t, confEngine.Start()) t.Cleanup(func() { confEngine.Stop() }) @@ -94,31 +94,31 @@ func newTestBackend(t *testing.T) *suaveRuntime { func TestSuave_BidWorkflow(t *testing.T) { b := newTestBackend(t) - bid5, err := b.newBid(5, []common.Address{{0x1}}, nil, "a") + d5, err := b.newDataRecord(5, []common.Address{{0x1}}, nil, "a") require.NoError(t, err) - bid10, err := b.newBid(10, []common.Address{{0x1}}, nil, "a") + d10, err := b.newDataRecord(10, []common.Address{{0x1}}, nil, "a") require.NoError(t, err) - bid10b, err := b.newBid(10, []common.Address{{0x1}}, nil, "a") + d10b, err := b.newDataRecord(10, []common.Address{{0x1}}, nil, "a") require.NoError(t, err) cases := []struct { - cond uint64 - namespace string - bids []types.Bid + cond uint64 + namespace string + dataRecords []types.DataRecord }{ - {0, "a", []types.Bid{}}, - {5, "a", []types.Bid{bid5}}, - {10, "a", []types.Bid{bid10, bid10b}}, - {11, "a", []types.Bid{}}, + {0, "a", []types.DataRecord{}}, + {5, "a", []types.DataRecord{d5}}, + {10, "a", []types.DataRecord{d10, d10b}}, + {11, "a", []types.DataRecord{}}, } for _, c := range cases { - bids, err := b.fetchBids(c.cond, c.namespace) + dRecords, err := b.fetchDataRecords(c.cond, c.namespace) require.NoError(t, err) - require.ElementsMatch(t, c.bids, bids) + require.ElementsMatch(t, c.dataRecords, dRecords) } } @@ -128,29 +128,29 @@ func TestSuave_ConfStoreWorkflow(t *testing.T) { callerAddr := common.Address{0x1} data := []byte{0x1} - // cannot store a value for a bid that does not exist - err := b.confidentialStore(types.BidId{}, "key", data) + // cannot store a value for a dataRecord that does not exist + err := b.confidentialStore(types.DataId{}, "key", data) require.Error(t, err) - bid, err := b.newBid(5, []common.Address{callerAddr}, nil, "a") + dataRecord, err := b.newDataRecord(5, []common.Address{callerAddr}, nil, "a") require.NoError(t, err) - // cannot store the bid if the caller is not allowed to - err = b.confidentialStore(bid.Id, "key", data) + // cannot store the dataRecord if the caller is not allowed to + err = b.confidentialStore(dataRecord.Id, "key", data) require.Error(t, err) - // now, the caller is allowed to store the bid + // now, the caller is allowed to store the dataRecord b.suaveContext.CallerStack = append(b.suaveContext.CallerStack, &callerAddr) - err = b.confidentialStore(bid.Id, "key", data) + err = b.confidentialStore(dataRecord.Id, "key", data) require.NoError(t, err) - val, err := b.confidentialRetrieve(bid.Id, "key") + val, err := b.confidentialRetrieve(dataRecord.Id, "key") require.NoError(t, err) require.Equal(t, data, val) // cannot retrieve the value if the caller is not allowed to b.suaveContext.CallerStack = []*common.Address{} - _, err = b.confidentialRetrieve(bid.Id, "key") + _, err = b.confidentialRetrieve(dataRecord.Id, "key") require.Error(t, err) } diff --git a/core/vm/suave.go b/core/vm/suave.go index 62af185b78..5f8ba0a7e7 100644 --- a/core/vm/suave.go +++ b/core/vm/suave.go @@ -17,11 +17,11 @@ import ( // ConfidentialStore represents the API for the confidential store // required by Suave runtime. type ConfidentialStore interface { - InitializeBid(bid types.Bid) (types.Bid, error) - Store(bidId suave.BidId, caller common.Address, key string, value []byte) (suave.Bid, error) - Retrieve(bid types.BidId, caller common.Address, key string) ([]byte, error) - FetchBidById(suave.BidId) (suave.Bid, error) - FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid + InitRecord(record types.DataRecord) (types.DataRecord, error) + Store(id suave.DataId, caller common.Address, key string, value []byte) (suave.DataRecord, error) + Retrieve(record types.DataId, caller common.Address, key string) ([]byte, error) + FetchRecordByID(suave.DataId) (suave.DataRecord, error) + FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord } type SuaveContext struct { @@ -107,8 +107,8 @@ func isPrecompileAddr(addr common.Address) bool { } // Returns the caller -func checkIsPrecompileCallAllowed(suaveContext *SuaveContext, precompile common.Address, bid suave.Bid) (common.Address, error) { - anyPeekerAllowed := slices.Contains(bid.AllowedPeekers, suave.AllowedPeekerAny) +func checkIsPrecompileCallAllowed(suaveContext *SuaveContext, precompile common.Address, record suave.DataRecord) (common.Address, error) { + anyPeekerAllowed := slices.Contains(record.AllowedPeekers, suave.AllowedPeekerAny) if anyPeekerAllowed { for i := len(suaveContext.CallerStack) - 1; i >= 0; i-- { caller := suaveContext.CallerStack[i] @@ -121,13 +121,13 @@ func checkIsPrecompileCallAllowed(suaveContext *SuaveContext, precompile common. } // In question! - // For now both the precompile *and* at least one caller must be allowed to allow access to bid data + // For now both the precompile *and* at least one caller must be allowed to allow access to confidential data // Alternative is to simply allow if any of the callers is allowed - isPrecompileAllowed := slices.Contains(bid.AllowedPeekers, precompile) + isPrecompileAllowed := slices.Contains(record.AllowedPeekers, precompile) // Special case for confStore as those are implicitly allowed if !isPrecompileAllowed && precompile != confidentialStoreAddr && precompile != confidentialRetrieveAddr { - return common.Address{}, fmt.Errorf("precompile %s (%x) not allowed on %x", artifacts.PrecompileAddressToName(precompile), precompile, bid.Id) + return common.Address{}, fmt.Errorf("precompile %s (%x) not allowed on %x", artifacts.PrecompileAddressToName(precompile), precompile, record.Id) } for i := len(suaveContext.CallerStack) - 1; i >= 0; i-- { @@ -135,10 +135,10 @@ func checkIsPrecompileCallAllowed(suaveContext *SuaveContext, precompile common. if caller == nil || *caller == precompile { continue } - if slices.Contains(bid.AllowedPeekers, *caller) { + if slices.Contains(record.AllowedPeekers, *caller) { return *caller, nil } } - return common.Address{}, fmt.Errorf("no caller of %s (%x) is allowed on %x", artifacts.PrecompileAddressToName(precompile), precompile, bid.Id) + return common.Address{}, fmt.Errorf("no caller of %s (%x) is allowed on %x", artifacts.PrecompileAddressToName(precompile), precompile, record.Id) } diff --git a/core/vm/suave_abis.go b/core/vm/suave_abis.go index b190b48dcb..864ce7ad61 100644 --- a/core/vm/suave_abis.go +++ b/core/vm/suave_abis.go @@ -1,3 +1,3 @@ package vm -var bidIdsAbi = mustParseMethodAbi(`[{"inputs": [{ "type": "bytes16[]" }], "name": "bidids", "outputs":[], "type": "function"}]`, "bidids") +var dataIDsAbi = mustParseMethodAbi(`[{"inputs": [{ "type": "bytes16[]" }], "name": "dataids", "outputs":[], "type": "function"}]`, "dataids") diff --git a/eth/api_backend.go b/eth/api_backend.go index b5d20d1f0f..51cadd7807 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -56,13 +56,13 @@ type EthAPIBackend struct { gpo *gasprice.Oracle suaveEthBundleSigningKey *ecdsa.PrivateKey suaveEthBlockSigningKey *bls.SecretKey - suaveEngine *cstore.ConfidentialStoreEngine + suaveEngine *cstore.CStoreEngine suaveEthBackend suave.ConfidentialEthBackend suaveExternalWhitelist []string } // For testing purposes -func (b *EthAPIBackend) SuaveEngine() *cstore.ConfidentialStoreEngine { +func (b *EthAPIBackend) SuaveEngine() *cstore.CStoreEngine { return b.suaveEngine } diff --git a/eth/backend.go b/eth/backend.go index 8c374a4b97..3df4ac35ff 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -285,7 +285,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { suaveDaSigner := &cstore.AccountManagerDASigner{Manager: eth.AccountManager()} - confidentialStoreEngine := cstore.NewConfidentialStoreEngine(confidentialStoreBackend, confidentialStoreTransport, suaveDaSigner, types.LatestSigner(chainConfig)) + confidentialStoreEngine := cstore.NewEngine(confidentialStoreBackend, confidentialStoreTransport, suaveDaSigner, types.LatestSigner(chainConfig)) eth.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, eth, nil, suaveEthBundleSigningKey, suaveEthBlockSigningKey, confidentialStoreEngine, suaveEthBackend, config.Suave.ExternalWhitelist} if eth.APIBackend.allowUnprotectedTxs { diff --git a/miner/worker.go b/miner/worker.go index 908080ed08..25701ee287 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -1340,8 +1340,8 @@ func (w *worker) buildBlockFromBundles(ctx context.Context, args *types.BuildBlo currNonce := work.state.GetNonce(ephemeralAddr) // HACK to include payment txn // multi refund block untested - bidTx := bundle.Txs[0] // NOTE : assumes first txn is refund recipient - refundAddr, err := types.Sender(types.LatestSignerForChainID(bidTx.ChainId()), bidTx) + userTx := bundle.Txs[0] // NOTE : assumes first txn is refund recipient + refundAddr, err := types.Sender(types.LatestSignerForChainID(userTx.ChainId()), userTx) if err != nil { return nil, nil, err } diff --git a/suave/artifacts/SuaveLib.json b/suave/artifacts/SuaveLib.json index 425fea3bec..0621c8e464 100644 --- a/suave/artifacts/SuaveLib.json +++ b/suave/artifacts/SuaveLib.json @@ -1 +1 @@ -[{"type":"error","name":"PeekerReverted","inputs":[{"name":"addr","type":"address"},{"name":"err","type":"bytes"}]},{"type":"function","name":"buildEthBlock","inputs":[{"name":"blockArgs","type":"tuple","internalType":"struct Suave.BuildBlockArgs","components":[{"name":"slot","type":"uint64","internalType":"uint64"},{"name":"proposerPubkey","type":"bytes","internalType":"bytes"},{"name":"parent","type":"bytes32","internalType":"bytes32"},{"name":"timestamp","type":"uint64","internalType":"uint64"},{"name":"feeRecipient","type":"address","internalType":"address"},{"name":"gasLimit","type":"uint64","internalType":"uint64"},{"name":"random","type":"bytes32","internalType":"bytes32"},{"name":"withdrawals","type":"tuple[]","internalType":"struct Suave.Withdrawal[]","components":[{"name":"index","type":"uint64","internalType":"uint64"},{"name":"validator","type":"uint64","internalType":"uint64"},{"name":"Address","type":"address","internalType":"address"},{"name":"amount","type":"uint64","internalType":"uint64"}]},{"name":"extra","type":"bytes","internalType":"bytes"}]},{"name":"bidId","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"namespace","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"},{"name":"output2","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialInputs","outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialRetrieve","inputs":[{"name":"bidId","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"key","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialStore","inputs":[{"name":"bidId","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"key","type":"string","internalType":"string"},{"name":"data1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"doHTTPRequest","inputs":[{"name":"request","type":"tuple","internalType":"struct Suave.HttpRequest","components":[{"name":"url","type":"string","internalType":"string"},{"name":"method","type":"string","internalType":"string"},{"name":"headers","type":"string[]","internalType":"string[]"},{"name":"body","type":"bytes","internalType":"bytes"}]}],"outputs":[{"name":"response","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"ethcall","inputs":[{"name":"contractAddr","type":"address","internalType":"address"},{"name":"input1","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"extractHint","inputs":[{"name":"bundleData","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"fetchBids","inputs":[{"name":"cond","type":"uint64","internalType":"uint64"},{"name":"namespace","type":"string","internalType":"string"}],"outputs":[{"name":"bid","type":"tuple[]","internalType":"struct Suave.Bid[]","components":[{"name":"id","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"salt","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"version","type":"string","internalType":"string"}]}]},{"type":"function","name":"fillMevShareBundle","inputs":[{"name":"bidId","type":"bytes16","internalType":"struct Suave.BidId"}],"outputs":[{"name":"encodedBundle","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"newBid","inputs":[{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"bidType","type":"string","internalType":"string"}],"outputs":[{"name":"bid","type":"tuple","internalType":"struct Suave.Bid","components":[{"name":"id","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"salt","type":"bytes16","internalType":"struct Suave.BidId"},{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"version","type":"string","internalType":"string"}]}]},{"type":"function","name":"signEthTransaction","inputs":[{"name":"txn","type":"bytes","internalType":"bytes"},{"name":"chainId","type":"string","internalType":"string"},{"name":"signingKey","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"simulateBundle","inputs":[{"name":"bundleData","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"uint64","internalType":"uint64"}]},{"type":"function","name":"submitBundleJsonRPC","inputs":[{"name":"url","type":"string","internalType":"string"},{"name":"method","type":"string","internalType":"string"},{"name":"params","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"submitEthBlockBidToRelay","inputs":[{"name":"relayUrl","type":"string","internalType":"string"},{"name":"builderBid","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]}] \ No newline at end of file +[{"type":"error","name":"PeekerReverted","inputs":[{"name":"addr","type":"address"},{"name":"err","type":"bytes"}]},{"type":"function","name":"buildEthBlock","inputs":[{"name":"blockArgs","type":"tuple","internalType":"struct Suave.BuildBlockArgs","components":[{"name":"slot","type":"uint64","internalType":"uint64"},{"name":"proposerPubkey","type":"bytes","internalType":"bytes"},{"name":"parent","type":"bytes32","internalType":"bytes32"},{"name":"timestamp","type":"uint64","internalType":"uint64"},{"name":"feeRecipient","type":"address","internalType":"address"},{"name":"gasLimit","type":"uint64","internalType":"uint64"},{"name":"random","type":"bytes32","internalType":"bytes32"},{"name":"withdrawals","type":"tuple[]","internalType":"struct Suave.Withdrawal[]","components":[{"name":"index","type":"uint64","internalType":"uint64"},{"name":"validator","type":"uint64","internalType":"uint64"},{"name":"Address","type":"address","internalType":"address"},{"name":"amount","type":"uint64","internalType":"uint64"}]},{"name":"extra","type":"bytes","internalType":"bytes"}]},{"name":"dataId","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"namespace","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"},{"name":"output2","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialInputs","outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialRetrieve","inputs":[{"name":"dataId","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"key","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"confidentialStore","inputs":[{"name":"dataId","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"key","type":"string","internalType":"string"},{"name":"data1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"doHTTPRequest","inputs":[{"name":"request","type":"tuple","internalType":"struct Suave.HttpRequest","components":[{"name":"url","type":"string","internalType":"string"},{"name":"method","type":"string","internalType":"string"},{"name":"headers","type":"string[]","internalType":"string[]"},{"name":"body","type":"bytes","internalType":"bytes"}]}],"outputs":[{"name":"response","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"ethcall","inputs":[{"name":"contractAddr","type":"address","internalType":"address"},{"name":"input1","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"extractHint","inputs":[{"name":"bundleData","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"fetchDataRecords","inputs":[{"name":"cond","type":"uint64","internalType":"uint64"},{"name":"namespace","type":"string","internalType":"string"}],"outputs":[{"name":"dataRecords","type":"tuple[]","internalType":"struct Suave.DataRecord[]","components":[{"name":"id","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"salt","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"version","type":"string","internalType":"string"}]}]},{"type":"function","name":"fillMevShareBundle","inputs":[{"name":"dataId","type":"bytes16","internalType":"struct Suave.DataId"}],"outputs":[{"name":"encodedBundle","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"newDataRecord","inputs":[{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"dataType","type":"string","internalType":"string"}],"outputs":[{"name":"dataRecord","type":"tuple","internalType":"struct Suave.DataRecord","components":[{"name":"id","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"salt","type":"bytes16","internalType":"struct Suave.DataId"},{"name":"decryptionCondition","type":"uint64","internalType":"uint64"},{"name":"allowedPeekers","type":"address[]","internalType":"address[]"},{"name":"allowedStores","type":"address[]","internalType":"address[]"},{"name":"version","type":"string","internalType":"string"}]}]},{"type":"function","name":"signEthTransaction","inputs":[{"name":"txn","type":"bytes","internalType":"bytes"},{"name":"chainId","type":"string","internalType":"string"},{"name":"signingKey","type":"string","internalType":"string"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"simulateBundle","inputs":[{"name":"bundleData","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"uint64","internalType":"uint64"}]},{"type":"function","name":"submitBundleJsonRPC","inputs":[{"name":"url","type":"string","internalType":"string"},{"name":"method","type":"string","internalType":"string"},{"name":"params","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]},{"type":"function","name":"submitEthBlockBidToRelay","inputs":[{"name":"relayUrl","type":"string","internalType":"string"},{"name":"builderBid","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"output1","type":"bytes","internalType":"bytes"}]}] \ No newline at end of file diff --git a/suave/artifacts/addresses.go b/suave/artifacts/addresses.go index a8fcdca8e3..64fb675800 100644 --- a/suave/artifacts/addresses.go +++ b/suave/artifacts/addresses.go @@ -1,5 +1,5 @@ // Code generated by suave/gen. DO NOT EDIT. -// Hash: cdc3a0bf9b0cd1b4a4b17e6245d7e942f42ffc5f7333bc11a220abbc67d6587b +// Hash: 80e00d3e46ad61ee6925143b317f91c0ad551d66908d0ab20e244db63b40ff40 package artifacts import ( @@ -15,9 +15,9 @@ var ( doHTTPRequestAddr = common.HexToAddress("0x0000000000000000000000000000000043200002") ethcallAddr = common.HexToAddress("0x0000000000000000000000000000000042100003") extractHintAddr = common.HexToAddress("0x0000000000000000000000000000000042100037") - fetchBidsAddr = common.HexToAddress("0x0000000000000000000000000000000042030001") + fetchDataRecordsAddr = common.HexToAddress("0x0000000000000000000000000000000042030001") fillMevShareBundleAddr = common.HexToAddress("0x0000000000000000000000000000000043200001") - newBidAddr = common.HexToAddress("0x0000000000000000000000000000000042030000") + newDataRecordAddr = common.HexToAddress("0x0000000000000000000000000000000042030000") signEthTransactionAddr = common.HexToAddress("0x0000000000000000000000000000000040100001") simulateBundleAddr = common.HexToAddress("0x0000000000000000000000000000000042100000") submitBundleJsonRPCAddr = common.HexToAddress("0x0000000000000000000000000000000043000001") @@ -32,9 +32,9 @@ var SuaveMethods = map[string]common.Address{ "doHTTPRequest": doHTTPRequestAddr, "ethcall": ethcallAddr, "extractHint": extractHintAddr, - "fetchBids": fetchBidsAddr, + "fetchDataRecords": fetchDataRecordsAddr, "fillMevShareBundle": fillMevShareBundleAddr, - "newBid": newBidAddr, + "newDataRecord": newDataRecordAddr, "signEthTransaction": signEthTransactionAddr, "simulateBundle": simulateBundleAddr, "submitBundleJsonRPC": submitBundleJsonRPCAddr, @@ -57,12 +57,12 @@ func PrecompileAddressToName(addr common.Address) string { return "ethcall" case extractHintAddr: return "extractHint" - case fetchBidsAddr: - return "fetchBids" + case fetchDataRecordsAddr: + return "fetchDataRecords" case fillMevShareBundleAddr: return "fillMevShareBundle" - case newBidAddr: - return "newBid" + case newDataRecordAddr: + return "newDataRecord" case signEthTransactionAddr: return "signEthTransaction" case simulateBundleAddr: diff --git a/suave/cmd/suavecli/main.go b/suave/cmd/suavecli/main.go index 9e36b1d982..06d1509185 100644 --- a/suave/cmd/suavecli/main.go +++ b/suave/cmd/suavecli/main.go @@ -125,19 +125,19 @@ func waitForTransactionToBeConfirmed(suaveClient *rpc.Client, txHash *common.Has utils.Fatalf("did not see the receipt succeed in time. hash: %s", txHash.String()) } -func extractBidId(suaveClient *rpc.Client, txHash common.Hash) (suave.BidId, error) { +func extractBidId(suaveClient *rpc.Client, txHash common.Hash) (suave.DataId, error) { var r *types.Receipt err := suaveClient.Call(&r, "eth_getTransactionReceipt", &txHash) if err == nil && r != nil { unpacked, err := mevShareABI.Events["HintEvent"].Inputs.Unpack(r.Logs[1].Data) // index = 1 because second hint is bid event if err != nil { - return suave.BidId{0}, err + return suave.DataId{0}, err } shareBidId := unpacked[0].([16]byte) return shareBidId, nil } - return suave.BidId{0}, err + return suave.DataId{0}, err } func setUpSuaveAndGoerli(privKeyHex *string, kettleAddressHex *string, suaveRpc *string, goerliRpc *string) (*ecdsa.PrivateKey, common.Address, *rpc.Client, *rpc.Client, types.Signer, types.Signer) { diff --git a/suave/cmd/suavecli/sendMevShareMatch.go b/suave/cmd/suavecli/sendMevShareMatch.go index 1c9a59c14b..df9525761d 100644 --- a/suave/cmd/suavecli/sendMevShareMatch.go +++ b/suave/cmd/suavecli/sendMevShareMatch.go @@ -98,7 +98,7 @@ func sendMevShareMatchTx( mevShareAddr common.Address, blockSenderAddr common.Address, kettleAddress common.Address, - matchBidId types.BidId, + matchBidId types.DataId, // account specific privKey *ecdsa.PrivateKey, ) (*common.Hash, error) { diff --git a/suave/core/types.go b/suave/core/types.go index e216051035..c7de9cd998 100644 --- a/suave/core/types.go +++ b/suave/core/types.go @@ -14,11 +14,11 @@ import ( var AllowedPeekerAny = common.HexToAddress("0xC8df3686b4Afb2BB53e60EAe97EF043FE03Fb829") // "*" type Bytes = hexutil.Bytes -type BidId = types.BidId +type DataId = types.DataId -type Bid struct { - Id types.BidId - Salt types.BidId +type DataRecord struct { + Id types.DataId + Salt types.DataId DecryptionCondition uint64 AllowedPeekers []common.Address AllowedStores []common.Address @@ -27,8 +27,8 @@ type Bid struct { Signature []byte } -func (b *Bid) ToInnerBid() types.Bid { - return types.Bid{ +func (b *DataRecord) ToInnerRecord() types.DataRecord { + return types.DataRecord{ Id: b.Id, Salt: b.Salt, DecryptionCondition: b.DecryptionCondition, @@ -38,26 +38,26 @@ func (b *Bid) ToInnerBid() types.Bid { } } -type MEVMBid = types.Bid +type MEVMBid = types.DataRecord type BuildBlockArgs = types.BuildBlockArgs var ConfStoreAllowedAny common.Address = common.HexToAddress("0x42") var ( - ErrBidAlreadyPresent = errors.New("bid already present") - ErrBidNotFound = errors.New("bid not found") - ErrUnsignedFinalize = errors.New("finalize called with unsigned transaction, refusing to propagate") + ErrRecordAlreadyPresent = errors.New("data record already present") + ErrRecordNotFound = errors.New("data record not found") + ErrUnsignedFinalize = errors.New("finalize called with unsigned transaction, refusing to propagate") ) type ConfidentialStoreBackend interface { node.Lifecycle - InitializeBid(bid Bid) error - Store(bid Bid, caller common.Address, key string, value []byte) (Bid, error) - Retrieve(bid Bid, caller common.Address, key string) ([]byte, error) - FetchBidById(BidId) (Bid, error) - FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []Bid + InitializeBid(record DataRecord) error + Store(record DataRecord, caller common.Address, key string, value []byte) (DataRecord, error) + Retrieve(record DataRecord, caller common.Address, key string) ([]byte, error) + FetchBidById(DataId) (DataRecord, error) + FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []DataRecord } type ConfidentialEthBackend interface { diff --git a/suave/core/utils.go b/suave/core/utils.go index ba4b59b994..b6323c074a 100644 --- a/suave/core/utils.go +++ b/suave/core/utils.go @@ -7,8 +7,8 @@ import ( "github.com/google/uuid" ) -func RandomBidId() types.BidId { - return types.BidId(uuid.New()) +func RandomDataRecordId() types.DataId { + return types.DataId(uuid.New()) } func MustEncode[T any](data T) []byte { diff --git a/suave/cstore/backend_testing.go b/suave/cstore/backend_testing.go index 2adebffd4d..9ab1ff7ef2 100644 --- a/suave/cstore/backend_testing.go +++ b/suave/cstore/backend_testing.go @@ -9,28 +9,28 @@ import ( ) func testBackendStore(t *testing.T, store ConfidentialStorageBackend) { - bid := suave.Bid{ - Id: suave.RandomBidId(), + record := suave.DataRecord{ + Id: suave.RandomDataRecordId(), DecryptionCondition: 10, AllowedPeekers: []common.Address{common.HexToAddress("0x424344")}, Version: "default:v0:ethBundles", } - err := store.InitializeBid(bid) + err := store.InitRecord(record) require.NoError(t, err) - bidRes, err := store.FetchBidById(bid.Id) + recordRes, err := store.FetchRecordByID(record.Id) require.NoError(t, err) - require.Equal(t, bid, bidRes) + require.Equal(t, record, recordRes) - _, err = store.Store(bid, bid.AllowedPeekers[0], "xx", []byte{0x43, 0x14}) + _, err = store.Store(record, record.AllowedPeekers[0], "xx", []byte{0x43, 0x14}) require.NoError(t, err) - retrievedData, err := store.Retrieve(bid, bid.AllowedPeekers[0], "xx") + retrievedData, err := store.Retrieve(record, record.AllowedPeekers[0], "xx") require.NoError(t, err) require.Equal(t, []byte{0x43, 0x14}, retrievedData) - bids := store.FetchBidsByProtocolAndBlock(10, "default:v0:ethBundles") - require.Len(t, bids, 1) - require.Equal(t, bid, bids[0]) + records := store.FetchRecordsByProtocolAndBlock(10, "default:v0:ethBundles") + require.Len(t, records, 1) + require.Equal(t, record, records[0]) } diff --git a/suave/cstore/engine.go b/suave/cstore/engine.go index 6b98185201..20642b868d 100644 --- a/suave/cstore/engine.go +++ b/suave/cstore/engine.go @@ -18,11 +18,11 @@ import ( // ConfidentialStorageBackend is the interface that must be implemented by a // storage backend for the confidential storage engine. type ConfidentialStorageBackend interface { - InitializeBid(bid suave.Bid) error - Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) - Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) - FetchBidById(suave.BidId) (suave.Bid, error) - FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid + InitRecord(record suave.DataRecord) error + Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) + Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) + FetchRecordByID(suave.DataId) (suave.DataRecord, error) + FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord Stop() error } @@ -42,10 +42,10 @@ type DAMessage struct { } type StoreWrite struct { - Bid suave.Bid `json:"bid"` - Caller common.Address `json:"caller"` - Key string `json:"key"` - Value suave.Bytes `json:"value"` + DataRecord suave.DataRecord `json:"dataRecord"` + Caller common.Address `json:"caller"` + Key string `json:"key"` + Value suave.Bytes `json:"value"` } type DASigner interface { @@ -58,7 +58,7 @@ type ChainSigner interface { Sender(tx *types.Transaction) (common.Address, error) } -type ConfidentialStoreEngine struct { +type CStoreEngine struct { ctx context.Context cancel context.CancelFunc @@ -72,13 +72,14 @@ type ConfidentialStoreEngine struct { localAddresses map[common.Address]struct{} } -func NewConfidentialStoreEngine(backend ConfidentialStorageBackend, transportTopic StoreTransportTopic, daSigner DASigner, chainSigner ChainSigner) *ConfidentialStoreEngine { +// NewEngine creates a new instance of CStoreEngine. +func NewEngine(backend ConfidentialStorageBackend, transportTopic StoreTransportTopic, daSigner DASigner, chainSigner ChainSigner) *CStoreEngine { localAddresses := make(map[common.Address]struct{}) for _, addr := range daSigner.LocalAddresses() { localAddresses[addr] = struct{}{} } - return &ConfidentialStoreEngine{ + return &CStoreEngine{ storage: backend, transportTopic: transportTopic, daSigner: daSigner, @@ -88,15 +89,17 @@ func NewConfidentialStoreEngine(backend ConfidentialStorageBackend, transportTop } } -func (e *ConfidentialStoreEngine) NewTransactionalStore(sourceTx *types.Transaction) *TransactionalStore { +// NewTransactionalStore creates a new transactional store. +func (e *CStoreEngine) NewTransactionalStore(sourceTx *types.Transaction) *TransactionalStore { return &TransactionalStore{ - sourceTx: sourceTx, - engine: e, - pendingBids: make(map[suave.BidId]suave.Bid), + sourceTx: sourceTx, + engine: e, + pendingRecords: make(map[suave.DataId]suave.DataRecord), } } -func (e *ConfidentialStoreEngine) Start() error { +// Start initializes the CStoreEngine. +func (e *CStoreEngine) Start() error { if err := e.transportTopic.Start(); err != nil { return err } @@ -113,7 +116,8 @@ func (e *ConfidentialStoreEngine) Start() error { return nil } -func (e *ConfidentialStoreEngine) Stop() error { +// Stop terminates the CStoreEngine. +func (e *CStoreEngine) Stop() error { if e.cancel == nil { return errors.New("Confidential engine: Stop() called before Start()") } @@ -131,12 +135,13 @@ func (e *ConfidentialStoreEngine) Stop() error { return nil } -// For testing purposes! -func (e *ConfidentialStoreEngine) Backend() ConfidentialStorageBackend { +// Backend provides for testing purposes access to the underlying ConfidentialStorageBackend. +func (e *CStoreEngine) Backend() ConfidentialStorageBackend { return e.storage } -func (e *ConfidentialStoreEngine) ProcessMessages() { +// ProcessMessages handles incoming messages. +func (e *CStoreEngine) ProcessMessages() { ch, cancel := e.transportTopic.Subscribe() defer cancel() @@ -155,83 +160,88 @@ func (e *ConfidentialStoreEngine) ProcessMessages() { } } -func (e *ConfidentialStoreEngine) InitializeBid(bid types.Bid, creationTx *types.Transaction) (suave.Bid, error) { +// InitRecord prepares a data record for storage. +func (e *CStoreEngine) InitRecord(record types.DataRecord, creationTx *types.Transaction) (suave.DataRecord, error) { // Share with all stores this node trusts - bid.AllowedStores = append(bid.AllowedStores, e.daSigner.LocalAddresses()...) + record.AllowedStores = append(record.AllowedStores, e.daSigner.LocalAddresses()...) - expectedId, err := calculateBidId(bid) + expectedId, err := calculateRecordId(record) if err != nil { - return suave.Bid{}, fmt.Errorf("confidential engine: could not initialize new bid: %w", err) + return suave.DataRecord{}, fmt.Errorf("confidential engine: could not initialize new record: %w", err) } - if bid.Id == emptyId { - bid.Id = expectedId - } else if bid.Id != expectedId { + if isEmptyID(record.Id) { + record.Id = expectedId + } else if record.Id != expectedId { // True in some tests, might be time to rewrite them - return suave.Bid{}, errors.New("confidential engine:incorrect bid id passed") + return suave.DataRecord{}, errors.New("confidential engine: incorrect record id passed") } - initializedBid := suave.Bid{ - Id: bid.Id, - Salt: bid.Salt, - DecryptionCondition: bid.DecryptionCondition, - AllowedPeekers: bid.AllowedPeekers, - AllowedStores: bid.AllowedStores, - Version: bid.Version, + initializedRecord := suave.DataRecord{ + Id: record.Id, + Salt: record.Salt, + DecryptionCondition: record.DecryptionCondition, + AllowedPeekers: record.AllowedPeekers, + AllowedStores: record.AllowedStores, + Version: record.Version, CreationTx: creationTx, } - bidBytes, err := SerializeBidForSigning(&initializedBid) + reocrdBytes, err := SerializeDataRecord(&initializedRecord) if err != nil { - return suave.Bid{}, fmt.Errorf("confidential engine: could not hash bid for signing: %w", err) + return suave.DataRecord{}, fmt.Errorf("confidential engine: could not hash record for signing: %w", err) } signingAccount, err := KettleAddressFromTransaction(creationTx) if err != nil { - return suave.Bid{}, fmt.Errorf("confidential engine: could not recover execution node from creation transaction: %w", err) + return suave.DataRecord{}, fmt.Errorf("confidential engine: could not recover execution node from creation transaction: %w", err) } - initializedBid.Signature, err = e.daSigner.Sign(signingAccount, bidBytes) + initializedRecord.Signature, err = e.daSigner.Sign(signingAccount, reocrdBytes) if err != nil { - return suave.Bid{}, fmt.Errorf("confidential engine: could not sign initialized bid: %w", err) + return suave.DataRecord{}, fmt.Errorf("confidential engine: could not sign initialized record: %w", err) } - return initializedBid, nil + return initializedRecord, nil } -func (e *ConfidentialStoreEngine) FetchBidById(bidId suave.BidId) (suave.Bid, error) { - return e.storage.FetchBidById(bidId) +// FetchRecordByID retrieves a data record by its identifier. +func (e *CStoreEngine) FetchRecordByID(id suave.DataId) (suave.DataRecord, error) { + return e.storage.FetchRecordByID(id) } -func (e *ConfidentialStoreEngine) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { - return e.storage.FetchBidsByProtocolAndBlock(blockNumber, namespace) +// FetchRecordsByProtocolAndBlock fetches data records based on protocol and block number. +func (e *CStoreEngine) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { + return e.storage.FetchRecordsByProtocolAndBlock(blockNumber, namespace) } -func (e *ConfidentialStoreEngine) Retrieve(bidId suave.BidId, caller common.Address, key string) ([]byte, error) { - bid, err := e.storage.FetchBidById(bidId) +// Retrieve fetches data associated with a record. +func (e *CStoreEngine) Retrieve(id suave.DataId, caller common.Address, key string) ([]byte, error) { + record, err := e.storage.FetchRecordByID(id) if err != nil { - return []byte{}, fmt.Errorf("confidential engine: could not fetch bid %x while retrieving: %w", bidId, err) + return []byte{}, fmt.Errorf("confidential engine: could not fetch record %x while retrieving: %w", id, err) } - if !slices.Contains(bid.AllowedPeekers, caller) && !slices.Contains(bid.AllowedPeekers, suave.AllowedPeekerAny) { - return []byte{}, fmt.Errorf("confidential engine: %x not allowed to retrieve %s on %x", caller, key, bidId) + if !slices.Contains(record.AllowedPeekers, caller) && !slices.Contains(record.AllowedPeekers, suave.AllowedPeekerAny) { + return []byte{}, fmt.Errorf("confidential engine: %x not allowed to retrieve %s on %x", caller, key, id) } - return e.storage.Retrieve(bid, caller, key) + return e.storage.Retrieve(record, caller, key) } -func (e *ConfidentialStoreEngine) Finalize(tx *types.Transaction, newBids map[suave.BidId]suave.Bid, stores []StoreWrite) error { +// Finalize finalizes a transaction and updates the store. +func (e *CStoreEngine) Finalize(tx *types.Transaction, newRecords map[suave.DataId]suave.DataRecord, stores []StoreWrite) error { // - for _, bid := range newBids { - err := e.storage.InitializeBid(bid) + for _, record := range newRecords { + err := e.storage.InitRecord(record) if err != nil { // TODO: deinitialize! - return fmt.Errorf("confidential engine: store backend failed to initialize bid: %w", err) + return fmt.Errorf("confidential engine: store backend failed to initialize record: %w", err) } } for _, sw := range stores { - if _, err := e.storage.Store(sw.Bid, sw.Caller, sw.Key, sw.Value); err != nil { + if _, err := e.storage.Store(sw.DataRecord, sw.Caller, sw.Key, sw.Value); err != nil { // TODO: deinitialize and deStore! return fmt.Errorf("failed to store data: %w", err) } @@ -249,7 +259,7 @@ func (e *ConfidentialStoreEngine) Finalize(tx *types.Transaction, newBids map[su return suave.ErrUnsignedFinalize } - msgBytes, err := SerializeMessageForSigning(&pwMsg) + msgBytes, err := SerializeDAMessage(&pwMsg) if err != nil { return fmt.Errorf("confidential engine: could not hash message for signing: %w", err) } @@ -270,11 +280,12 @@ func (e *ConfidentialStoreEngine) Finalize(tx *types.Transaction, newBids map[su return nil } -func (e *ConfidentialStoreEngine) NewMessage(message DAMessage) error { +// NewMessage processes a new incoming DAMessage. +func (e *CStoreEngine) NewMessage(message DAMessage) error { // Note the validation is a work in progress and not guaranteed to be correct! // Message-level validation - msgBytes, err := SerializeMessageForSigning(&message) + msgBytes, err := SerializeDAMessage(&message) if err != nil { return fmt.Errorf("confidential engine: could not hash received message: %w", err) } @@ -305,66 +316,66 @@ func (e *ConfidentialStoreEngine) NewMessage(message DAMessage) error { // TODO: check if message.SourceTx is valid and insert it into the mempool! - // Bid level validation + // DataRecord level validation for _, sw := range message.StoreWrites { - expectedId, err := calculateBidId(types.Bid{ - Id: sw.Bid.Id, - Salt: sw.Bid.Salt, - DecryptionCondition: sw.Bid.DecryptionCondition, - AllowedPeekers: sw.Bid.AllowedPeekers, - AllowedStores: sw.Bid.AllowedStores, - Version: sw.Bid.Version, + expectedId, err := calculateRecordId(types.DataRecord{ + Id: sw.DataRecord.Id, + Salt: sw.DataRecord.Salt, + DecryptionCondition: sw.DataRecord.DecryptionCondition, + AllowedPeekers: sw.DataRecord.AllowedPeekers, + AllowedStores: sw.DataRecord.AllowedStores, + Version: sw.DataRecord.Version, }) if err != nil { - return fmt.Errorf("confidential engine: could not calculate received bids id: %w", err) + return fmt.Errorf("confidential engine: could not calculate received records id: %w", err) } - if expectedId != sw.Bid.Id { - return fmt.Errorf("confidential engine: received bids id (%x) does not match the expected (%x)", sw.Bid.Id, expectedId) + if expectedId != sw.DataRecord.Id { + return fmt.Errorf("confidential engine: received records id (%x) does not match the expected (%x)", sw.DataRecord.Id, expectedId) } - bidBytes, err := SerializeBidForSigning(&sw.Bid) + reocrdBytes, err := SerializeDataRecord(&sw.DataRecord) if err != nil { - return fmt.Errorf("confidential engine: could not hash received bid: %w", err) + return fmt.Errorf("confidential engine: could not hash received record: %w", err) } - recoveredBidSigner, err := e.daSigner.Sender(bidBytes, sw.Bid.Signature) + recoveredRecordSigner, err := e.daSigner.Sender(reocrdBytes, sw.DataRecord.Signature) if err != nil { - return fmt.Errorf("confidential engine: incorrect bid signature: %w", err) + return fmt.Errorf("confidential engine: incorrect record signature: %w", err) } - expectedBidSigner, err := KettleAddressFromTransaction(sw.Bid.CreationTx) + expectedRecordSigner, err := KettleAddressFromTransaction(sw.DataRecord.CreationTx) if err != nil { - return fmt.Errorf("confidential engine: could not recover signer from bid: %w", err) + return fmt.Errorf("confidential engine: could not recover signer from record: %w", err) } - if recoveredBidSigner != expectedBidSigner { - return fmt.Errorf("confidential engine: bid signer %x, expected %x", recoveredBidSigner, expectedBidSigner) + if recoveredRecordSigner != expectedRecordSigner { + return fmt.Errorf("confidential engine: record signer %x, expected %x", recoveredRecordSigner, expectedRecordSigner) } - if !slices.Contains(sw.Bid.AllowedStores, recoveredMessageSigner) { - return fmt.Errorf("confidential engine: sw signer %x not allowed to store on bid %x", recoveredMessageSigner, sw.Bid.Id) + if !slices.Contains(sw.DataRecord.AllowedStores, recoveredMessageSigner) { + return fmt.Errorf("confidential engine: sw signer %x not allowed to store on record %x", recoveredMessageSigner, sw.DataRecord.Id) } - if !slices.Contains(sw.Bid.AllowedPeekers, sw.Caller) && !slices.Contains(sw.Bid.AllowedPeekers, suave.AllowedPeekerAny) { - return fmt.Errorf("confidential engine: caller %x not allowed on bid %x", sw.Caller, sw.Bid.Id) + if !slices.Contains(sw.DataRecord.AllowedPeekers, sw.Caller) && !slices.Contains(sw.DataRecord.AllowedPeekers, suave.AllowedPeekerAny) { + return fmt.Errorf("confidential engine: caller %x not allowed on record %x", sw.Caller, sw.DataRecord.Id) } // TODO: move to types.Sender() - _, err = e.chainSigner.Sender(sw.Bid.CreationTx) + _, err = e.chainSigner.Sender(sw.DataRecord.CreationTx) if err != nil { - return fmt.Errorf("confidential engine: creation tx for bid id %x is not signed properly: %w", sw.Bid.Id, err) + return fmt.Errorf("confidential engine: creation tx for record id %x is not signed properly: %w", sw.DataRecord.Id, err) } } for _, sw := range message.StoreWrites { - err = e.storage.InitializeBid(sw.Bid) + err = e.storage.InitRecord(sw.DataRecord) if err != nil { - if !errors.Is(err, suave.ErrBidAlreadyPresent) { - log.Error("confidential engine: unexpected error while initializing bid from transport: %w", err) + if !errors.Is(err, suave.ErrRecordAlreadyPresent) { + log.Error("confidential engine: unexpected error while initializing record from transport: %w", err) continue // Don't abandon! } } - _, err = e.storage.Store(sw.Bid, sw.Caller, sw.Key, sw.Value) + _, err = e.storage.Store(sw.DataRecord, sw.Caller, sw.Key, sw.Value) if err != nil { log.Error("confidential engine: unexpected error while storing: %w", err) continue // Don't abandon! @@ -374,24 +385,26 @@ func (e *ConfidentialStoreEngine) NewMessage(message DAMessage) error { return nil } -func SerializeBidForSigning(bid *suave.Bid) ([]byte, error) { - bidBytes, err := json.Marshal(suave.Bid{ - Id: bid.Id, - Salt: bid.Salt, - DecryptionCondition: bid.DecryptionCondition, - AllowedPeekers: bid.AllowedPeekers, - AllowedStores: bid.AllowedStores, - Version: bid.Version, - CreationTx: bid.CreationTx, +// SerializeDataRecord prepares a data record for signing. +func SerializeDataRecord(record *suave.DataRecord) ([]byte, error) { + recordBytes, err := json.Marshal(suave.DataRecord{ + Id: record.Id, + Salt: record.Salt, + DecryptionCondition: record.DecryptionCondition, + AllowedPeekers: record.AllowedPeekers, + AllowedStores: record.AllowedStores, + Version: record.Version, + CreationTx: record.CreationTx, }) if err != nil { return []byte{}, err } - return []byte(fmt.Sprintf("\x19Suave Signed Message:\n%d%s", len(bidBytes), string(bidBytes))), nil + return []byte(fmt.Sprintf("\x19Suave Signed Message:\n%d%s", len(recordBytes), string(recordBytes))), nil } -func SerializeMessageForSigning(message *DAMessage) ([]byte, error) { +// SerializeDAMessage prepares a DAMessage for signing. +func SerializeDAMessage(message *DAMessage) ([]byte, error) { msgBytes, err := json.Marshal(DAMessage{ SourceTx: message.SourceTx, StoreWrites: message.StoreWrites, @@ -405,6 +418,50 @@ func SerializeMessageForSigning(message *DAMessage) ([]byte, error) { return []byte(fmt.Sprintf("\x19Suave Signed Message:\n%d%s", len(msgBytes), string(msgBytes))), nil } +// KettleAddressFromTransaction returns address of kettle that executed confidential transaction +func KettleAddressFromTransaction(tx *types.Transaction) (common.Address, error) { + innerExecutedTx, ok := types.CastTxInner[*types.SuaveTransaction](tx) + if ok { + return innerExecutedTx.ConfidentialComputeRequest.KettleAddress, nil + } + + innerRequestTx, ok := types.CastTxInner[*types.ConfidentialComputeRequest](tx) + if ok { + return innerRequestTx.KettleAddress, nil + } + + return common.Address{}, fmt.Errorf("transaction is not of confidential type") +} + +var emptyId [16]byte + +var recordUuidSpace = uuid.UUID{0x42} + +func calculateRecordId(record types.DataRecord) (types.DataId, error) { + copy(record.Id[:], emptyId[:]) + + body, err := json.Marshal(record) + if err != nil { + return types.DataId{}, fmt.Errorf("could not marshal record to calculate its id: %w", err) + } + + uuidv5 := uuid.NewSHA1(recordUuidSpace, body) + copy(record.Id[:], uuidv5[:]) + + return record.Id, nil +} + +func RandomRecordId() types.DataId { + return types.DataId(uuid.New()) +} + +// isEmptyID checks if the given DataId is empty. +func isEmptyID(id types.DataId) bool { + return id == emptyId +} + +// Mocks + type MockTransport struct{} func (MockTransport) Start() error { return nil } @@ -438,39 +495,3 @@ func (MockChainSigner) Sender(tx *types.Transaction) (common.Address, error) { return types.NewSuaveSigner(tx.ChainId()).Sender(tx) } - -func KettleAddressFromTransaction(tx *types.Transaction) (common.Address, error) { - innerExecutedTx, ok := types.CastTxInner[*types.SuaveTransaction](tx) - if ok { - return innerExecutedTx.ConfidentialComputeRequest.KettleAddress, nil - } - - innerRequestTx, ok := types.CastTxInner[*types.ConfidentialComputeRequest](tx) - if ok { - return innerRequestTx.KettleAddress, nil - } - - return common.Address{}, fmt.Errorf("transaction is not of confidential type") -} - -var emptyId [16]byte - -var bidUuidSpace = uuid.UUID{0x42} - -func calculateBidId(bid types.Bid) (types.BidId, error) { - copy(bid.Id[:], emptyId[:]) - - body, err := json.Marshal(bid) - if err != nil { - return types.BidId{}, fmt.Errorf("could not marshal bid to calculate its id: %w", err) - } - - uuidv5 := uuid.NewSHA1(bidUuidSpace, body) - copy(bid.Id[:], uuidv5[:]) - - return bid.Id, nil -} - -func RandomBidId() types.BidId { - return types.BidId(uuid.New()) -} diff --git a/suave/cstore/engine_test.go b/suave/cstore/engine_test.go index c7d5b2bfb0..be9609d4b4 100644 --- a/suave/cstore/engine_test.go +++ b/suave/cstore/engine_test.go @@ -26,45 +26,47 @@ func (FakeDASigner) Sender(data []byte, signature []byte) (common.Address, error func (f FakeDASigner) LocalAddresses() []common.Address { return f.localAddresses } type FakeStoreBackend struct { - OnStore func(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) + OnStore func(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) } func (*FakeStoreBackend) Start() error { return nil } func (*FakeStoreBackend) Stop() error { return nil } -func (*FakeStoreBackend) InitializeBid(bid suave.Bid) error { return nil } -func (*FakeStoreBackend) FetchEngineBidById(bidId suave.BidId) (suave.Bid, error) { - return suave.Bid{}, errors.New("not implemented") +func (*FakeStoreBackend) InitRecord(record suave.DataRecord) error { return nil } +func (*FakeStoreBackend) FetchRecordByID(id suave.DataId) (suave.DataRecord, error) { + return suave.DataRecord{}, errors.New("not implemented") } -func (b *FakeStoreBackend) Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { - return b.OnStore(bid, caller, key, value) +func (b *FakeStoreBackend) Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { + return b.OnStore(record, caller, key, value) } -func (*FakeStoreBackend) Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) { +func (*FakeStoreBackend) Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) { return nil, errors.New("not implemented") } -func (*FakeStoreBackend) FetchBidById(suave.BidId) (suave.Bid, error) { - return suave.Bid{}, nil +func (*FakeStoreBackend) FetchRecordById(suave.DataId) (suave.DataRecord, error) { + return suave.DataRecord{}, nil } -func (*FakeStoreBackend) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { +func (*FakeStoreBackend) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { return nil } -func (*FakeStoreBackend) SubmitBid(types.Bid) error { +func (*FakeStoreBackend) SubmitDataRecord(types.DataRecord) error { return nil } +/// + func TestOwnMessageDropping(t *testing.T) { var wasCalled *bool = new(bool) - fakeStore := FakeStoreBackend{OnStore: func(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { + fakeStore := FakeStoreBackend{OnStore: func(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { *wasCalled = true - return bid, nil + return record, nil }} fakeDaSigner := FakeDASigner{localAddresses: []common.Address{{0x42}}} - engine := NewConfidentialStoreEngine(&fakeStore, MockTransport{}, fakeDaSigner, MockChainSigner{}) + engine := NewEngine(&fakeStore, MockTransport{}, fakeDaSigner, MockChainSigner{}) testKey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") // testKeyAddress := crypto.PubkeyToAddress(testKey.PublicKey) @@ -75,22 +77,22 @@ func TestOwnMessageDropping(t *testing.T) { }), types.NewSuaveSigner(new(big.Int)), testKey) require.NoError(t, err) - bidId, err := calculateBidId(types.Bid{ + recordId, err := calculateRecordId(types.DataRecord{ AllowedStores: []common.Address{{0x42}}, AllowedPeekers: []common.Address{{}}, }) require.NoError(t, err) - testBid := suave.Bid{ - Id: bidId, + testRecord := suave.DataRecord{ + Id: recordId, CreationTx: dummyCreationTx, AllowedStores: []common.Address{{0x42}}, AllowedPeekers: []common.Address{{}}, } - testBidBytes, err := SerializeBidForSigning(&testBid) + testRecordBytes, err := SerializeDataRecord(&testRecord) require.NoError(t, err) - testBid.Signature, err = fakeDaSigner.Sign(common.Address{0x42}, testBidBytes) + testRecord.Signature, err = fakeDaSigner.Sign(common.Address{0x42}, testRecordBytes) require.NoError(t, err) *wasCalled = false @@ -98,10 +100,10 @@ func TestOwnMessageDropping(t *testing.T) { daMessage := DAMessage{ SourceTx: dummyCreationTx, StoreUUID: engine.storeUUID, - StoreWrites: []StoreWrite{{Bid: testBid}}, + StoreWrites: []StoreWrite{{DataRecord: testRecord}}, } - daMessageBytes, err := SerializeMessageForSigning(&daMessage) + daMessageBytes, err := SerializeDAMessage(&daMessage) require.NoError(t, err) daMessage.Signature, err = fakeDaSigner.Sign(common.Address{0x42}, daMessageBytes) @@ -113,7 +115,7 @@ func TestOwnMessageDropping(t *testing.T) { // require.True(t, *wasCalled) daMessage.StoreUUID = uuid.New() - daMessageBytes, err = SerializeMessageForSigning(&daMessage) + daMessageBytes, err = SerializeDAMessage(&daMessage) require.NoError(t, err) daMessage.Signature, err = fakeDaSigner.Sign(common.Address{0x42}, daMessageBytes) diff --git a/suave/cstore/local_store_backend.go b/suave/cstore/local_store_backend.go index 872a92d383..9079b78f32 100644 --- a/suave/cstore/local_store_backend.go +++ b/suave/cstore/local_store_backend.go @@ -14,16 +14,16 @@ var _ ConfidentialStorageBackend = &LocalConfidentialStore{} type LocalConfidentialStore struct { lock sync.Mutex - bids map[suave.BidId]suave.Bid + records map[suave.DataId]suave.DataRecord dataMap map[string][]byte - index map[string][]suave.BidId + index map[string][]suave.DataId } func NewLocalConfidentialStore() *LocalConfidentialStore { return &LocalConfidentialStore{ - bids: make(map[suave.BidId]suave.Bid), + records: make(map[suave.DataId]suave.DataRecord), dataMap: make(map[string][]byte), - index: make(map[string][]suave.BidId), + index: make(map[string][]suave.DataId), } } @@ -31,41 +31,41 @@ func (l *LocalConfidentialStore) Stop() error { return nil } -func (l *LocalConfidentialStore) InitializeBid(bid suave.Bid) error { +func (l *LocalConfidentialStore) InitRecord(record suave.DataRecord) error { l.lock.Lock() defer l.lock.Unlock() - _, found := l.bids[bid.Id] + _, found := l.records[record.Id] if found { - return suave.ErrBidAlreadyPresent + return suave.ErrRecordAlreadyPresent } - l.bids[bid.Id] = bid + l.records[record.Id] = record - // index the bid by (protocol, block number) - indexKey := fmt.Sprintf("protocol-%s-bn-%d", bid.Version, bid.DecryptionCondition) - bidIds := l.index[indexKey] - bidIds = append(bidIds, bid.Id) - l.index[indexKey] = bidIds + // index the record by (protocol, block number) + indexKey := fmt.Sprintf("protocol-%s-bn-%d", record.Version, record.DecryptionCondition) + recordIds := l.index[indexKey] + recordIds = append(recordIds, record.Id) + l.index[indexKey] = recordIds return nil } -func (l *LocalConfidentialStore) Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { +func (l *LocalConfidentialStore) Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { l.lock.Lock() defer l.lock.Unlock() - l.dataMap[fmt.Sprintf("%x-%s", bid.Id, key)] = append(make([]byte, 0, len(value)), value...) + l.dataMap[fmt.Sprintf("%x-%s", record.Id, key)] = append(make([]byte, 0, len(value)), value...) - defer log.Trace("CSSW", "caller", caller, "key", key, "value", value, "stored", l.dataMap[fmt.Sprintf("%x-%s", bid.Id, key)]) - return bid, nil + defer log.Trace("CSSW", "caller", caller, "key", key, "value", value, "stored", l.dataMap[fmt.Sprintf("%x-%s", record.Id, key)]) + return record, nil } -func (l *LocalConfidentialStore) Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) { +func (l *LocalConfidentialStore) Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) { l.lock.Lock() defer l.lock.Unlock() - data, found := l.dataMap[fmt.Sprintf("%x-%s", bid.Id, key)] + data, found := l.dataMap[fmt.Sprintf("%x-%s", record.Id, key)] if !found { return []byte{}, fmt.Errorf("data for key %s not found", key) } @@ -74,19 +74,19 @@ func (l *LocalConfidentialStore) Retrieve(bid suave.Bid, caller common.Address, return append(make([]byte, 0, len(data)), data...), nil } -func (l *LocalConfidentialStore) FetchBidById(bidId suave.BidId) (suave.Bid, error) { +func (l *LocalConfidentialStore) FetchRecordByID(dataId suave.DataId) (suave.DataRecord, error) { l.lock.Lock() defer l.lock.Unlock() - bid, found := l.bids[bidId] + bid, found := l.records[dataId] if !found { - return suave.Bid{}, errors.New("bid not found") + return suave.DataRecord{}, errors.New("record not found") } return bid, nil } -func (l *LocalConfidentialStore) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { +func (l *LocalConfidentialStore) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { l.lock.Lock() defer l.lock.Unlock() @@ -96,9 +96,9 @@ func (l *LocalConfidentialStore) FetchBidsByProtocolAndBlock(blockNumber uint64, return nil } - res := []suave.Bid{} + res := []suave.DataRecord{} for _, id := range bidIDs { - bid, found := l.bids[id] + bid, found := l.records[id] if found { res = append(res, bid) } diff --git a/suave/cstore/pebble_store_backend.go b/suave/cstore/pebble_store_backend.go index 6cadd33691..becee0846a 100644 --- a/suave/cstore/pebble_store_backend.go +++ b/suave/cstore/pebble_store_backend.go @@ -12,11 +12,6 @@ import ( suave "github.com/ethereum/go-ethereum/suave/core" ) -var ( - formatPebbleBidKey = formatRedisBidKey - formatPebbleBidValueKey = formatRedisBidValueKey -) - type PebbleStoreBackend struct { ctx context.Context cancel context.CancelFunc @@ -24,11 +19,11 @@ type PebbleStoreBackend struct { db *pebble.DB } -var bidByBlockAndProtocolIndexDbKey = func(blockNumber uint64, namespace string) []byte { - return []byte(fmt.Sprintf("bids-block-%d-ns-%s", blockNumber, namespace)) +var recordByBlockAndProtocolIndexDbKey = func(blockNumber uint64, namespace string) []byte { + return []byte(fmt.Sprintf("records-block-%d-ns-%s", blockNumber, namespace)) } -type bidByBlockAndProtocolIndexType = []types.BidId +type recordByBlockAndProtocolIndexType = []types.DataId func NewPebbleStoreBackend(dbPath string) (*PebbleStoreBackend, error) { // TODO: should we check sanity in the constructor? @@ -68,18 +63,19 @@ func (b *PebbleStoreBackend) Stop() error { return nil } -func (b *PebbleStoreBackend) InitializeBid(bid suave.Bid) error { - key := []byte(formatPebbleBidKey(bid.Id)) +// InitRecord prepares a data record for storage. +func (b *PebbleStoreBackend) InitRecord(record suave.DataRecord) error { + key := []byte(formatRecordKey(record.Id)) _, closer, err := b.db.Get(key) if !errors.Is(err, pebble.ErrNotFound) { if err == nil { closer.Close() } - return suave.ErrBidAlreadyPresent + return suave.ErrRecordAlreadyPresent } - data, err := json.Marshal(bid) + data, err := json.Marshal(record) if err != nil { return err } @@ -90,9 +86,9 @@ func (b *PebbleStoreBackend) InitializeBid(bid suave.Bid) error { } // index update - var currentValues bidByBlockAndProtocolIndexType + var currentValues recordByBlockAndProtocolIndexType - dbBlockProtoIndexKey := bidByBlockAndProtocolIndexDbKey(bid.DecryptionCondition, bid.Version) + dbBlockProtoIndexKey := recordByBlockAndProtocolIndexDbKey(record.DecryptionCondition, record.Version) rawCurrentValues, closer, err := b.db.Get(dbBlockProtoIndexKey) if err != nil { if !errors.Is(err, pebble.ErrNotFound) { @@ -106,7 +102,7 @@ func (b *PebbleStoreBackend) InitializeBid(bid suave.Bid) error { } } - currentValues = append(currentValues, bid.Id) + currentValues = append(currentValues, record.Id) rawUpdatedValues, err := json.Marshal(currentValues) if err != nil { return err @@ -115,34 +111,36 @@ func (b *PebbleStoreBackend) InitializeBid(bid suave.Bid) error { return b.db.Set(dbBlockProtoIndexKey, rawUpdatedValues, nil) } -func (b *PebbleStoreBackend) FetchBidById(bidId suave.BidId) (suave.Bid, error) { - key := []byte(formatPebbleBidKey(bidId)) +// FetchRecordByID retrieves a data record by its identifier. +func (b *PebbleStoreBackend) FetchRecordByID(dataId suave.DataId) (suave.DataRecord, error) { + key := []byte(formatRecordKey(dataId)) - bidData, closer, err := b.db.Get(key) + recordData, closer, err := b.db.Get(key) if err != nil { - return suave.Bid{}, fmt.Errorf("bid %x not found: %w", bidId, err) + return suave.DataRecord{}, fmt.Errorf("record %x not found: %w", dataId, err) } - var bid suave.Bid - err = json.Unmarshal(bidData, &bid) + var record suave.DataRecord + err = json.Unmarshal(recordData, &record) closer.Close() if err != nil { - return suave.Bid{}, fmt.Errorf("could not unmarshal stored bid: %w", err) + return suave.DataRecord{}, fmt.Errorf("could not unmarshal stored record: %w", err) } - return bid, nil + return record, nil } -func (b *PebbleStoreBackend) Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { - storeKey := []byte(formatPebbleBidValueKey(bid.Id, key)) - return bid, b.db.Set(storeKey, value, nil) +func (b *PebbleStoreBackend) Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { + storeKey := []byte(formatRecordValueKey(record.Id, key)) + return record, b.db.Set(storeKey, value, nil) } -func (b *PebbleStoreBackend) Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) { - storeKey := []byte(formatPebbleBidValueKey(bid.Id, key)) +// Retrieve fetches data associated with a record. +func (b *PebbleStoreBackend) Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) { + storeKey := []byte(formatRecordValueKey(record.Id, key)) data, closer, err := b.db.Get(storeKey) if err != nil { - return nil, fmt.Errorf("could not fetch data for bid %x and key %s: %w", bid.Id, key, err) + return nil, fmt.Errorf("could not fetch data for record %x and key %s: %w", record.Id, key, err) } ret := make([]byte, len(data)) copy(ret, data) @@ -150,27 +148,27 @@ func (b *PebbleStoreBackend) Retrieve(bid suave.Bid, caller common.Address, key return ret, nil } -func (b *PebbleStoreBackend) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { - dbBlockProtoIndexKey := bidByBlockAndProtocolIndexDbKey(blockNumber, namespace) +func (b *PebbleStoreBackend) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { + dbBlockProtoIndexKey := recordByBlockAndProtocolIndexDbKey(blockNumber, namespace) rawCurrentValues, closer, err := b.db.Get(dbBlockProtoIndexKey) if err != nil { return nil } - var currentBidIds bidByBlockAndProtocolIndexType - err = json.Unmarshal(rawCurrentValues, ¤tBidIds) + var currentRecordIds recordByBlockAndProtocolIndexType + err = json.Unmarshal(rawCurrentValues, ¤tRecordIds) closer.Close() if err != nil { return nil } - bids := []suave.Bid{} - for _, bidId := range currentBidIds { - bid, err := b.FetchBidById(bidId) + records := []suave.DataRecord{} + for _, dataId := range currentRecordIds { + record, err := b.FetchRecordByID(dataId) if err == nil { - bids = append(bids, bid) + records = append(records, record) } } - return bids + return records } diff --git a/suave/cstore/redis_backends_test.go b/suave/cstore/redis_backends_test.go index 465326418d..7a2cfa20d5 100644 --- a/suave/cstore/redis_backends_test.go +++ b/suave/cstore/redis_backends_test.go @@ -26,8 +26,8 @@ func TestRedisTransport(t *testing.T) { daMsg := DAMessage{ StoreWrites: []StoreWrite{{ - Bid: suave.Bid{ - Id: suave.BidId{0x42}, + DataRecord: suave.DataRecord{ + Id: suave.DataId{0x42}, DecryptionCondition: uint64(13), AllowedPeekers: []common.Address{{0x41, 0x39}}, Version: string("vv"), @@ -52,7 +52,7 @@ func TestRedisTransport(t *testing.T) { case <-time.After(5 * time.Millisecond): } - daMsg.StoreWrites[0].Bid.Id[0] = 0x43 + daMsg.StoreWrites[0].DataRecord.Id[0] = 0x43 redisPubSub.Publish(daMsg) select { @@ -71,14 +71,14 @@ func TestEngineOnRedis(t *testing.T) { redisPubSub1 := NewRedisPubSubTransport(mrPubSub.Addr()) redisStoreBackend1, _ := NewRedisStoreBackend(mrStore1.Addr()) - engine1 := NewConfidentialStoreEngine(redisStoreBackend1, redisPubSub1, MockSigner{}, MockChainSigner{}) + engine1 := NewEngine(redisStoreBackend1, redisPubSub1, MockSigner{}, MockChainSigner{}) require.NoError(t, engine1.Start()) t.Cleanup(func() { engine1.Stop() }) redisPubSub2 := NewRedisPubSubTransport(mrPubSub.Addr()) redisStoreBackend2, _ := NewRedisStoreBackend(mrStore2.Addr()) - engine2 := NewConfidentialStoreEngine(redisStoreBackend2, redisPubSub2, MockSigner{}, MockChainSigner{}) + engine2 := NewEngine(redisStoreBackend2, redisPubSub2, MockSigner{}, MockChainSigner{}) require.NoError(t, engine2.Start()) t.Cleanup(func() { engine2.Stop() }) @@ -91,7 +91,7 @@ func TestEngineOnRedis(t *testing.T) { require.NoError(t, err) // Make sure a store to engine1 is propagated to endine2 through redis->miniredis transport - bid, err := engine1.InitializeBid(types.Bid{ + record, err := engine1.InitRecord(types.DataRecord{ DecryptionCondition: uint64(13), AllowedPeekers: []common.Address{{0x41, 0x39}}, AllowedStores: []common.Address{{}}, @@ -109,22 +109,22 @@ func TestEngineOnRedis(t *testing.T) { // Trigger propagation err = engine1.Finalize(dummyCreationTx, nil, []StoreWrite{{ - Bid: bid, - Caller: bid.AllowedPeekers[0], - Key: "xx", - Value: []byte{0x43, 0x14}, + DataRecord: record, + Caller: record.AllowedPeekers[0], + Key: "xx", + Value: []byte{0x43, 0x14}, }}) require.NoError(t, err) time.Sleep(10 * time.Millisecond) - submittedBid := suave.Bid{ - Id: bid.Id, - Salt: bid.Salt, - DecryptionCondition: bid.DecryptionCondition, - AllowedPeekers: bid.AllowedPeekers, - AllowedStores: bid.AllowedStores, - Version: bid.Version, + submittedBid := suave.DataRecord{ + Id: record.Id, + Salt: record.Salt, + DecryptionCondition: record.DecryptionCondition, + AllowedPeekers: record.AllowedPeekers, + AllowedStores: record.AllowedStores, + Version: record.Version, CreationTx: dummyCreationTx, } @@ -138,22 +138,22 @@ func TestEngineOnRedis(t *testing.T) { select { case msg := <-subch: - rececivedBidJson, err := json.Marshal(msg.StoreWrites[0].Bid) + rececivedBidJson, err := json.Marshal(msg.StoreWrites[0].DataRecord) require.NoError(t, err) require.Equal(t, submittedBidJson, rececivedBidJson) require.Equal(t, "xx", msg.StoreWrites[0].Key) require.Equal(t, suave.Bytes{0x43, 0x14}, msg.StoreWrites[0].Value) - require.Equal(t, bid.AllowedPeekers[0], msg.StoreWrites[0].Caller) + require.Equal(t, record.AllowedPeekers[0], msg.StoreWrites[0].Caller) case <-time.After(20 * time.Millisecond): t.Error("did not receive expected message") } - retrievedData, err := engine2.Retrieve(bid.Id, bid.AllowedPeekers[0], "xx") + retrievedData, err := engine2.Retrieve(record.Id, record.AllowedPeekers[0], "xx") require.NoError(t, err) require.Equal(t, []byte{0x43, 0x14}, retrievedData) - fetchedBid, err := redisStoreBackend2.FetchBidById(bid.Id) + fetchedBid, err := redisStoreBackend2.FetchRecordByID(record.Id) require.NoError(t, err) fetchedBidJson, err := json.Marshal(fetchedBid) diff --git a/suave/cstore/redis_store_backend.go b/suave/cstore/redis_store_backend.go index 55ac60aa81..e0727288dd 100644 --- a/suave/cstore/redis_store_backend.go +++ b/suave/cstore/redis_store_backend.go @@ -18,12 +18,12 @@ import ( var _ ConfidentialStorageBackend = &RedisStoreBackend{} var ( - formatRedisBidKey = func(bidId suave.BidId) string { - return fmt.Sprintf("bid-%x", bidId) + formatRecordKey = func(dataId suave.DataId) string { + return fmt.Sprintf("record-%x", dataId) } - formatRedisBidValueKey = func(bidId suave.BidId, key string) string { - return fmt.Sprintf("bid-data-%x-%s", bidId, key) + formatRecordValueKey = func(dataId suave.DataId, key string) string { + return fmt.Sprintf("record-data-%x-%s", dataId, key) } ffStoreTTL = 24 * time.Hour @@ -74,8 +74,8 @@ func (r *RedisStoreBackend) start() error { } r.client = client - err = r.InitializeBid(mempoolConfidentialStoreBid) - if err != nil && !errors.Is(err, suave.ErrBidAlreadyPresent) { + err = r.InitRecord(mempoolConfidentialStoreRecord) + if err != nil && !errors.Is(err, suave.ErrRecordAlreadyPresent) { return fmt.Errorf("mempool: could not initialize: %w", err) } @@ -96,15 +96,16 @@ func (r *RedisStoreBackend) Stop() error { return nil } -func (r *RedisStoreBackend) InitializeBid(bid suave.Bid) error { - key := formatRedisBidKey(bid.Id) +// InitRecord prepares a data record for storage. +func (r *RedisStoreBackend) InitRecord(record suave.DataRecord) error { + key := formatRecordKey(record.Id) err := r.client.Get(r.ctx, key).Err() if !errors.Is(err, redis.Nil) { - return suave.ErrBidAlreadyPresent + return suave.ErrRecordAlreadyPresent } - data, err := json.Marshal(bid) + data, err := json.Marshal(record) if err != nil { return err } @@ -114,7 +115,7 @@ func (r *RedisStoreBackend) InitializeBid(bid suave.Bid) error { return err } - err = r.indexBid(bid) + err = r.indexRecord(record) if err != nil { return err } @@ -122,35 +123,37 @@ func (r *RedisStoreBackend) InitializeBid(bid suave.Bid) error { return nil } -func (r *RedisStoreBackend) FetchBidById(bidId suave.BidId) (suave.Bid, error) { - key := formatRedisBidKey(bidId) +// FetchRecordByID retrieves a data record by its identifier. +func (r *RedisStoreBackend) FetchRecordByID(dataId suave.DataId) (suave.DataRecord, error) { + key := formatRecordKey(dataId) data, err := r.client.Get(r.ctx, key).Bytes() if err != nil { - return suave.Bid{}, err + return suave.DataRecord{}, err } - var bid suave.Bid - err = json.Unmarshal(data, &bid) + var record suave.DataRecord + err = json.Unmarshal(data, &record) if err != nil { - return suave.Bid{}, err + return suave.DataRecord{}, err } - return bid, nil + return record, nil } -func (r *RedisStoreBackend) Store(bid suave.Bid, caller common.Address, key string, value []byte) (suave.Bid, error) { - storeKey := formatRedisBidValueKey(bid.Id, key) +func (r *RedisStoreBackend) Store(record suave.DataRecord, caller common.Address, key string, value []byte) (suave.DataRecord, error) { + storeKey := formatRecordValueKey(record.Id, key) err := r.client.Set(r.ctx, storeKey, string(value), ffStoreTTL).Err() if err != nil { - return suave.Bid{}, fmt.Errorf("unexpected redis error: %w", err) + return suave.DataRecord{}, fmt.Errorf("unexpected redis error: %w", err) } - return bid, nil + return record, nil } -func (r *RedisStoreBackend) Retrieve(bid suave.Bid, caller common.Address, key string) ([]byte, error) { - storeKey := formatRedisBidValueKey(bid.Id, key) +// Retrieve fetches data associated with a record. +func (r *RedisStoreBackend) Retrieve(record suave.DataRecord, caller common.Address, key string) ([]byte, error) { + storeKey := formatRecordValueKey(record.Id, key) data, err := r.client.Get(r.ctx, storeKey).Bytes() if err != nil { return []byte{}, fmt.Errorf("unexpected redis error: %w, %s, %v", err, storeKey, r.client.Keys(context.TODO(), "*").String()) @@ -160,44 +163,44 @@ func (r *RedisStoreBackend) Retrieve(bid suave.Bid, caller common.Address, key s } var ( - mempoolConfStoreId = types.BidId{0x39} - mempoolConfStoreAddr = common.HexToAddress("0x39") - mempoolConfidentialStoreBid = suave.Bid{Id: mempoolConfStoreId, AllowedPeekers: []common.Address{mempoolConfStoreAddr}} + mempoolConfStoreId = types.DataId{0x39} + mempoolConfStoreAddr = common.HexToAddress("0x39") + mempoolConfidentialStoreRecord = suave.DataRecord{Id: mempoolConfStoreId, AllowedPeekers: []common.Address{mempoolConfStoreAddr}} ) -func (r *RedisStoreBackend) indexBid(bid suave.Bid) error { - defer log.Info("bid submitted", "bid", bid, "store", r.Store) +func (r *RedisStoreBackend) indexRecord(record suave.DataRecord) error { + defer log.Info("record submitted", "record", record, "store", r.Store) - var bidsByBlockAndProtocol []suave.BidId - bidsByBlockAndProtocolBytes, err := r.Retrieve(mempoolConfidentialStoreBid, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", bid.Version, bid.DecryptionCondition)) + var recordsByBlockAndProtocol []suave.DataId + recordsByBlockAndProtocolBytes, err := r.Retrieve(mempoolConfidentialStoreRecord, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", record.Version, record.DecryptionCondition)) if err == nil { - bidsByBlockAndProtocol = suave.MustDecode[[]suave.BidId](bidsByBlockAndProtocolBytes) + recordsByBlockAndProtocol = suave.MustDecode[[]suave.DataId](recordsByBlockAndProtocolBytes) } - // store bid by block number and by protocol + block number - bidsByBlockAndProtocol = append(bidsByBlockAndProtocol, bid.Id) + // store record by block number and by protocol + block number + recordsByBlockAndProtocol = append(recordsByBlockAndProtocol, record.Id) - r.Store(mempoolConfidentialStoreBid, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", bid.Version, bid.DecryptionCondition), suave.MustEncode(bidsByBlockAndProtocol)) + r.Store(mempoolConfidentialStoreRecord, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", record.Version, record.DecryptionCondition), suave.MustEncode(recordsByBlockAndProtocol)) return nil } -func (r *RedisStoreBackend) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { - bidsByProtocolBytes, err := r.Retrieve(mempoolConfidentialStoreBid, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", namespace, blockNumber)) +func (r *RedisStoreBackend) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { + recordsByProtocolBytes, err := r.Retrieve(mempoolConfidentialStoreRecord, mempoolConfStoreAddr, fmt.Sprintf("protocol-%s-bn-%d", namespace, blockNumber)) if err != nil { return nil } - res := []suave.Bid{} + res := []suave.DataRecord{} - bidIDs := suave.MustDecode[[]suave.BidId](bidsByProtocolBytes) - for _, id := range bidIDs { - bid, err := r.FetchBidById(id) + recordIDs := suave.MustDecode[[]suave.DataId](recordsByProtocolBytes) + for _, id := range recordIDs { + record, err := r.FetchRecordByID(id) if err != nil { continue } - res = append(res, bid) + res = append(res, record) } - // defer log.Info("bids fetched", "bids", string(bidsByProtocolBytes)) + // defer log.Info("records fetched", "records", string(recordsByProtocolBytes)) return res } diff --git a/suave/cstore/transactional_store.go b/suave/cstore/transactional_store.go index 11bb694576..798b28ee5b 100644 --- a/suave/cstore/transactional_store.go +++ b/suave/cstore/transactional_store.go @@ -13,102 +13,105 @@ import ( type TransactionalStore struct { sourceTx *types.Transaction - engine *ConfidentialStoreEngine + engine *CStoreEngine - pendingLock sync.Mutex - pendingBids map[suave.BidId]suave.Bid - pendingWrites []StoreWrite + pendingLock sync.Mutex + pendingRecords map[suave.DataId]suave.DataRecord + pendingWrites []StoreWrite } -func (s *TransactionalStore) FetchBidById(bidId suave.BidId) (suave.Bid, error) { +// FetchRecordByID retrieves a data record by its identifier. +func (s *TransactionalStore) FetchRecordByID(dataId suave.DataId) (suave.DataRecord, error) { s.pendingLock.Lock() - bid, ok := s.pendingBids[bidId] + record, ok := s.pendingRecords[dataId] s.pendingLock.Unlock() if ok { - return bid, nil + return record, nil } - return s.engine.FetchBidById(bidId) + return s.engine.FetchRecordByID(dataId) } -func (s *TransactionalStore) FetchBidsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.Bid { - bids := s.engine.FetchBidsByProtocolAndBlock(blockNumber, namespace) +func (s *TransactionalStore) FetchRecordsByProtocolAndBlock(blockNumber uint64, namespace string) []suave.DataRecord { + records := s.engine.FetchRecordsByProtocolAndBlock(blockNumber, namespace) s.pendingLock.Lock() defer s.pendingLock.Unlock() - for _, bid := range s.pendingBids { - if bid.Version == namespace && bid.DecryptionCondition == blockNumber { - bids = append(bids, bid) + for _, record := range s.pendingRecords { + if record.Version == namespace && record.DecryptionCondition == blockNumber { + records = append(records, record) } } - return bids + return records } -func (s *TransactionalStore) Store(bidId suave.BidId, caller common.Address, key string, value []byte) (suave.Bid, error) { - bid, err := s.FetchBidById(bidId) +func (s *TransactionalStore) Store(dataId suave.DataId, caller common.Address, key string, value []byte) (suave.DataRecord, error) { + record, err := s.FetchRecordByID(dataId) if err != nil { - return suave.Bid{}, err + return suave.DataRecord{}, err } - if !slices.Contains(bid.AllowedPeekers, caller) && !slices.Contains(bid.AllowedPeekers, suave.AllowedPeekerAny) { - return suave.Bid{}, fmt.Errorf("confidential store transaction: %x not allowed to store %s on %x", caller, key, bidId) + if !slices.Contains(record.AllowedPeekers, caller) && !slices.Contains(record.AllowedPeekers, suave.AllowedPeekerAny) { + return suave.DataRecord{}, fmt.Errorf("confidential store transaction: %x not allowed to store %s on %x", caller, key, dataId) } s.pendingLock.Lock() defer s.pendingLock.Unlock() s.pendingWrites = append(s.pendingWrites, StoreWrite{ - Bid: bid, - Caller: caller, - Key: key, - Value: common.CopyBytes(value), + DataRecord: record, + Caller: caller, + Key: key, + Value: common.CopyBytes(value), }) - return bid, nil + return record, nil } -func (s *TransactionalStore) Retrieve(bidId suave.BidId, caller common.Address, key string) ([]byte, error) { - bid, err := s.FetchBidById(bidId) +// Retrieve fetches data associated with a record. +func (s *TransactionalStore) Retrieve(dataId suave.DataId, caller common.Address, key string) ([]byte, error) { + record, err := s.FetchRecordByID(dataId) if err != nil { return nil, err } - if !slices.Contains(bid.AllowedPeekers, caller) && !slices.Contains(bid.AllowedPeekers, suave.AllowedPeekerAny) { - return nil, fmt.Errorf("confidential store transaction: %x not allowed to retrieve %s on %x", caller, key, bidId) + if !slices.Contains(record.AllowedPeekers, caller) && !slices.Contains(record.AllowedPeekers, suave.AllowedPeekerAny) { + return nil, fmt.Errorf("confidential store transaction: %x not allowed to retrieve %s on %x", caller, key, dataId) } s.pendingLock.Lock() for _, sw := range s.pendingWrites { - if sw.Bid.Id == bid.Id && sw.Key == key { + if sw.DataRecord.Id == record.Id && sw.Key == key { s.pendingLock.Unlock() return common.CopyBytes(sw.Value), nil } } s.pendingLock.Unlock() - return s.engine.Retrieve(bidId, caller, key) + return s.engine.Retrieve(dataId, caller, key) } -func (s *TransactionalStore) InitializeBid(rawBid types.Bid) (types.Bid, error) { - bid, err := s.engine.InitializeBid(rawBid, s.sourceTx) +// InitRecord prepares a data record for storage. +func (s *TransactionalStore) InitRecord(rawRecord types.DataRecord) (types.DataRecord, error) { + record, err := s.engine.InitRecord(rawRecord, s.sourceTx) if err != nil { - return types.Bid{}, err + return types.DataRecord{}, err } s.pendingLock.Lock() - _, found := s.pendingBids[bid.Id] + _, found := s.pendingRecords[record.Id] if found { s.pendingLock.Unlock() - return types.Bid{}, errors.New("bid with this id already exists") + return types.DataRecord{}, errors.New("record with this id already exists") } - s.pendingBids[bid.Id] = bid + s.pendingRecords[record.Id] = record s.pendingLock.Unlock() - return bid.ToInnerBid(), nil + return record.ToInnerRecord(), nil } func (s *TransactionalStore) Finalize() error { - return s.engine.Finalize(s.sourceTx, s.pendingBids, s.pendingWrites) + return s.engine.Finalize(s.sourceTx, s.pendingRecords, s.pendingWrites) } diff --git a/suave/cstore/transactional_store_test.go b/suave/cstore/transactional_store_test.go index 788a06a740..1efb391b6e 100644 --- a/suave/cstore/transactional_store_test.go +++ b/suave/cstore/transactional_store_test.go @@ -12,7 +12,7 @@ import ( ) func TestTransactionalStore(t *testing.T) { - engine := NewConfidentialStoreEngine(NewLocalConfidentialStore(), MockTransport{}, MockSigner{}, MockChainSigner{}) + engine := NewEngine(NewLocalConfidentialStore(), MockTransport{}, MockSigner{}, MockChainSigner{}) testKey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") dummyCreationTx, err := types.SignTx(types.NewTx(&types.ConfidentialComputeRequest{ @@ -24,8 +24,8 @@ func TestTransactionalStore(t *testing.T) { tstore := engine.NewTransactionalStore(dummyCreationTx) - testBid, err := tstore.InitializeBid(types.Bid{ - Salt: RandomBidId(), + testBid, err := tstore.InitRecord(types.DataRecord{ + Salt: RandomRecordId(), DecryptionCondition: 46, AllowedStores: []common.Address{{0x42}}, AllowedPeekers: []common.Address{{0x43}}, @@ -36,21 +36,21 @@ func TestTransactionalStore(t *testing.T) { _, err = tstore.Store(testBid.Id, testBid.AllowedPeekers[0], "xx", []byte{0x44}) require.NoError(t, err) - tfetchedBid, err := tstore.FetchBidById(testBid.Id) + tfetchedBid, err := tstore.FetchRecordByID(testBid.Id) require.NoError(t, err) - require.Equal(t, testBid, tfetchedBid.ToInnerBid()) + require.Equal(t, testBid, tfetchedBid.ToInnerRecord()) - require.Empty(t, tstore.FetchBidsByProtocolAndBlock(45, "v0-test")) - require.Empty(t, tstore.FetchBidsByProtocolAndBlock(46, "v1-test")) + require.Empty(t, tstore.FetchRecordsByProtocolAndBlock(45, "v0-test")) + require.Empty(t, tstore.FetchRecordsByProtocolAndBlock(46, "v1-test")) - tfetchedBids := tstore.FetchBidsByProtocolAndBlock(46, "v0-test") + tfetchedBids := tstore.FetchRecordsByProtocolAndBlock(46, "v0-test") require.Equal(t, 1, len(tfetchedBids)) - require.Equal(t, testBid, tfetchedBids[0].ToInnerBid()) + require.Equal(t, testBid, tfetchedBids[0].ToInnerRecord()) _, err = tstore.Retrieve(testBid.Id, testBid.AllowedPeekers[0], "xy") require.Error(t, err) - _, err = tstore.Retrieve(suave.RandomBidId(), testBid.AllowedPeekers[0], "xx") + _, err = tstore.Retrieve(suave.RandomDataRecordId(), testBid.AllowedPeekers[0], "xx") require.Error(t, err) _, err = tstore.Retrieve(testBid.Id, testBid.AllowedStores[0], "xx") @@ -61,21 +61,21 @@ func TestTransactionalStore(t *testing.T) { require.Equal(t, []byte{0x44}, tretrieved) // Not finalized, engine should return empty - _, err = engine.FetchBidById(testBid.Id) + _, err = engine.FetchRecordByID(testBid.Id) require.Error(t, err) - require.Empty(t, engine.FetchBidsByProtocolAndBlock(46, "v0-test")) + require.Empty(t, engine.FetchRecordsByProtocolAndBlock(46, "v0-test")) _, err = engine.Retrieve(testBid.Id, testBid.AllowedPeekers[0], "xx") require.Error(t, err) require.NoError(t, tstore.Finalize()) - efetchedBid, err := engine.FetchBidById(testBid.Id) + efetchedBid, err := engine.FetchRecordByID(testBid.Id) require.NoError(t, err) - require.Equal(t, testBid, efetchedBid.ToInnerBid()) + require.Equal(t, testBid, efetchedBid.ToInnerRecord()) - efetchedBids := engine.FetchBidsByProtocolAndBlock(46, "v0-test") + efetchedBids := engine.FetchRecordsByProtocolAndBlock(46, "v0-test") require.Equal(t, 1, len(efetchedBids)) - require.Equal(t, testBid, efetchedBids[0].ToInnerBid()) + require.Equal(t, testBid, efetchedBids[0].ToInnerRecord()) eretrieved, err := engine.Retrieve(testBid.Id, testBid.AllowedPeekers[0], "xx") require.NoError(t, err) diff --git a/suave/devenv/cmd/main.go b/suave/devenv/cmd/main.go index 9d2c5f0940..2e2157af26 100644 --- a/suave/devenv/cmd/main.go +++ b/suave/devenv/cmd/main.go @@ -50,7 +50,7 @@ func main() { ) fundBalance := big.NewInt(100000000) - var bidId [16]byte + var DataID [16]byte steps := []step{ { @@ -110,7 +110,7 @@ func main() { }, }, { - name: "Send bid", + name: "Send user transaction", action: func() error { refundPercent := 10 bundle := &types.SBundle{ @@ -120,13 +120,13 @@ func main() { } bundleBytes, _ := json.Marshal(bundle) - // new bid inputs + // new mevshare transaction inputs targetBlock := uint64(1) allowedPeekers := []common.Address{mevShareContract.Address()} - confidentialDataBytes, _ := bundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, _ := bundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) - txnResult, err := mevShareContract.SendTransaction("newBid", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) + txnResult, err := mevShareContract.SendTransaction("newTransaction", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) if err != nil { return err } @@ -135,21 +135,21 @@ func main() { return err } if receipt.Status == 0 { - return fmt.Errorf("failed to send bid") + return fmt.Errorf("failed to send a transaction") } - bidEvent := &BidEvent{} - if err := bidEvent.Unpack(receipt.Logs[0]); err != nil { + DataRecordEvent := &DataRecordEvent{} + if err := DataRecordEvent.Unpack(receipt.Logs[0]); err != nil { return err } hintEvent := &HintEvent{} if err := hintEvent.Unpack(receipt.Logs[1]); err != nil { return err } - bidId = bidEvent.BidId + DataID = DataRecordEvent.DataID - fmt.Printf("- Bid sent at txn: %s\n", receipt.TxHash.Hex()) - fmt.Printf("- Bid id: %x\n", bidEvent.BidId) + fmt.Printf("- transaction sent at txn: %s\n", receipt.TxHash.Hex()) + fmt.Printf("- Data Record id: %x\n", DataRecordEvent.DataID) return nil }, @@ -163,13 +163,13 @@ func main() { } backRunBundleBytes, _ := json.Marshal(backRunBundle) - confidentialDataMatchBytes, _ := bundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(backRunBundleBytes) + confidentialDataMatchBytes, _ := bundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(backRunBundleBytes) // backrun inputs targetBlock := uint64(1) allowedPeekers := []common.Address{mevShareContract.Address()} - txnResult, err := mevShareContract.SendTransaction("newMatch", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}, bidId}, confidentialDataMatchBytes) + txnResult, err := mevShareContract.SendTransaction("newMatch", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}, DataID}, confidentialDataMatchBytes) if err != nil { return err } @@ -178,16 +178,16 @@ func main() { return err } if receipt.Status == 0 { - return fmt.Errorf("failed to send bid") + return fmt.Errorf("failed to send back run") } - bidEvent := &BidEvent{} - if err := bidEvent.Unpack(receipt.Logs[0]); err != nil { + DataRecordEvent := &DataRecordEvent{} + if err := DataRecordEvent.Unpack(receipt.Logs[0]); err != nil { return err } fmt.Printf("- Backrun sent at txn: %s\n", receipt.TxHash.Hex()) - fmt.Printf("- Backrun bid id: %x\n", bidEvent.BidId) + fmt.Printf("- Backrun data record id: %x\n", DataRecordEvent.DataID) return nil }, @@ -261,8 +261,8 @@ func generatePrivKey() *privKey { } type HintEvent struct { - BidId [16]byte - Hint []byte + DataID [16]byte + Hint []byte } func (h *HintEvent) Unpack(log *types.Log) error { @@ -270,23 +270,23 @@ func (h *HintEvent) Unpack(log *types.Log) error { if err != nil { return err } - h.BidId = unpacked[0].([16]byte) + h.DataID = unpacked[0].([16]byte) h.Hint = unpacked[1].([]byte) return nil } -type BidEvent struct { - BidId [16]byte +type DataRecordEvent struct { + DataID [16]byte DecryptionCondition uint64 AllowedPeekers []common.Address } -func (b *BidEvent) Unpack(log *types.Log) error { - unpacked, err := bundleBidContract.Abi.Events["BidEvent"].Inputs.Unpack(log.Data) +func (b *DataRecordEvent) Unpack(log *types.Log) error { + unpacked, err := bundleBidContract.Abi.Events["DataRecordEvent"].Inputs.Unpack(log.Data) if err != nil { return err } - b.BidId = unpacked[0].([16]byte) + b.DataID = unpacked[0].([16]byte) b.DecryptionCondition = unpacked[1].(uint64) b.AllowedPeekers = unpacked[2].([]common.Address) return nil diff --git a/suave/e2e/contracts.go b/suave/e2e/contracts.go index ac03d0904e..bac5eca145 100644 --- a/suave/e2e/contracts.go +++ b/suave/e2e/contracts.go @@ -12,11 +12,11 @@ import ( ) var ( - MevShareBidContract = newArtifact("bids.sol/MevShareBidContract.json") - BundleBidContract = newArtifact("bids.sol/BundleBidContract.json") + MevShareBidContract = newArtifact("bids.sol/MevShareContract.json") + BundleBidContract = newArtifact("bids.sol/BundleContract.json") EthBundleSenderContract = newArtifact("bids.sol/EthBundleSenderContract.json") MevShareBundleSenderContract = newArtifact("bids.sol/MevShareBundleSenderContract.json") - buildEthBlockContract = newArtifact("bids.sol/EthBlockBidContract.json") + buildEthBlockContract = newArtifact("bids.sol/EthBlockContract.json") ethBlockBidSenderContract = newArtifact("bids.sol/EthBlockBidSenderContract.json") exampleCallSourceContract = newArtifact("example.sol/ExampleEthCallSource.json") exampleCallTargetContract = newArtifact("example.sol/ExampleEthCallTarget.json") diff --git a/suave/e2e/redis_transport_test.go b/suave/e2e/redis_transport_test.go index 1d6fbd4aaa..fe114d680f 100644 --- a/suave/e2e/redis_transport_test.go +++ b/suave/e2e/redis_transport_test.go @@ -50,12 +50,12 @@ func TestRedisBackends(t *testing.T) { { // Send a bundle bid allowedPeekers := []common.Address{newBlockBidAddress, newBundleBidAddress, buildEthBlockAddress} - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) bundleBidContractI := sdk.GetContract(newBundleBidAddress, BundleBidContract.Abi, clt1) - _, err = bundleBidContractI.SendTransaction("newBid", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{fr1.KettleAddress(), fr2.KettleAddress()}}, confidentialDataBytes) + _, err = bundleBidContractI.SendTransaction("newBundle", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{fr1.KettleAddress(), fr2.KettleAddress()}}, confidentialDataBytes) requireNoRpcError(t, err) } diff --git a/suave/e2e/workflow_test.go b/suave/e2e/workflow_test.go index f78a800fb5..e293c103fc 100644 --- a/suave/e2e/workflow_test.go +++ b/suave/e2e/workflow_test.go @@ -140,8 +140,8 @@ func TestMempool(t *testing.T) { }, }) - bid1, err := fr.ConfidentialEngine().InitializeBid(types.Bid{ - Salt: suave.RandomBidId(), + bid1, err := fr.ConfidentialEngine().InitRecord(types.DataRecord{ + Salt: suave.RandomDataRecordId(), DecryptionCondition: targetBlock, AllowedPeekers: []common.Address{common.HexToAddress("0x424344")}, Version: "default:v0:ethBundles", @@ -149,18 +149,18 @@ func TestMempool(t *testing.T) { require.NoError(t, err) - bid2, err := fr.ConfidentialEngine().InitializeBid(types.Bid{ - Salt: suave.RandomBidId(), + bid2, err := fr.ConfidentialEngine().InitRecord(types.DataRecord{ + Salt: suave.RandomDataRecordId(), DecryptionCondition: targetBlock, AllowedPeekers: []common.Address{common.HexToAddress("0x424344")}, Version: "default:v0:ethBundles", }, creationTx) require.NoError(t, err) - require.NoError(t, fr.ConfidentialStoreBackend().InitializeBid(bid1)) - require.NoError(t, fr.ConfidentialStoreBackend().InitializeBid(bid2)) + require.NoError(t, fr.ConfidentialStoreBackend().InitRecord(bid1)) + require.NoError(t, fr.ConfidentialStoreBackend().InitRecord(bid2)) - inoutAbi := mustParseMethodAbi(`[ { "inputs": [ { "internalType": "uint64", "name": "cond", "type": "uint64" }, { "internalType": "string", "name": "namespace", "type": "string" } ], "name": "fetchBids", "outputs": [ { "components": [ { "internalType": "Suave.BidId", "name": "id", "type": "bytes16" }, { "internalType": "Suave.BidId", "name": "salt", "type": "bytes16" }, { "internalType": "uint64", "name": "decryptionCondition", "type": "uint64" }, { "internalType": "address[]", "name": "allowedPeekers", "type": "address[]" }, { "internalType": "address[]", "name": "allowedStores", "type": "address[]" }, { "internalType": "string", "name": "version", "type": "string" } ], "internalType": "struct Suave.Bid[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" } ]`, "fetchBids") + inoutAbi := mustParseMethodAbi(`[ { "inputs": [ { "internalType": "uint64", "name": "cond", "type": "uint64" }, { "internalType": "string", "name": "namespace", "type": "string" } ], "name": "fetchBids", "outputs": [ { "components": [ { "internalType": "Suave.DataId", "name": "id", "type": "bytes16" }, { "internalType": "Suave.DataId", "name": "salt", "type": "bytes16" }, { "internalType": "uint64", "name": "decryptionCondition", "type": "uint64" }, { "internalType": "address[]", "name": "allowedPeekers", "type": "address[]" }, { "internalType": "address[]", "name": "allowedStores", "type": "address[]" }, { "internalType": "string", "name": "version", "type": "string" } ], "internalType": "struct Suave.Bid[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" } ]`, "fetchBids") calldata, err := inoutAbi.Inputs.Pack(targetBlock, "default:v0:ethBundles") require.NoError(t, err) @@ -177,7 +177,7 @@ func TestMempool(t *testing.T) { unpacked, err := inoutAbi.Outputs.Unpack(simResult) require.NoError(t, err) - var bids []suave.Bid + var bids []suave.DataRecord require.NoError(t, mapstructure.Decode(unpacked[0], &bids)) require.Equal(t, bid1.Id, bids[0].Id) @@ -296,11 +296,11 @@ func TestBundleBid(t *testing.T) { bundleBytes, err := json.Marshal(bundle) require.NoError(t, err) - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) bundleBidContractI := sdk.GetContract(newBundleBidAddress, BundleBidContract.Abi, clt) - _, err = bundleBidContractI.SendTransaction("newBid", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) + _, err = bundleBidContractI.SendTransaction("newBundle", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) requireNoRpcError(t, err) block := fr.suethSrv.ProgressChain() @@ -312,9 +312,9 @@ func TestBundleBid(t *testing.T) { require.Equal(t, uint64(1), receipts[0].Status) require.Equal(t, 1, len(block.Transactions())) - unpacked, err := BundleBidContract.Abi.Methods["emitBid"].Inputs.Unpack(block.Transactions()[0].Data()[4:]) + unpacked, err := BundleBidContract.Abi.Methods["emitDataRecord"].Inputs.Unpack(block.Transactions()[0].Data()[4:]) require.NoError(t, err) - bid := unpacked[0].(struct { + record := unpacked[0].(struct { Id [16]uint8 "json:\"id\"" Salt [16]uint8 "json:\"salt\"" DecryptionCondition uint64 "json:\"decryptionCondition\"" @@ -322,20 +322,20 @@ func TestBundleBid(t *testing.T) { AllowedStores []common.Address "json:\"allowedStores\"" Version string "json:\"version\"" }) - require.Equal(t, targetBlock, bid.DecryptionCondition) - require.Equal(t, allowedPeekers, bid.AllowedPeekers) + require.Equal(t, targetBlock, record.DecryptionCondition) + require.Equal(t, allowedPeekers, record.AllowedPeekers) require.NotNil(t, receipts[0].Logs[0]) require.Equal(t, newBundleBidAddress, receipts[0].Logs[0].Address) - unpacked, err = BundleBidContract.Abi.Events["BidEvent"].Inputs.Unpack(receipts[0].Logs[0].Data) + unpacked, err = BundleBidContract.Abi.Events["DataRecordEvent"].Inputs.Unpack(receipts[0].Logs[0].Data) require.NoError(t, err) - require.Equal(t, bid.Id, unpacked[0].([16]byte)) - require.Equal(t, bid.DecryptionCondition, unpacked[1].(uint64)) - require.Equal(t, bid.AllowedPeekers, unpacked[2].([]common.Address)) + require.Equal(t, record.Id, unpacked[0].([16]byte)) + require.Equal(t, record.DecryptionCondition, unpacked[1].(uint64)) + require.Equal(t, record.AllowedPeekers, unpacked[2].([]common.Address)) - _, err = fr.ConfidentialEngine().Retrieve(bid.Id, common.Address{0x41, 0x42, 0x43}, "default:v0:ethBundleSimResults") + _, err = fr.ConfidentialEngine().Retrieve(record.Id, common.Address{0x41, 0x42, 0x43}, "default:v0:ethBundleSimResults") require.NoError(t, err) } } @@ -396,7 +396,7 @@ func TestBundleSenderContract(t *testing.T) { bundleBytes, err := json.Marshal(bundle) require.NoError(t, err) - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) constructorArgs, err := EthBundleSenderContract.Abi.Constructor.Inputs.Pack([]string{fakeRelayServer.URL}) @@ -415,7 +415,7 @@ func TestBundleSenderContract(t *testing.T) { allowedPeekers := []common.Address{bundleSenderContract.Address()} - _, err = bundleSenderContract.SendTransaction("newBid", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) + _, err = bundleSenderContract.SendTransaction("newBundle", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) requireNoRpcError(t, err) block := fr.suethSrv.ProgressChain() @@ -461,13 +461,13 @@ func prepareMevShareBundle(t *testing.T) (*types.Transaction, types.SBundle, []b bundleBytes, err := json.Marshal(bundle) require.NoError(t, err) - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) return ethTx, *bundle, confidentialDataBytes } -func prepareMevShareBackrun(t *testing.T, shareBidId types.BidId) (*types.Transaction, types.SBundle, []byte) { +func prepareMevShareBackrun(t *testing.T, shareBidId types.DataId) (*types.Transaction, types.SBundle, []byte) { backrunTx, err := types.SignTx(types.NewTx(&types.LegacyTx{ Nonce: 0, To: &testAddr, @@ -485,7 +485,7 @@ func prepareMevShareBackrun(t *testing.T, shareBidId types.BidId) (*types.Transa backRunBundleBytes, err := json.Marshal(backRunBundle) require.NoError(t, err) - confidentialDataMatchBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(backRunBundleBytes) + confidentialDataMatchBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(backRunBundleBytes) require.NoError(t, err) return backrunTx, *backRunBundle, confidentialDataMatchBytes @@ -510,11 +510,11 @@ func TestMevShare(t *testing.T) { ethTx, _, confidentialDataBytes := prepareMevShareBundle(t) targetBlock := uint64(1) - // Send a bundle bid + // Send a bundle record allowedPeekers := []common.Address{{0x41, 0x42, 0x43}, newBlockBidAddress, buildEthBlockAddress, mevShareAddress} - bundleBidContractI := sdk.GetContract(mevShareAddress, BundleBidContract.Abi, clt) - _, err := bundleBidContractI.SendTransaction("newBid", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{fr.KettleAddress()}}, confidentialDataBytes) + bundleBidContractI := sdk.GetContract(mevShareAddress, MevShareBidContract.Abi, clt) + _, err := bundleBidContractI.SendTransaction("newTransaction", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{fr.KettleAddress()}}, confidentialDataBytes) requireNoRpcError(t, err) // 1a. confirm submission @@ -528,11 +528,11 @@ func TestMevShare(t *testing.T) { rpc.Call(&r, "eth_getTransactionReceipt", block.Transactions()[0].Hash()) require.NotEmpty(t, r) - t.Log("logs", r.Logs) + // t.Log("logs", r.Logs) require.NoError(t, err) require.NotEmpty(t, r.Logs) - // extract share BidId + // extract share DataId unpacked, err := MevShareBidContract.Abi.Events["HintEvent"].Inputs.Unpack(r.Logs[1].Data) require.NoError(t, err) shareBidId := unpacked[0].([16]byte) @@ -555,7 +555,7 @@ func TestMevShare(t *testing.T) { require.NotEmpty(t, r2) require.NotEmpty(t, r.Logs) - t.Log("logs", r2.Logs) + // t.Log("logs", r2.Logs) // ************ 3. Build Share Block ************ @@ -585,7 +585,7 @@ func TestMevShare(t *testing.T) { require.Equal(t, 2, len(receipts[0].Logs)) require.NotNil(t, receipts[0].Logs[1]) - unpacked, err := BundleBidContract.Abi.Events["BidEvent"].Inputs.Unpack(receipts[0].Logs[1].Data) + unpacked, err := BundleBidContract.Abi.Events["DataRecordEvent"].Inputs.Unpack(receipts[0].Logs[1].Data) require.NoError(t, err) bidId := unpacked[0].([16]byte) @@ -654,10 +654,10 @@ func TestMevShareBundleSenderContract(t *testing.T) { userTx, _, confidentialDataBytes := prepareMevShareBundle(t) targetBlock := uint64(1) - // Send a bundle bid + // Send a bundle record allowedPeekers := []common.Address{fillMevShareBundleAddress, bundleSenderContract.Address()} - txRes, err := bundleSenderContract.SendTransaction("newBid", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) + txRes, err := bundleSenderContract.SendTransaction("newTransaction", []interface{}{targetBlock, allowedPeekers, []common.Address{}}, confidentialDataBytes) requireNoRpcError(t, err) fr.suethSrv.ProgressChain() @@ -668,7 +668,7 @@ func TestMevShareBundleSenderContract(t *testing.T) { require.NotEmpty(t, receipt.Logs) - // extract share BidId + // extract share DataId unpacked, err := MevShareBidContract.Abi.Events["HintEvent"].Inputs.Unpack(receipt.Logs[1].Data) require.NoError(t, err) shareBidId := unpacked[0].([16]byte) @@ -752,7 +752,7 @@ func TestBlockBuildingPrecompiles(t *testing.T) { } { // Test the block building precompile through eth_call - // function buildEthBlock(BuildBlockArgs memory blockArgs, BidId bid) internal view returns (bytes memory, bytes memory) { + // function buildEthBlock(BuildBlockArgs memory blockArgs, DataId record) internal view returns (bytes memory, bytes memory) { dummyCreationTx, err := types.SignNewTx(testKey, signer, &types.ConfidentialComputeRequest{ ConfidentialComputeRecord: types.ConfidentialComputeRecord{ @@ -761,7 +761,7 @@ func TestBlockBuildingPrecompiles(t *testing.T) { }) require.NoError(t, err) - bid, err := fr.ConfidentialEngine().InitializeBid(types.Bid{ + record, err := fr.ConfidentialEngine().InitRecord(types.DataRecord{ DecryptionCondition: uint64(1), AllowedPeekers: []common.Address{suave.AllowedPeekerAny}, AllowedStores: []common.Address{fr.KettleAddress()}, @@ -769,12 +769,12 @@ func TestBlockBuildingPrecompiles(t *testing.T) { }, dummyCreationTx) require.NoError(t, err) - err = fr.ConfidentialEngine().Finalize(dummyCreationTx, map[suave.BidId]suave.Bid{bid.Id: bid}, []cstore.StoreWrite{{ + err = fr.ConfidentialEngine().Finalize(dummyCreationTx, map[suave.DataId]suave.DataRecord{record.Id: record}, []cstore.StoreWrite{{ - Bid: bid, - Caller: common.Address{0x41, 0x42, 0x43}, - Key: "default:v0:ethBundles", - Value: bundleBytes, + DataRecord: record, + Caller: common.Address{0x41, 0x42, 0x43}, + Key: "default:v0:ethBundles", + Value: bundleBytes, }}) require.NoError(t, err) @@ -785,7 +785,7 @@ func TestBlockBuildingPrecompiles(t *testing.T) { FeeRecipient: common.Address{0x42}, } - packed, err := artifacts.SuaveAbi.Methods["buildEthBlock"].Inputs.Pack(payloadArgsTuple, bid.Id, "") + packed, err := artifacts.SuaveAbi.Methods["buildEthBlock"].Inputs.Pack(payloadArgsTuple, record.Id, "") require.NoError(t, err) var simResult hexutil.Bytes @@ -802,7 +802,7 @@ func TestBlockBuildingPrecompiles(t *testing.T) { unpacked, err := artifacts.SuaveAbi.Methods["buildEthBlock"].Outputs.Unpack(simResult) require.NoError(t, err) - // TODO: test builder bid + // TODO: test builder record var envelope *engine.ExecutionPayloadEnvelope require.NoError(t, json.Unmarshal(unpacked[1].([]byte), &envelope)) require.Equal(t, 2, len(envelope.ExecutionPayload.Transactions)) @@ -840,15 +840,15 @@ func TestBlockBuildingContract(t *testing.T) { targetBlock := uint64(1) - { // Send a bundle bid + { // Send a bundle record allowedPeekers := []common.Address{newBlockBidAddress, newBundleBidAddress, buildEthBlockAddress} - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) bundleBidContractI := sdk.GetContract(newBundleBidAddress, BundleBidContract.Abi, clt) - _, err = bundleBidContractI.SendTransaction("newBid", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) + _, err = bundleBidContractI.SendTransaction("newBundle", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) require.NoError(t, err) } @@ -960,14 +960,14 @@ func TestRelayBlockSubmissionContract(t *testing.T) { targetBlock := uint64(1) - { // Send a bundle bid + { // Send a bundle record allowedPeekers := []common.Address{ethBlockBidSenderAddr, newBundleBidAddress, buildEthBlockAddress} - confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchBidConfidentialBundleData"].Outputs.Pack(bundleBytes) + confidentialDataBytes, err := BundleBidContract.Abi.Methods["fetchConfidentialBundleData"].Outputs.Pack(bundleBytes) require.NoError(t, err) bundleBidContractI := sdk.GetContract(newBundleBidAddress, BundleBidContract.Abi, clt) - _, err = bundleBidContractI.SendTransaction("newBid", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) + _, err = bundleBidContractI.SendTransaction("newBundle", []interface{}{targetBlock + 1, allowedPeekers, []common.Address{}}, confidentialDataBytes) requireNoRpcError(t, err) } @@ -1051,21 +1051,21 @@ func TestE2E_ForgeIntegration(t *testing.T) { } addrList := []common.Address{suave.AllowedPeekerAny} - bidRaw := doCall("newBid", uint64(0), addrList, addrList, "default:v0:ethBundles") + recordRaw := doCall("newDataRecord", uint64(0), addrList, addrList, "default:v0:ethBundles") - var bid types.Bid - require.NoError(t, mapstructure.Decode(bidRaw[0], &bid)) + var record types.DataRecord + require.NoError(t, mapstructure.Decode(recordRaw[0], &record)) - bidsRaw := doCall("fetchBids", uint64(0), "default:v0:ethBundles") - var bids []types.Bid - require.NoError(t, mapstructure.Decode(bidsRaw[0], &bids)) + recordsRaw := doCall("fetchDataRecords", uint64(0), "default:v0:ethBundles") + var bids []types.DataRecord + require.NoError(t, mapstructure.Decode(recordsRaw[0], &bids)) require.Len(t, bids, 1) - require.Equal(t, bids[0].Id, bid.Id) + require.Equal(t, bids[0].Id, record.Id) val := []byte{0x1, 0x2, 0x3} - doCall("confidentialStore", bid.Id, "a", val) + doCall("confidentialStore", record.Id, "a", val) - valRaw := doCall("confidentialRetrieve", bid.Id, "a") + valRaw := doCall("confidentialRetrieve", record.Id, "a") require.Equal(t, val, valRaw[0]) } @@ -1338,7 +1338,7 @@ func (f *framework) ConfidentialStoreBackend() cstore.ConfidentialStorageBackend return f.suethSrv.service.APIBackend.SuaveEngine().Backend() } -func (f *framework) ConfidentialEngine() *cstore.ConfidentialStoreEngine { +func (f *framework) ConfidentialEngine() *cstore.CStoreEngine { return f.suethSrv.service.APIBackend.SuaveEngine() } @@ -1527,8 +1527,11 @@ func requireNoRpcError(t *testing.T, rpcErr error) { if len(decodedError) < 4 { require.NoError(t, rpcErr, decodedError) } + t.Log(decodedError) unpacked, err := artifacts.SuaveAbi.Errors["PeekerReverted"].Inputs.Unpack(decodedError[4:]) + t.Log(artifacts.SuaveAbi) + t.Log(unpacked) if err != nil { require.NoError(t, err, rpcErr.Error()) } else { diff --git a/suave/gen/main.go b/suave/gen/main.go index b6276c9bbc..a366cc9588 100644 --- a/suave/gen/main.go +++ b/suave/gen/main.go @@ -693,7 +693,7 @@ func encodeTypeName(typName string, addMemory bool, addLink bool) string { typ, err := abi.NewType(typName, "", nil) if err != nil { // not a basic type (i.e. struct or []struct) - if typName != "BidId" { + if typName != "DataId" { isMemoryType = true } // add the link reference to Suave library if necessary diff --git a/suave/gen/suave_spec.yaml b/suave/gen/suave_spec.yaml index 15a411dfe7..0e8adde316 100644 --- a/suave/gen/suave_spec.yaml +++ b/suave/gen/suave_spec.yaml @@ -1,13 +1,13 @@ types: - - name: BidId + - name: DataId type: bytes16 structs: - - name: Bid + - name: DataRecord fields: - name: id - type: BidId + type: DataId - name: salt - type: BidId + type: DataId - name: decryptionCondition type: uint64 - name: allowedPeekers @@ -64,7 +64,7 @@ functions: fields: - name: output1 type: bytes - - name: newBid + - name: newDataRecord address: "0x0000000000000000000000000000000042030000" input: - name: decryptionCondition @@ -73,13 +73,13 @@ functions: type: address[] - name: allowedStores type: address[] - - name: bidType + - name: dataType type: string output: fields: - - name: bid - type: Bid - - name: fetchBids + - name: dataRecord + type: DataRecord + - name: fetchDataRecords address: "0x0000000000000000000000000000000042030001" input: - name: cond @@ -88,13 +88,13 @@ functions: type: string output: fields: - - name: bid - type: Bid[] + - name: dataRecords + type: DataRecord[] - name: confidentialStore address: "0x0000000000000000000000000000000042020000" input: - - name: bidId - type: BidId + - name: dataId + type: DataId - name: key type: string - name: data1 @@ -102,8 +102,8 @@ functions: - name: confidentialRetrieve address: "0x0000000000000000000000000000000042020001" input: - - name: bidId - type: BidId + - name: dataId + type: DataId - name: key type: string output: @@ -149,8 +149,8 @@ functions: input: - name: blockArgs type: BuildBlockArgs - - name: bidId - type: BidId + - name: dataId + type: DataId - name: namespace type: string output: @@ -202,8 +202,8 @@ functions: address: "0x0000000000000000000000000000000043200001" isConfidential: true input: - - name: bidId - type: BidId + - name: dataId + type: DataId output: packed: true fields: diff --git a/suave/sol/libraries/Suave.sol b/suave/sol/libraries/Suave.sol index 098752750a..884be1626f 100644 --- a/suave/sol/libraries/Suave.sol +++ b/suave/sol/libraries/Suave.sol @@ -4,16 +4,7 @@ pragma solidity ^0.8.8; library Suave { error PeekerReverted(address, bytes); - type BidId is bytes16; - - struct Bid { - BidId id; - BidId salt; - uint64 decryptionCondition; - address[] allowedPeekers; - address[] allowedStores; - string version; - } + type DataId is bytes16; struct BuildBlockArgs { uint64 slot; @@ -27,6 +18,15 @@ library Suave { bytes extra; } + struct DataRecord { + DataId id; + DataId salt; + uint64 decryptionCondition; + address[] allowedPeekers; + address[] allowedStores; + string version; + } + struct HttpRequest { string url; string method; @@ -59,11 +59,11 @@ library Suave { address public constant EXTRACT_HINT = 0x0000000000000000000000000000000042100037; - address public constant FETCH_BIDS = 0x0000000000000000000000000000000042030001; + address public constant FETCH_DATA_RECORDS = 0x0000000000000000000000000000000042030001; address public constant FILL_MEV_SHARE_BUNDLE = 0x0000000000000000000000000000000043200001; - address public constant NEW_BID = 0x0000000000000000000000000000000042030000; + address public constant NEW_DATA_RECORD = 0x0000000000000000000000000000000042030000; address public constant SIGN_ETH_TRANSACTION = 0x0000000000000000000000000000000040100001; @@ -87,12 +87,12 @@ library Suave { } } - function buildEthBlock(BuildBlockArgs memory blockArgs, BidId bidId, string memory namespace) + function buildEthBlock(BuildBlockArgs memory blockArgs, DataId dataId, string memory namespace) internal view returns (bytes memory, bytes memory) { - (bool success, bytes memory data) = BUILD_ETH_BLOCK.staticcall(abi.encode(blockArgs, bidId, namespace)); + (bool success, bytes memory data) = BUILD_ETH_BLOCK.staticcall(abi.encode(blockArgs, dataId, namespace)); if (!success) { revert PeekerReverted(BUILD_ETH_BLOCK, data); } @@ -109,8 +109,8 @@ library Suave { return data; } - function confidentialRetrieve(BidId bidId, string memory key) internal view returns (bytes memory) { - (bool success, bytes memory data) = CONFIDENTIAL_RETRIEVE.staticcall(abi.encode(bidId, key)); + function confidentialRetrieve(DataId dataId, string memory key) internal view returns (bytes memory) { + (bool success, bytes memory data) = CONFIDENTIAL_RETRIEVE.staticcall(abi.encode(dataId, key)); if (!success) { revert PeekerReverted(CONFIDENTIAL_RETRIEVE, data); } @@ -118,8 +118,8 @@ library Suave { return data; } - function confidentialStore(BidId bidId, string memory key, bytes memory data1) internal view { - (bool success, bytes memory data) = CONFIDENTIAL_STORE.staticcall(abi.encode(bidId, key, data1)); + function confidentialStore(DataId dataId, string memory key, bytes memory data1) internal view { + (bool success, bytes memory data) = CONFIDENTIAL_STORE.staticcall(abi.encode(dataId, key, data1)); if (!success) { revert PeekerReverted(CONFIDENTIAL_STORE, data); } @@ -153,18 +153,18 @@ library Suave { return data; } - function fetchBids(uint64 cond, string memory namespace) internal view returns (Bid[] memory) { - (bool success, bytes memory data) = FETCH_BIDS.staticcall(abi.encode(cond, namespace)); + function fetchDataRecords(uint64 cond, string memory namespace) internal view returns (DataRecord[] memory) { + (bool success, bytes memory data) = FETCH_DATA_RECORDS.staticcall(abi.encode(cond, namespace)); if (!success) { - revert PeekerReverted(FETCH_BIDS, data); + revert PeekerReverted(FETCH_DATA_RECORDS, data); } - return abi.decode(data, (Bid[])); + return abi.decode(data, (DataRecord[])); } - function fillMevShareBundle(BidId bidId) internal view returns (bytes memory) { + function fillMevShareBundle(DataId dataId) internal view returns (bytes memory) { require(isConfidential()); - (bool success, bytes memory data) = FILL_MEV_SHARE_BUNDLE.staticcall(abi.encode(bidId)); + (bool success, bytes memory data) = FILL_MEV_SHARE_BUNDLE.staticcall(abi.encode(dataId)); if (!success) { revert PeekerReverted(FILL_MEV_SHARE_BUNDLE, data); } @@ -172,19 +172,19 @@ library Suave { return data; } - function newBid( + function newDataRecord( uint64 decryptionCondition, address[] memory allowedPeekers, address[] memory allowedStores, - string memory bidType - ) internal view returns (Bid memory) { + string memory dataType + ) internal view returns (DataRecord memory) { (bool success, bytes memory data) = - NEW_BID.staticcall(abi.encode(decryptionCondition, allowedPeekers, allowedStores, bidType)); + NEW_DATA_RECORD.staticcall(abi.encode(decryptionCondition, allowedPeekers, allowedStores, dataType)); if (!success) { - revert PeekerReverted(NEW_BID, data); + revert PeekerReverted(NEW_DATA_RECORD, data); } - return abi.decode(data, (Bid)); + return abi.decode(data, (DataRecord)); } function signEthTransaction(bytes memory txn, string memory chainId, string memory signingKey) diff --git a/suave/sol/libraries/SuaveForge.sol b/suave/sol/libraries/SuaveForge.sol index 4f3bbc4cc4..5e0d148512 100644 --- a/suave/sol/libraries/SuaveForge.sol +++ b/suave/sol/libraries/SuaveForge.sol @@ -36,13 +36,13 @@ library SuaveForge { return string(abi.encodePacked("0x", converted)); } - function buildEthBlock(Suave.BuildBlockArgs memory blockArgs, Suave.BidId bidId, string memory namespace) + function buildEthBlock(Suave.BuildBlockArgs memory blockArgs, Suave.DataId dataId, string memory namespace) internal view returns (bytes memory, bytes memory) { bytes memory data = - forgeIt("0x0000000000000000000000000000000042100001", abi.encode(blockArgs, bidId, namespace)); + forgeIt("0x0000000000000000000000000000000042100001", abi.encode(blockArgs, dataId, namespace)); return abi.decode(data, (bytes, bytes)); } @@ -53,14 +53,14 @@ library SuaveForge { return data; } - function confidentialRetrieve(Suave.BidId bidId, string memory key) internal view returns (bytes memory) { - bytes memory data = forgeIt("0x0000000000000000000000000000000042020001", abi.encode(bidId, key)); + function confidentialRetrieve(Suave.DataId dataId, string memory key) internal view returns (bytes memory) { + bytes memory data = forgeIt("0x0000000000000000000000000000000042020001", abi.encode(dataId, key)); return data; } - function confidentialStore(Suave.BidId bidId, string memory key, bytes memory data1) internal view { - bytes memory data = forgeIt("0x0000000000000000000000000000000042020000", abi.encode(bidId, key, data1)); + function confidentialStore(Suave.DataId dataId, string memory key, bytes memory data1) internal view { + bytes memory data = forgeIt("0x0000000000000000000000000000000042020000", abi.encode(dataId, key, data1)); } function doHTTPRequest(Suave.HttpRequest memory request) internal view returns (bytes memory) { @@ -81,30 +81,30 @@ library SuaveForge { return data; } - function fetchBids(uint64 cond, string memory namespace) internal view returns (Suave.Bid[] memory) { + function fetchDataRecords(uint64 cond, string memory namespace) internal view returns (Suave.DataRecord[] memory) { bytes memory data = forgeIt("0x0000000000000000000000000000000042030001", abi.encode(cond, namespace)); - return abi.decode(data, (Suave.Bid[])); + return abi.decode(data, (Suave.DataRecord[])); } - function fillMevShareBundle(Suave.BidId bidId) internal view returns (bytes memory) { - bytes memory data = forgeIt("0x0000000000000000000000000000000043200001", abi.encode(bidId)); + function fillMevShareBundle(Suave.DataId dataId) internal view returns (bytes memory) { + bytes memory data = forgeIt("0x0000000000000000000000000000000043200001", abi.encode(dataId)); return data; } - function newBid( + function newDataRecord( uint64 decryptionCondition, address[] memory allowedPeekers, address[] memory allowedStores, - string memory bidType - ) internal view returns (Suave.Bid memory) { + string memory dataType + ) internal view returns (Suave.DataRecord memory) { bytes memory data = forgeIt( "0x0000000000000000000000000000000042030000", - abi.encode(decryptionCondition, allowedPeekers, allowedStores, bidType) + abi.encode(decryptionCondition, allowedPeekers, allowedStores, dataType) ); - return abi.decode(data, (Suave.Bid)); + return abi.decode(data, (Suave.DataRecord)); } function signEthTransaction(bytes memory txn, string memory chainId, string memory signingKey) diff --git a/suave/sol/scripts/forge_example.sol b/suave/sol/scripts/forge_example.sol index 9f44f696c5..e27e2a7449 100644 --- a/suave/sol/scripts/forge_example.sol +++ b/suave/sol/scripts/forge_example.sol @@ -8,13 +8,13 @@ contract Example is Script { address[] public addressList = [Suave.ANYALLOWED]; function run() public { - Suave.Bid memory bid = SuaveForge.newBid(0, addressList, addressList, "default:v0:ethBundles"); + Suave.DataRecord memory record = SuaveForge.newDataRecord(0, addressList, addressList, "default:v0:ethBundles"); - Suave.Bid[] memory allShareMatchBids = SuaveForge.fetchBids(0, "default:v0:ethBundles"); + Suave.DataRecord[] memory allShareMatchBids = SuaveForge.fetchDataRecords(0, "default:v0:ethBundles"); console.log(allShareMatchBids.length); - SuaveForge.confidentialStore(bid.id, "a", abi.encodePacked("bbbbbb")); - bytes memory result = SuaveForge.confidentialRetrieve(bid.id, "a"); + SuaveForge.confidentialStore(record.id, "a", abi.encodePacked("bbbbbb")); + bytes memory result = SuaveForge.confidentialRetrieve(record.id, "a"); console.logBytes(result); } } diff --git a/suave/sol/standard_peekers/bids.sol b/suave/sol/standard_peekers/bids.sol index 4c866a5a73..297f8dc6eb 100644 --- a/suave/sol/standard_peekers/bids.sol +++ b/suave/sol/standard_peekers/bids.sol @@ -2,57 +2,56 @@ pragma solidity ^0.8.8; import "../libraries/Suave.sol"; -contract AnyBidContract { - event BidEvent(Suave.BidId bidId, uint64 decryptionCondition, address[] allowedPeekers); +contract AnyBundleContract { + event DataRecordEvent(Suave.DataId dataId, uint64 decryptionCondition, address[] allowedPeekers); - function fetchBidConfidentialBundleData() public returns (bytes memory) { + function fetchConfidentialBundleData() public returns (bytes memory) { require(Suave.isConfidential()); bytes memory confidentialInputs = Suave.confidentialInputs(); return abi.decode(confidentialInputs, (bytes)); } - // Bids to this contract should not be trusted! - function emitBid(Suave.Bid calldata bid) public { - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); + function emitDataRecord(Suave.DataRecord calldata dataRecord) public { + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); } } -contract BundleBidContract is AnyBidContract { - function newBid(uint64 decryptionCondition, address[] memory bidAllowedPeekers, address[] memory bidAllowedStores) - external - payable - returns (bytes memory) - { +contract BundleContract is AnyBundleContract { + function newBundle( + uint64 decryptionCondition, + address[] memory dataAllowedPeekers, + address[] memory dataAllowedStores + ) external payable returns (bytes memory) { require(Suave.isConfidential()); - bytes memory bundleData = this.fetchBidConfidentialBundleData(); + bytes memory bundleData = this.fetchConfidentialBundleData(); uint64 egp = Suave.simulateBundle(bundleData); - Suave.Bid memory bid = - Suave.newBid(decryptionCondition, bidAllowedPeekers, bidAllowedStores, "default:v0:ethBundles"); + Suave.DataRecord memory dataRecord = + Suave.newDataRecord(decryptionCondition, dataAllowedPeekers, dataAllowedStores, "default:v0:ethBundles"); - Suave.confidentialStore(bid.id, "default:v0:ethBundles", bundleData); - Suave.confidentialStore(bid.id, "default:v0:ethBundleSimResults", abi.encode(egp)); + Suave.confidentialStore(dataRecord.id, "default:v0:ethBundles", bundleData); + Suave.confidentialStore(dataRecord.id, "default:v0:ethBundleSimResults", abi.encode(egp)); - return emitAndReturn(bid, bundleData); + return emitAndReturn(dataRecord, bundleData); } - function emitAndReturn(Suave.Bid memory bid, bytes memory) internal virtual returns (bytes memory) { - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); - return bytes.concat(this.emitBid.selector, abi.encode(bid)); + function emitAndReturn(Suave.DataRecord memory dataRecord, bytes memory) internal virtual returns (bytes memory) { + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); + return bytes.concat(this.emitDataRecord.selector, abi.encode(dataRecord)); } } -contract EthBundleSenderContract is BundleBidContract { +contract EthBundleSenderContract is BundleContract { string[] public builderUrls; constructor(string[] memory builderUrls_) { builderUrls = builderUrls_; } - function emitAndReturn(Suave.Bid memory bid, bytes memory bundleData) + function emitAndReturn(Suave.DataRecord memory dataRecord, bytes memory bundleData) internal virtual override @@ -62,25 +61,25 @@ contract EthBundleSenderContract is BundleBidContract { Suave.submitBundleJsonRPC(builderUrls[i], "eth_sendBundle", bundleData); } - return BundleBidContract.emitAndReturn(bid, bundleData); + return BundleContract.emitAndReturn(dataRecord, bundleData); } } -contract MevShareBidContract is AnyBidContract { - event HintEvent(Suave.BidId bidId, bytes hint); +contract MevShareContract is AnyBundleContract { + event HintEvent(Suave.DataId dataId, bytes hint); - event MatchEvent(Suave.BidId matchBidId, bytes matchHint); + event MatchEvent(Suave.DataId matchDataId, bytes matchHint); - function newBid(uint64 decryptionCondition, address[] memory bidAllowedPeekers, address[] memory bidAllowedStores) - external - payable - returns (bytes memory) - { + function newTransaction( + uint64 decryptionCondition, + address[] memory dataAllowedPeekers, + address[] memory dataAllowedStores + ) external payable returns (bytes memory) { // 0. check confidential execution require(Suave.isConfidential()); // 1. fetch bundle data - bytes memory bundleData = this.fetchBidConfidentialBundleData(); + bytes memory bundleData = this.fetchConfidentialBundleData(); // 2. sim bundle uint64 egp = Suave.simulateBundle(bundleData); @@ -89,34 +88,35 @@ contract MevShareBidContract is AnyBidContract { bytes memory hint = Suave.extractHint(bundleData); // // 4. store bundle and sim results - Suave.Bid memory bid = - Suave.newBid(decryptionCondition, bidAllowedPeekers, bidAllowedStores, "mevshare:v0:unmatchedBundles"); - Suave.confidentialStore(bid.id, "mevshare:v0:ethBundles", bundleData); - Suave.confidentialStore(bid.id, "mevshare:v0:ethBundleSimResults", abi.encode(egp)); - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); - emit HintEvent(bid.id, hint); + Suave.DataRecord memory dataRecord = Suave.newDataRecord( + decryptionCondition, dataAllowedPeekers, dataAllowedStores, "mevshare:v0:unmatchedBundles" + ); + Suave.confidentialStore(dataRecord.id, "mevshare:v0:ethBundles", bundleData); + Suave.confidentialStore(dataRecord.id, "mevshare:v0:ethBundleSimResults", abi.encode(egp)); + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); + emit HintEvent(dataRecord.id, hint); // // 5. return "callback" to emit hint onchain - return bytes.concat(this.emitBidAndHint.selector, abi.encode(bid, hint)); + return bytes.concat(this.emitDataRecordAndHint.selector, abi.encode(dataRecord, hint)); } - function emitBidAndHint(Suave.Bid calldata bid, bytes memory hint) public { - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); - emit HintEvent(bid.id, hint); + function emitDataRecordAndHint(Suave.DataRecord calldata dataRecord, bytes memory hint) public { + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); + emit HintEvent(dataRecord.id, hint); } function newMatch( uint64 decryptionCondition, - address[] memory bidAllowedPeekers, - address[] memory bidAllowedStores, - Suave.BidId shareBidId + address[] memory dataAllowedPeekers, + address[] memory dataAllowedStores, + Suave.DataId sharedataId ) external payable returns (bytes memory) { // WARNING : this function will copy the original mev share bid // into a new key with potentially different permsissions require(Suave.isConfidential()); // 1. fetch confidential data - bytes memory matchBundleData = this.fetchBidConfidentialBundleData(); + bytes memory matchBundleData = this.fetchConfidentialBundleData(); // 2. sim match alone for validity uint64 egp = Suave.simulateBundle(matchBundleData); @@ -124,64 +124,65 @@ contract MevShareBidContract is AnyBidContract { // 3. extract hint bytes memory matchHint = Suave.extractHint(matchBundleData); - Suave.Bid memory bid = - Suave.newBid(decryptionCondition, bidAllowedPeekers, bidAllowedStores, "mevshare:v0:matchBids"); - Suave.confidentialStore(bid.id, "mevshare:v0:ethBundles", matchBundleData); - Suave.confidentialStore(bid.id, "mevshare:v0:ethBundleSimResults", abi.encode(0)); + Suave.DataRecord memory dataRecord = Suave.newDataRecord( + decryptionCondition, dataAllowedPeekers, dataAllowedStores, "mevshare:v0:matchDataRecords" + ); + Suave.confidentialStore(dataRecord.id, "mevshare:v0:ethBundles", matchBundleData); + Suave.confidentialStore(dataRecord.id, "mevshare:v0:ethBundleSimResults", abi.encode(0)); - //4. merge bids - Suave.BidId[] memory bids = new Suave.BidId[](2); - bids[0] = shareBidId; - bids[1] = bid.id; - Suave.confidentialStore(bid.id, "mevshare:v0:mergedBids", abi.encode(bids)); + //4. merge data records + Suave.DataId[] memory dataRecords = new Suave.DataId[](2); + dataRecords[0] = sharedataId; + dataRecords[1] = dataRecord.id; + Suave.confidentialStore(dataRecord.id, "mevshare:v0:mergedDataRecords", abi.encode(dataRecords)); - return emitMatchBidAndHint(bid, matchHint); + return emitMatchDataRecordAndHint(dataRecord, matchHint); } - function emitMatchBidAndHint(Suave.Bid memory bid, bytes memory matchHint) + function emitMatchDataRecordAndHint(Suave.DataRecord memory dataRecord, bytes memory matchHint) internal virtual returns (bytes memory) { - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); - emit MatchEvent(bid.id, matchHint); + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); + emit MatchEvent(dataRecord.id, matchHint); - return bytes.concat(this.emitBid.selector, abi.encode(bid)); + return bytes.concat(this.emitDataRecord.selector, abi.encode(dataRecord)); } } -contract MevShareBundleSenderContract is MevShareBidContract { +contract MevShareBundleSenderContract is MevShareContract { string[] public builderUrls; constructor(string[] memory builderUrls_) { builderUrls = builderUrls_; } - function emitMatchBidAndHint(Suave.Bid memory bid, bytes memory matchHint) + function emitMatchDataRecordAndHint(Suave.DataRecord memory dataRecord, bytes memory matchHint) internal virtual override returns (bytes memory) { - bytes memory bundleData = Suave.fillMevShareBundle(bid.id); + bytes memory bundleData = Suave.fillMevShareBundle(dataRecord.id); for (uint256 i = 0; i < builderUrls.length; i++) { Suave.submitBundleJsonRPC(builderUrls[i], "mev_sendBundle", bundleData); } - return MevShareBidContract.emitMatchBidAndHint(bid, matchHint); + return MevShareContract.emitMatchDataRecordAndHint(dataRecord, matchHint); } } /* Not tested or implemented on the precompile side */ -struct EgpBidPair { +struct EgpRecordPair { uint64 egp; // in wei, beware overflow - Suave.BidId bidId; + Suave.DataId dataId; } -contract EthBlockBidContract is AnyBidContract { - event BuilderBoostBidEvent(Suave.BidId bidId, bytes builderBid); +contract EthBlockContract is AnyBundleContract { + event BuilderBoostBidEvent(Suave.DataId dataId, bytes builderBid); - function idsEqual(Suave.BidId _l, Suave.BidId _r) public pure returns (bool) { + function idsEqual(Suave.DataId _l, Suave.DataId _r) public pure returns (bool) { bytes memory l = abi.encodePacked(_l); bytes memory r = abi.encodePacked(_r); for (uint256 i = 0; i < l.length; i++) { @@ -196,35 +197,38 @@ contract EthBlockBidContract is AnyBidContract { function buildMevShare(Suave.BuildBlockArgs memory blockArgs, uint64 blockHeight) public returns (bytes memory) { require(Suave.isConfidential()); - Suave.Bid[] memory allShareMatchBids = Suave.fetchBids(blockHeight, "mevshare:v0:matchBids"); - Suave.Bid[] memory allShareUserBids = Suave.fetchBids(blockHeight, "mevshare:v0:unmatchedBundles"); + Suave.DataRecord[] memory allShareMatchDataRecords = + Suave.fetchDataRecords(blockHeight, "mevshare:v0:matchDataRecords"); + Suave.DataRecord[] memory allShareUserDataRecords = + Suave.fetchDataRecords(blockHeight, "mevshare:v0:unmatchedBundles"); - if (allShareUserBids.length == 0) { - revert Suave.PeekerReverted(address(this), "no bids"); + if (allShareUserDataRecords.length == 0) { + revert Suave.PeekerReverted(address(this), "no data records"); } - Suave.Bid[] memory allBids = new Suave.Bid[](allShareUserBids.length); - for (uint256 i = 0; i < allShareUserBids.length; i++) { + Suave.DataRecord[] memory allRecords = new Suave.DataRecord[](allShareUserDataRecords.length); + for (uint256 i = 0; i < allShareUserDataRecords.length; i++) { // TODO: sort matches by egp first! - Suave.Bid memory bidToInsert = allShareUserBids[i]; // will be updated with the best match if any - for (uint256 j = 0; j < allShareMatchBids.length; j++) { + Suave.DataRecord memory dataRecordToInsert = allShareUserDataRecords[i]; // will be updated with the best match if any + for (uint256 j = 0; j < allShareMatchDataRecords.length; j++) { // TODO: should be done once at the start and sorted - Suave.BidId[] memory mergedBidIds = abi.decode( - Suave.confidentialRetrieve(allShareMatchBids[j].id, "mevshare:v0:mergedBids"), (Suave.BidId[]) + Suave.DataId[] memory mergeddataIds = abi.decode( + Suave.confidentialRetrieve(allShareMatchDataRecords[j].id, "mevshare:v0:mergedDataRecords"), + (Suave.DataId[]) ); - if (idsEqual(mergedBidIds[0], allShareUserBids[i].id)) { - bidToInsert = allShareMatchBids[j]; + if (idsEqual(mergeddataIds[0], allShareUserDataRecords[i].id)) { + dataRecordToInsert = allShareMatchDataRecords[j]; break; } } - allBids[i] = bidToInsert; + allRecords[i] = dataRecordToInsert; } - EgpBidPair[] memory bidsByEGP = new EgpBidPair[](allBids.length); - for (uint256 i = 0; i < allBids.length; i++) { - bytes memory simResults = Suave.confidentialRetrieve(allBids[i].id, "mevshare:v0:ethBundleSimResults"); + EgpRecordPair[] memory bidsByEGP = new EgpRecordPair[](allRecords.length); + for (uint256 i = 0; i < allRecords.length; i++) { + bytes memory simResults = Suave.confidentialRetrieve(allRecords[i].id, "mevshare:v0:ethBundleSimResults"); uint64 egp = abi.decode(simResults, (uint64)); - bidsByEGP[i] = EgpBidPair(egp, allBids[i].id); + bidsByEGP[i] = EgpRecordPair(egp, allRecords[i].id); } // Bubble sort, cause why not @@ -232,34 +236,34 @@ contract EthBlockBidContract is AnyBidContract { for (uint256 i = 0; i < n - 1; i++) { for (uint256 j = i + 1; j < n; j++) { if (bidsByEGP[i].egp < bidsByEGP[j].egp) { - EgpBidPair memory temp = bidsByEGP[i]; + EgpRecordPair memory temp = bidsByEGP[i]; bidsByEGP[i] = bidsByEGP[j]; bidsByEGP[j] = temp; } } } - Suave.BidId[] memory allBidIds = new Suave.BidId[](allBids.length); + Suave.DataId[] memory alldataIds = new Suave.DataId[](allRecords.length); for (uint256 i = 0; i < bidsByEGP.length; i++) { - allBidIds[i] = bidsByEGP[i].bidId; + alldataIds[i] = bidsByEGP[i].dataId; } - return buildAndEmit(blockArgs, blockHeight, allBidIds, "mevshare:v0"); + return buildAndEmit(blockArgs, blockHeight, alldataIds, "mevshare:v0"); } function buildFromPool(Suave.BuildBlockArgs memory blockArgs, uint64 blockHeight) public returns (bytes memory) { require(Suave.isConfidential()); - Suave.Bid[] memory allBids = Suave.fetchBids(blockHeight, "default:v0:ethBundles"); - if (allBids.length == 0) { - revert Suave.PeekerReverted(address(this), "no bids"); + Suave.DataRecord[] memory allRecords = Suave.fetchDataRecords(blockHeight, "default:v0:ethBundles"); + if (allRecords.length == 0) { + revert Suave.PeekerReverted(address(this), "no data records"); } - EgpBidPair[] memory bidsByEGP = new EgpBidPair[](allBids.length); - for (uint256 i = 0; i < allBids.length; i++) { - bytes memory simResults = Suave.confidentialRetrieve(allBids[i].id, "default:v0:ethBundleSimResults"); + EgpRecordPair[] memory bidsByEGP = new EgpRecordPair[](allRecords.length); + for (uint256 i = 0; i < allRecords.length; i++) { + bytes memory simResults = Suave.confidentialRetrieve(allRecords[i].id, "default:v0:ethBundleSimResults"); uint64 egp = abi.decode(simResults, (uint64)); - bidsByEGP[i] = EgpBidPair(egp, allBids[i].id); + bidsByEGP[i] = EgpRecordPair(egp, allRecords[i].id); } // Bubble sort, cause why not @@ -267,48 +271,50 @@ contract EthBlockBidContract is AnyBidContract { for (uint256 i = 0; i < n - 1; i++) { for (uint256 j = i + 1; j < n; j++) { if (bidsByEGP[i].egp < bidsByEGP[j].egp) { - EgpBidPair memory temp = bidsByEGP[i]; + EgpRecordPair memory temp = bidsByEGP[i]; bidsByEGP[i] = bidsByEGP[j]; bidsByEGP[j] = temp; } } } - Suave.BidId[] memory allBidIds = new Suave.BidId[](allBids.length); + Suave.DataId[] memory alldataIds = new Suave.DataId[](allRecords.length); for (uint256 i = 0; i < bidsByEGP.length; i++) { - allBidIds[i] = bidsByEGP[i].bidId; + alldataIds[i] = bidsByEGP[i].dataId; } - return buildAndEmit(blockArgs, blockHeight, allBidIds, ""); + return buildAndEmit(blockArgs, blockHeight, alldataIds, ""); } function buildAndEmit( Suave.BuildBlockArgs memory blockArgs, uint64 blockHeight, - Suave.BidId[] memory bids, + Suave.DataId[] memory records, string memory namespace ) public virtual returns (bytes memory) { require(Suave.isConfidential()); - (Suave.Bid memory blockBid, bytes memory builderBid) = this.doBuild(blockArgs, blockHeight, bids, namespace); + (Suave.DataRecord memory blockBid, bytes memory builderBid) = + this.doBuild(blockArgs, blockHeight, records, namespace); emit BuilderBoostBidEvent(blockBid.id, builderBid); - emit BidEvent(blockBid.id, blockBid.decryptionCondition, blockBid.allowedPeekers); + emit DataRecordEvent(blockBid.id, blockBid.decryptionCondition, blockBid.allowedPeekers); return bytes.concat(this.emitBuilderBidAndBid.selector, abi.encode(blockBid, builderBid)); } function doBuild( Suave.BuildBlockArgs memory blockArgs, uint64 blockHeight, - Suave.BidId[] memory bids, + Suave.DataId[] memory records, string memory namespace - ) public view returns (Suave.Bid memory, bytes memory) { + ) public view returns (Suave.DataRecord memory, bytes memory) { address[] memory allowedPeekers = new address[](2); allowedPeekers[0] = address(this); allowedPeekers[1] = Suave.BUILD_ETH_BLOCK; - Suave.Bid memory blockBid = Suave.newBid(blockHeight, allowedPeekers, allowedPeekers, "default:v0:mergedBids"); - Suave.confidentialStore(blockBid.id, "default:v0:mergedBids", abi.encode(bids)); + Suave.DataRecord memory blockBid = + Suave.newDataRecord(blockHeight, allowedPeekers, allowedPeekers, "default:v0:mergedDataRecords"); + Suave.confidentialStore(blockBid.id, "default:v0:mergedDataRecords", abi.encode(records)); (bytes memory builderBid, bytes memory payload) = Suave.buildEthBlock(blockArgs, blockBid.id, namespace); Suave.confidentialStore(blockBid.id, "default:v0:builderPayload", payload); // only through this.unlock @@ -316,26 +322,26 @@ contract EthBlockBidContract is AnyBidContract { return (blockBid, builderBid); } - function emitBuilderBidAndBid(Suave.Bid memory bid, bytes memory builderBid) + function emitBuilderBidAndBid(Suave.DataRecord memory dataRecord, bytes memory builderBid) public - returns (Suave.Bid memory, bytes memory) + returns (Suave.DataRecord memory, bytes memory) { - emit BuilderBoostBidEvent(bid.id, builderBid); - emit BidEvent(bid.id, bid.decryptionCondition, bid.allowedPeekers); - return (bid, builderBid); + emit BuilderBoostBidEvent(dataRecord.id, builderBid); + emit DataRecordEvent(dataRecord.id, dataRecord.decryptionCondition, dataRecord.allowedPeekers); + return (dataRecord, builderBid); } - function unlock(Suave.BidId bidId, bytes memory signedBlindedHeader) public view returns (bytes memory) { + function unlock(Suave.DataId dataId, bytes memory signedBlindedHeader) public view returns (bytes memory) { require(Suave.isConfidential()); // TODO: verify the header is correct // TODO: incorporate protocol name - bytes memory payload = Suave.confidentialRetrieve(bidId, "default:v0:builderPayload"); + bytes memory payload = Suave.confidentialRetrieve(dataId, "default:v0:builderPayload"); return payload; } } -contract EthBlockBidSenderContract is EthBlockBidContract { +contract EthBlockBidSenderContract is EthBlockContract { string boostRelayUrl; constructor(string memory boostRelayUrl_) { @@ -345,15 +351,16 @@ contract EthBlockBidSenderContract is EthBlockBidContract { function buildAndEmit( Suave.BuildBlockArgs memory blockArgs, uint64 blockHeight, - Suave.BidId[] memory bids, + Suave.DataId[] memory dataRecords, string memory namespace ) public virtual override returns (bytes memory) { require(Suave.isConfidential()); - (Suave.Bid memory blockBid, bytes memory builderBid) = this.doBuild(blockArgs, blockHeight, bids, namespace); + (Suave.DataRecord memory blockDataRecord, bytes memory builderBid) = + this.doBuild(blockArgs, blockHeight, dataRecords, namespace); Suave.submitEthBlockBidToRelay(boostRelayUrl, builderBid); - emit BidEvent(blockBid.id, blockBid.decryptionCondition, blockBid.allowedPeekers); - return bytes.concat(this.emitBid.selector, abi.encode(blockBid)); + emit DataRecordEvent(blockDataRecord.id, blockDataRecord.decryptionCondition, blockDataRecord.allowedPeekers); + return bytes.concat(this.emitDataRecord.selector, abi.encode(blockDataRecord)); } }