Skip to content

Commit 7d7d3f1

Browse files
committed
Change p2p sync logic
1 parent d235270 commit 7d7d3f1

File tree

10 files changed

+88
-73
lines changed

10 files changed

+88
-73
lines changed

blockchain/blockchain.go

+10-14
Original file line numberDiff line numberDiff line change
@@ -371,11 +371,17 @@ func (b *Blockchain) Store(block *core.Block, blockCommitments *core.BlockCommit
371371
return err
372372
}
373373

374-
// todo only for <0.13.2 blocks
375-
if err := StoreP2PHash(txn, block, stateUpdate.StateDiff); err != nil {
374+
blockVer, err := core.ParseBlockVersion(block.ProtocolVersion)
375+
if err != nil {
376376
return err
377377
}
378378

379+
if blockVer.LessThan(core.Ver0_13_2) {
380+
if err := StoreP2PHash(txn, block, stateUpdate.StateDiff); err != nil {
381+
return err
382+
}
383+
}
384+
379385
if err := StoreBlockCommitments(txn, block.Number, blockCommitments); err != nil {
380386
return err
381387
}
@@ -399,23 +405,13 @@ func (b *Blockchain) VerifyBlock(block *core.Block) error {
399405
}
400406

401407
func StoreP2PHash(txn db.Transaction, block *core.Block, stateDiff *core.StateDiff) error {
402-
originalParentHash := block.ParentHash
403-
if block.Number > 0 {
404-
prevP2PHash, err := blockP2PHashByNumber(txn, block.Number-1)
405-
if err != nil {
406-
return err
407-
}
408-
block.ParentHash = prevP2PHash
409-
}
410-
411-
numBytes := core.MarshalBlockNumber(block.Number)
412408
hash, _, err := core.Post0132Hash(block, stateDiff)
413409
if err != nil {
414410
return err
415411
}
416-
block.ParentHash = originalParentHash
417412

418413
hashBytes := hash.Bytes()
414+
numBytes := core.MarshalBlockNumber(block.Number)
419415
return txn.Set(db.P2PHash.Key(numBytes), hashBytes[:])
420416
}
421417

@@ -684,7 +680,7 @@ func (b *Blockchain) SanityCheckNewHeight(block *core.Block, stateUpdate *core.S
684680
return nil, err
685681
}
686682

687-
return core.VerifyBlockHash(block, b.network, stateUpdate.StateDiff, force0132Hash)
683+
return core.VerifyBlockHash(block, b.network, stateUpdate.StateDiff)
688684
}
689685

