Skip to content

Commit

Permalink
feat: validate cartesi machine hash
Browse files Browse the repository at this point in the history
  • Loading branch information
torives committed Mar 13, 2024
1 parent b5f25c4 commit be94bce
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
74 changes: 74 additions & 0 deletions cmd/cartesi-rollups-node/machinehash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

package main

import (
"fmt"
"os"
"path"

"github.com/cartesi/rollups-node/pkg/contracts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)

const HASH_SIZE = 32

// Validates if the hash from the Cartesi Machine at machineDir matches the template hash onchain.
// It returns an error if it doesn't.
func validateMachineHash(
machineDir string,
applicationAddress string,
ethereumNodeAddr string,
) error {
offchainHash, err := getHash(machineDir)
if err != nil {
return err
}
onchainHash, err := getTemplateHash(applicationAddress, ethereumNodeAddr)
if err != nil {
return err
}
if offchainHash != onchainHash {
return fmt.Errorf(
"cartesi machine hash mismatch: expected %v but got %v",
onchainHash,
offchainHash,
)
}
return nil
}

// Reads the Cartesi Machine hash from machineDir. Returns the hash as
// a hex string or an error
func getHash(machineDir string) (string, error) {
path := path.Join(machineDir, "hash")
hash, err := os.ReadFile(path)
if err != nil {
return "", err
} else if len(hash) != HASH_SIZE {
return "", fmt.Errorf("Malformed hash: expected %v bytes, read %v", HASH_SIZE, len(hash))
}
return common.Bytes2Hex(hash), nil
}

// TODO: documentation
func getTemplateHash(applicationAddress string, ethereumNodeAddr string) (string, error) {
client, err := ethclient.Dial(ethereumNodeAddr)
if err != nil {
return "", err
}
cartesiApplication, err := contracts.NewCartesiDAppCaller(
common.HexToAddress(applicationAddress),
client,
)
if err != nil {
return "", err
}
hash, err := cartesiApplication.GetTemplateHash(nil)
if err != nil {
return "", err
}
return common.Bytes2Hex(hash[:]), nil
}
10 changes: 10 additions & 0 deletions cmd/cartesi-rollups-node/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

if !config.GetCartesiFeatureDisableMachineHashCheck() {
if err := validateMachineHash(
config.GetCartesiSnapshotDir(),
config.GetCartesiContractsApplicationAddress(),
config.GetCartesiBlockchainHttpEndpoint(),
); err != nil {
config.ErrorLogger.Fatal(err)
}
}

sunodoValidatorEnabled := config.GetCartesiExperimentalSunodoValidatorEnabled()
if !sunodoValidatorEnabled {
// add Redis first
Expand Down

0 comments on commit be94bce

Please sign in to comment.