Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
tudor-malene committed Jun 21, 2024
1 parent fd0d92d commit 7e3b0ec
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 47 deletions.
10 changes: 5 additions & 5 deletions go/enclave/storage/enclavedb/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ func MarkBatchExecuted(ctx context.Context, dbtx *sql.Tx, seqNo *big.Int) error
return err
}

func WriteReceipt(ctx context.Context, dbtx *sql.Tx, batchSeqNo uint64, txId *uint64, createdContract *uint64, receipt []byte) (uint64, error) {
insert := "insert into receipt (created_contract_address, content, tx, batch) values " + "(?,?,?,?)"
res, err := dbtx.ExecContext(ctx, insert, createdContract, receipt, txId, batchSeqNo)
func WriteReceipt(ctx context.Context, dbtx *sql.Tx, batchSeqNo uint64, txId *uint64, receipt []byte) (uint64, error) {
insert := "insert into receipt (content, tx, batch) values " + "(?,?,?)"
res, err := dbtx.ExecContext(ctx, insert, receipt, txId, batchSeqNo)
if err != nil {
return 0, err
}
Expand Down Expand Up @@ -396,15 +396,15 @@ func ReadBatchTransactions(ctx context.Context, db *sql.DB, height uint64) ([]*c
}

func ReadContractCreationCount(ctx context.Context, db *sql.DB) (*big.Int, error) {
row := db.QueryRowContext(ctx, "select id from contract order by id desc limit 1")
row := db.QueryRowContext(ctx, "select count(id) from contract")

var count int64
err := row.Scan(&count)
if err != nil {
return nil, err
}

return big.NewInt(count + 1), nil
return big.NewInt(count), nil
}

func ReadUnexecutedBatches(ctx context.Context, db *sql.DB, from *big.Int) ([]*common.BatchHeader, error) {
Expand Down
3 changes: 1 addition & 2 deletions go/enclave/storage/init/edgelessdb/001_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,11 @@ GRANT ALL ON obsdb.tx TO obscuro;
create table if not exists obsdb.receipt
(
id INTEGER AUTO_INCREMENT,
created_contract_address int,
content mediumblob,
tx int,
batch int NOT NULL,
INDEX (batch),
INDEX (tx, created_contract_address),
INDEX (tx),
primary key (id)
);
GRANT ALL ON obsdb.receipt TO obscuro;
Expand Down
3 changes: 1 addition & 2 deletions go/enclave/storage/init/sqlite/001_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,13 @@ create index IDX_TX_BATCH_HEIGHT on tx (batch_height, idx);
create table if not exists receipt
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_contract_address INTEGER REFERENCES contract,
content mediumblob,
-- commenting out the fk until synthetic transactions are also stored
tx INTEGER,
batch INTEGER NOT NULL REFERENCES batch
);
create index IDX_EX_TX_BATCH on receipt (batch);
create index IDX_EX_TX_CCA on receipt (created_contract_address, tx);
create index IDX_EX_TX_CCA on receipt (tx);

create table if not exists contract
(
Expand Down
1 change: 1 addition & 0 deletions go/enclave/storage/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ type Storage interface {

ReadEOA(ctx context.Context, addr gethcommon.Address) (*uint64, error)

SaveContract(ctx context.Context, contractAddr, sender gethcommon.Address) error
ReadContractAddress(ctx context.Context, addr gethcommon.Address) (*uint64, error)
ReadContractOwner(ctx context.Context, address gethcommon.Address) (*gethcommon.Address, error)
}
Expand Down
110 changes: 72 additions & 38 deletions go/enclave/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"math/big"
"time"

"github.com/ethereum/go-ethereum/core/tracing"

"github.com/ten-protocol/go-ten/go/common/errutil"

"github.com/ethereum/go-ethereum/core/rawdb"
Expand Down Expand Up @@ -453,9 +455,52 @@ func (s *storageImpl) CreateStateDB(ctx context.Context, batchHash common.L2Batc
if err != nil {
return nil, fmt.Errorf("could not create state DB for %s. Cause: %w", batch.Root, err)
}
var ownerAddress *gethcommon.Address
// todo - this should be set only when executing a batch
statedb.SetLogger(&tracing.Hooks{
// when a
OnNonceChange: func(addr gethcommon.Address, prev, new uint64) {
ownerAddress = &addr
},
// called when the code of a contract changes.
OnCodeChange: func(addr gethcommon.Address, prevCodeHash gethcommon.Hash, prevCode []byte, codeHash gethcommon.Hash, code []byte) {
if len(prevCode) > 0 {
return
}
// only proceed for new deployments.
//
err := s.SaveContract(context.Background(), addr, *ownerAddress)
if err != nil {
s.logger.Error("could not save contract address", log.ErrKey, err)
}
},
})
return statedb, nil
}

func (s *storageImpl) SaveContract(ctx context.Context, contractAddr, sender gethcommon.Address) error {
s.logger.Debug("Writing contract address ", "addr", contractAddr)
dbTX, err := s.db.NewDBTransaction(context.Background())
if err != nil {
return fmt.Errorf("could not create db tx. cause %w", err)
}

senderId, err := s.readOrWriteEOA(context.Background(), dbTX, sender)
if err != nil {
return fmt.Errorf("could not readOrWriteEOA. cause %w", err)
}

_, err = enclavedb.WriteContractAddress(ctx, dbTX, contractAddr, *senderId)
if err != nil {
return fmt.Errorf("could not write contract address. cause %w", err)
}
err = dbTX.Commit()
if err != nil {
return fmt.Errorf("could not commit db tx. cause %w", err)
}
return nil
}

func (s *storageImpl) EmptyStateDB() (*state.StateDB, error) {
defer s.logDuration("EmptyStateDB", measure.NewStopwatch())
statedb, err := state.New(types.EmptyRootHash, s.stateCache, nil)
Expand Down Expand Up @@ -623,17 +668,9 @@ func (s *storageImpl) handleTxSenders(ctx context.Context, batch *core.Batch, db
if err != nil {
return nil, fmt.Errorf("could not read tx sender. Cause: %w", err)
}
eoaID, err := s.readEOA(ctx, dbTx, sender)
eoaID, err := s.readOrWriteEOA(ctx, dbTx, sender)
if err != nil {
if errors.Is(err, errutil.ErrNotFound) {
wid, err := enclavedb.WriteEoa(ctx, dbTx, sender)
if err != nil {
return nil, fmt.Errorf("could not write the eoa. Cause: %w", err)
}
eoaID = &wid
} else {
return nil, fmt.Errorf("could not insert EOA. cause: %w", err)
}
return nil, fmt.Errorf("could not insert EOA. cause: %w", err)
}
senders[i] = eoaID
}
Expand Down Expand Up @@ -678,20 +715,11 @@ func (s *storageImpl) StoreExecutedBatch(ctx context.Context, batch *common.Batc

// todo - move this to a separate service
func (s *storageImpl) storeReceiptAndEventLogs(ctx context.Context, dbTX *sql.Tx, batch *common.BatchHeader, receipt *types.Receipt) error {
txId, senderId, err := enclavedb.ReadTransactionIdAndSender(ctx, dbTX, receipt.TxHash)
txId, _, err := enclavedb.ReadTransactionIdAndSender(ctx, dbTX, receipt.TxHash)
if err != nil && !errors.Is(err, errutil.ErrNotFound) {
return fmt.Errorf("could not get transaction id. Cause: %w", err)
}

// store the created contractaddress
var createdContractId *uint64
if len(receipt.ContractAddress.Bytes()) > 0 {
createdContractId, err = enclavedb.WriteContractAddress(ctx, dbTX, receipt.ContractAddress, *senderId)
if err != nil {
return fmt.Errorf("could not write contract address. Cause: %w", err)
}
}

// Convert the receipt into its storage form and serialize
// this removes information that can be recreated
// todo - in a future iteration, this can be slimmed down further because we already store the logs separately
Expand All @@ -701,7 +729,7 @@ func (s *storageImpl) storeReceiptAndEventLogs(ctx context.Context, dbTX *sql.Tx
return fmt.Errorf("failed to encode block receipts. Cause: %w", err)
}

execTxId, err := enclavedb.WriteReceipt(ctx, dbTX, batch.SequencerOrderNo.Uint64(), txId, createdContractId, receiptBytes)
execTxId, err := enclavedb.WriteReceipt(ctx, dbTX, batch.SequencerOrderNo.Uint64(), txId, receiptBytes)
if err != nil {
return fmt.Errorf("could not write receipt. Cause: %w", err)
}
Expand Down Expand Up @@ -759,7 +787,7 @@ func (s *storageImpl) handleEventType(ctx context.Context, dbTX *sql.Tx, l *type
contractAddId, err := s.readContractAddress(ctx, dbTX, l.Address)
if err != nil {
// the contract was already stored when it was created
return 0, fmt.Errorf("could not read contract address. Cause: %w", err)
return 0, fmt.Errorf("could not read contract address. %s. Cause: %w", l.Address, err)
}
return enclavedb.WriteEventType(ctx, dbTX, contractAddId, l.Topics[0], isLifecycle)
}
Expand Down Expand Up @@ -1028,25 +1056,39 @@ func (s *storageImpl) ReadEOA(ctx context.Context, addr gethcommon.Address) (*ui

func (s *storageImpl) readEOA(ctx context.Context, dbTX *sql.Tx, addr gethcommon.Address) (*uint64, error) {
defer s.logDuration("readEOA", measure.NewStopwatch())
id, err := common.GetCachedValue(ctx, s.eoaCache, s.logger, addr, func(v any) (*uint64, error) {
return common.GetCachedValue(ctx, s.eoaCache, s.logger, addr, func(v any) (*uint64, error) {
id, err := enclavedb.ReadEoa(ctx, dbTX, addr)
if err != nil {
return nil, err
}
return &id, nil
})
if err != nil {
return nil, err
}
return id, err
}

func (s *storageImpl) readOrWriteEOA(ctx context.Context, dbTX *sql.Tx, addr gethcommon.Address) (*uint64, error) {
defer s.logDuration("readOrWriteEOA", measure.NewStopwatch())
return common.GetCachedValue(ctx, s.eoaCache, s.logger, addr, func(v any) (*uint64, error) {
id, err := enclavedb.ReadEoa(ctx, dbTX, addr)
if err != nil {
if errors.Is(err, errutil.ErrNotFound) {
wid, err := enclavedb.WriteEoa(ctx, dbTX, addr)
if err != nil {
return nil, fmt.Errorf("could not write the eoa. Cause: %w", err)
}
return &wid, nil
}
return nil, fmt.Errorf("count not read eoa. cause: %w", err)
}
return &id, nil
})
}

func (s *storageImpl) ReadContractAddress(ctx context.Context, addr gethcommon.Address) (*uint64, error) {
dbtx, err := s.db.NewDBTransaction(ctx)
if err != nil {
return nil, err
}
defer dbtx.Rollback()
defer dbtx.Commit()
return s.readContractAddress(ctx, dbtx, addr)
}

Expand All @@ -1056,17 +1098,9 @@ func (s *storageImpl) ReadContractOwner(ctx context.Context, address gethcommon.

func (s *storageImpl) readContractAddress(ctx context.Context, dbTX *sql.Tx, addr gethcommon.Address) (*uint64, error) {
defer s.logDuration("readContractAddress", measure.NewStopwatch())
id, err := common.GetCachedValue(ctx, s.contractAddressCache, s.logger, addr, func(v any) (*uint64, error) {
id, err := enclavedb.ReadContractAddress(ctx, dbTX, addr)
if err != nil {
return nil, err
}
return id, nil
return common.GetCachedValue(ctx, s.contractAddressCache, s.logger, addr, func(v any) (*uint64, error) {
return enclavedb.ReadContractAddress(ctx, dbTX, addr)
})
if err != nil {
return nil, err
}
return id, err
}

func (s *storageImpl) findEventTopic(ctx context.Context, dbTX *sql.Tx, topic []byte) (uint64, *uint64, error) {
Expand Down

0 comments on commit 7e3b0ec

Please sign in to comment.