690686
type txAndReceiptDBKey struct {

cmd/juno/dbcmd.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ func getNetwork(head *core.Block, stateDiff *core.StateDiff) string {
194194
}
195195

196196
for _, network := range networks {
197-
if _, err := core.VerifyBlockHash(head, network, stateDiff, false); err == nil {
197+
if _, err := core.VerifyBlockHash(head, network, stateDiff); err == nil {
198198
return network.Name
199199
}
200200
}

core/block.go

+7-18
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"fmt"
77
"slices"
88

9-
"github.com/Masterminds/semver/v3"
109
"github.com/NethermindEth/juno/core/crypto"
1110
"github.com/NethermindEth/juno/core/felt"
1211
"github.com/NethermindEth/juno/utils"
@@ -74,7 +73,7 @@ type BlockCommitments struct {
7473

7574
// VerifyBlockHash verifies the block hash. Due to bugs in Starknet alpha, not all blocks have
7675
// verifiable hashes.
77-
func VerifyBlockHash(b *Block, network *utils.Network, stateDiff *StateDiff, force0132Hash bool) (*BlockCommitments, error) {
76+
func VerifyBlockHash(b *Block, network *utils.Network, stateDiff *StateDiff) (*BlockCommitments, error) {
7877
if len(b.Transactions) != len(b.Receipts) {
7978
return nil, fmt.Errorf("len of transactions: %v do not match len of receipts: %v",
8079
len(b.Transactions), len(b.Receipts))
@@ -92,9 +91,6 @@ func VerifyBlockHash(b *Block, network *utils.Network, stateDiff *StateDiff, for
9291
unverifiableRange := metaInfo.UnverifiableRange
9392

9493
skipVerification := unverifiableRange != nil && b.Number >= unverifiableRange[0] && b.Number <= unverifiableRange[1] //nolint:gocritic
95-
if force0132Hash {
96-
skipVerification = false
97-
}
9894
if !skipVerification {
9995
if err := VerifyTransactions(b.Transactions, network, b.ProtocolVersion); err != nil {
10096
return nil, err
@@ -112,7 +108,7 @@ func VerifyBlockHash(b *Block, network *utils.Network, stateDiff *StateDiff, for
112108
overrideSeq = fallbackSeq
113109
}
114110

115-
hash, commitments, err := blockHash(b, stateDiff, network, overrideSeq, force0132Hash)
111+
hash, commitments, err := blockHash(b, stateDiff, network, overrideSeq)
116112
if err != nil {
117113
return nil, err
118114
}
@@ -143,22 +139,15 @@ func BlockHash(b *Block) (*felt.Felt, error) {
143139
}
144140

145141
// blockHash computes the block hash, with option to override sequence address
146-
func blockHash(b *Block, stateDiff *StateDiff, network *utils.Network,
147-
overrideSeqAddr *felt.Felt, force0132Hash bool) (*felt.Felt, *BlockCommitments, error) {
142+
func blockHash(b *Block, stateDiff *StateDiff, network *utils.Network, overrideSeqAddr *felt.Felt) (*felt.Felt, *BlockCommitments, error) {
148143
metaInfo := network.BlockHashMetaInfo
149144

150-
usePre0132Hash := !force0132Hash
151-
if usePre0132Hash {
152-
blockVer, err := ParseBlockVersion(b.ProtocolVersion)
153-
if err != nil {
154-
return nil, nil, err
155-
}
156-
157-
v0_13_2 := semver.MustParse("0.13.2")
158-
usePre0132Hash = blockVer.LessThan(v0_13_2)
145+
blockVer, err := ParseBlockVersion(b.ProtocolVersion)
146+
if err != nil {
147+
return nil, nil, err
159148
}
160149

161-
if usePre0132Hash {
150+
if blockVer.LessThan(Ver0_13_2) {
162151
if b.Number < metaInfo.First07Block {
163152
return pre07Hash(b, network.L2ChainIDFelt())
164153
}

core/block_test.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ func TestBlockHash(t *testing.T) {
180180
block, err := gw.BlockByNumber(context.Background(), tc.number)
181181
require.NoError(t, err)
182182

183-
commitments, err := core.VerifyBlockHash(block, &tc.chain, nil, false)
183+
commitments, err := core.VerifyBlockHash(block, &tc.chain, nil)
184184
assert.NoError(t, err)
185185
assert.NotNil(t, commitments)
186186
})
@@ -198,7 +198,7 @@ func TestBlockHash(t *testing.T) {
198198
mainnetBlock1.Hash = h1
199199

200200
expectedErr := "can not verify hash in block header"
201-
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil, false)
201+
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil)
202202
assert.EqualError(t, err, expectedErr)
203203
assert.Nil(t, commitments)
204204
})
@@ -209,7 +209,7 @@ func TestBlockHash(t *testing.T) {
209209
block119802, err := goerliGW.BlockByNumber(context.Background(), 119802)
210210
require.NoError(t, err)
211211

212-
commitments, err := core.VerifyBlockHash(block119802, &utils.Goerli, nil, false)
212+
commitments, err := core.VerifyBlockHash(block119802, &utils.Goerli, nil)
213213
assert.NoError(t, err)
214214
assert.NotNil(t, commitments)
215215
})
@@ -223,7 +223,7 @@ func TestBlockHash(t *testing.T) {
223223
expectedErr := fmt.Sprintf("len of transactions: %v do not match len of receipts: %v",
224224
len(mainnetBlock1.Transactions), len(mainnetBlock1.Receipts))
225225

226-
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil, false)
226+
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil)
227227
assert.EqualError(t, err, expectedErr)
228228
assert.Nil(t, commitments)
229229
})
@@ -237,7 +237,7 @@ func TestBlockHash(t *testing.T) {
237237
"transaction hash (%v) at index: %v does not match receipt's hash (%v)",
238238
mainnetBlock1.Transactions[1].Hash().String(), 1,
239239
mainnetBlock1.Receipts[1].TransactionHash)
240-
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil, false)
240+
commitments, err := core.VerifyBlockHash(mainnetBlock1, &utils.Mainnet, nil)
241241
assert.EqualError(t, err, expectedErr)
242242
assert.Nil(t, commitments)
243243
})
@@ -261,7 +261,7 @@ func Test0132BlockHash(t *testing.T) {
261261
su, err := gw.StateUpdate(context.Background(), test.blockNum)
262262
require.NoError(t, err)
263263

264-
c, err := core.VerifyBlockHash(b, &utils.SepoliaIntegration, su.StateDiff, false)
264+
c, err := core.VerifyBlockHash(b, &utils.SepoliaIntegration, su.StateDiff)
265265
require.NoError(t, err)
266266
assert.NotNil(t, c)
267267
})

core/transaction.go

-16
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"math/big"
88
"runtime"
99
"slices"
10-
"strings"
1110
"sync"
1211

1312
"github.com/Masterminds/semver/v3"
@@ -690,21 +689,6 @@ func transactionCommitmentPoseidon(transactions []Transaction) (*felt.Felt, erro
690689
})
691690
}
692691

693-
// ParseBlockVersion computes the block version, defaulting to "0.0.0" for empty strings
694-
func ParseBlockVersion(protocolVersion string) (*semver.Version, error) {
695-
if protocolVersion == "" {
696-
return semver.NewVersion("0.0.0")
697-
}
698-
699-
sep := "."
700-
digits := strings.Split(protocolVersion, sep)
701-
// pad with 3 zeros in case version has less than 3 digits
702-
digits = append(digits, []string{"0", "0", "0"}...)
703-
704-
// get first 3 digits only
705-
return semver.NewVersion(strings.Join(digits[:3], sep))
706-
}
707-
708692
// eventCommitmentPoseidon computes the event commitment for a block.
709693
func eventCommitmentPoseidon(receipts []*TransactionReceipt) (*felt.Felt, error) {
710694
var commitment *felt.Felt

core/version.go

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package core
2+
3+
import (
4+
"github.com/Masterminds/semver/v3"
5+
"strings"
6+
)
7+
8+
var Ver0_13_2 = semver.MustParse("0.13.2")
9+
10+
// ParseBlockVersion computes the block version, defaulting to "0.0.0" for empty strings
11+
func ParseBlockVersion(protocolVersion string) (*semver.Version, error) {
12+
if protocolVersion == "" {
13+
return semver.NewVersion("0.0.0")
14+
}
15+
16+
sep := "."
17+
digits := strings.Split(protocolVersion, sep)
18+
// pad with 3 zeros in case version has less than 3 digits
19+
digits = append(digits, []string{"0", "0", "0"}...)
20+
21+
// get first 3 digits only
22+
return semver.NewVersion(strings.Join(digits[:3], sep))
23+
}

migration/migration.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,7 @@ func calculateBlockCommitments(txn db.Transaction, network *utils.Network) error
538538
}
539539

540540
workerPool.Go(func() error {
541-
commitments, err := core.VerifyBlockHash(block, network, nil, false)
541+
commitments, err := core.VerifyBlockHash(block, network, nil)
542542
if err != nil {
543543
return err
544544
}

node/node.go

+8-7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"fmt"
7+
"github.com/NethermindEth/juno/core"
78
"net/url"
89
"reflect"
910
"runtime"
@@ -131,15 +132,15 @@ func New(cfg *Config, version string) (*Node, error) { //nolint:gocyclo,funlen
131132
return nil, fmt.Errorf("get head block from database: %v", err)
132133
}
133134
if head != nil {
134-
//stateUpdate, err := chain.StateUpdateByNumber(head.Number)
135-
//if err != nil {
136-
// return nil, err
137-
//}
135+
stateUpdate, err := chain.StateUpdateByNumber(head.Number)
136+
if err != nil {
137+
return nil, err
138+
}
138139

139140
// We assume that there is at least one transaction in the block or that it is a pre-0.7 block.
140-
//if _, err = core.VerifyBlockHash(head, &cfg.Network, stateUpdate.StateDiff, false); err != nil {
141-
// return nil, errors.New("unable to verify latest block hash; are the database and --network option compatible?")
142-
//}
141+
if _, err = core.VerifyBlockHash(head, &cfg.Network, stateUpdate.StateDiff); err != nil {
142+
return nil, errors.New("unable to verify latest block hash; are the database and --network option compatible?")
143+
}
143144
}
144145

145146
if cfg.VersionedConstantsFile != "" {

p2p/starknet/handlers.go

-8
Original file line numberDiff line numberDiff line change
@@ -180,14 +180,6 @@ func (h *Handler) updateHashes(block *core.Block) error {
180180
}
181181
block.Hash = p2pHash
182182

183-
if block.Number > 0 {
184-
prevP2PHash, err := h.bcReader.BlockP2PHashByNumber(block.Number - 1)
185-
if err != nil {
186-
return err
187-
}
188-
block.ParentHash = prevP2PHash
189-
}
190-
191183
return nil
192184
}
193185

p2p/sync.go

+32-2
Original file line numberDiff line numberDiff line change
@@ -356,14 +356,44 @@ func (s *syncService) adaptAndSanityCheckBlock(ctx context.Context, header *spec
356356
}
357357
}()
358358

359+
stateDiff := p2p2core.AdaptStateDiff(stateReader, contractDiffs, classes)
360+
361+
blockVer, err := core.ParseBlockVersion(coreBlock.ProtocolVersion)
362+
if err != nil {
363+
bodyCh <- blockBody{err: fmt.Errorf("failed to parse block version: %w", err)}
364+
return
365+
}
366+
367+
if blockVer.LessThan(core.Ver0_13_2) {
368+
expectedHash, _, err := core.Post0132Hash(coreBlock, stateDiff)
369+
if err != nil {
370+
bodyCh <- blockBody{err: fmt.Errorf("failed to compute p2p hash: %w", err)}
371+
return
372+
}
373+
374+
if !coreBlock.Hash.Equal(expectedHash) {
375+
err = fmt.Errorf("received p2p hash %v doesn't match expected %v", coreBlock.Hash, expectedHash)
376+
bodyCh <- blockBody{err: err}
377+
return
378+
}
379+
380+
// todo comment
381+
coreBlock.Hash, err = core.BlockHash(coreBlock)
382+
if err != nil {
383+
bodyCh <- blockBody{err: fmt.Errorf("failed to generate block hash: %w", err)}
384+
return
385+
}
386+
}
387+
359388
stateUpdate := &core.StateUpdate{
360389
BlockHash: coreBlock.Hash,
361390
NewRoot: coreBlock.GlobalStateRoot,
362391
OldRoot: prevBlockRoot,
363-
StateDiff: p2p2core.AdaptStateDiff(stateReader, contractDiffs, classes),
392+
StateDiff: stateDiff,
364393
}
365394

366-
commitments, err := s.blockchain.SanityCheckNewHeight(coreBlock, stateUpdate, newClasses, true)
395+
fmt.Printf("For block %d hash is %v, parent hash is %v\n", coreBlock.Number, coreBlock.Hash, coreBlock.ParentHash)
396+
commitments, err := s.blockchain.SanityCheckNewHeight(coreBlock, stateUpdate, newClasses, false)
367397
if err != nil {
368398
bodyCh <- blockBody{err: fmt.Errorf("sanity check error: %v for block number: %v", err, coreBlock.Number)}
369399
return

0 commit comments

Comments
 (0)