github.com/NebulousLabs/Sia@v1.3.7/modules/consensus/fork_test.go (about) 1 package consensus 2 3 import ( 4 "testing" 5 6 "github.com/NebulousLabs/Sia/modules" 7 ) 8 9 // TestBacktrackToCurrentPath probes the backtrackToCurrentPath method of the 10 // consensus set. 11 func TestBacktrackToCurrentPath(t *testing.T) { 12 if testing.Short() { 13 t.SkipNow() 14 } 15 t.Parallel() 16 cst, err := createConsensusSetTester(t.Name()) 17 if err != nil { 18 t.Fatal(err) 19 } 20 defer cst.Close() 21 pb := cst.cs.dbCurrentProcessedBlock() 22 23 // Backtrack from the current node to the blockchain. 24 nodes := cst.cs.dbBacktrackToCurrentPath(pb) 25 if len(nodes) != 1 { 26 t.Fatal("backtracking to the current node gave incorrect result") 27 } 28 if nodes[0].Block.ID() != pb.Block.ID() { 29 t.Error("backtrack returned the wrong node") 30 } 31 32 // Backtrack from a node that has diverted from the current blockchain. 33 child0, _ := cst.miner.FindBlock() 34 child1, _ := cst.miner.FindBlock() // Is the block not on hte current path. 35 err = cst.cs.AcceptBlock(child0) 36 if err != nil { 37 t.Fatal(err) 38 } 39 err = cst.cs.AcceptBlock(child1) 40 if err != modules.ErrNonExtendingBlock { 41 t.Fatal(err) 42 } 43 pb, err = cst.cs.dbGetBlockMap(child1.ID()) 44 if err != nil { 45 t.Fatal(err) 46 } 47 nodes = cst.cs.dbBacktrackToCurrentPath(pb) 48 if len(nodes) != 2 { 49 t.Error("backtracking grabbed wrong number of nodes") 50 } 51 parent, err := cst.cs.dbGetBlockMap(pb.Block.ParentID) 52 if err != nil { 53 t.Fatal(err) 54 } 55 if nodes[0].Block.ID() != parent.Block.ID() { 56 t.Error("grabbed the wrong block as the common block") 57 } 58 if nodes[1].Block.ID() != pb.Block.ID() { 59 t.Error("backtracked from the wrong node") 60 } 61 } 62 63 // TestRevertToNode probes the revertToBlock method of the consensus set. 64 func TestRevertToNode(t *testing.T) { 65 if testing.Short() { 66 t.SkipNow() 67 } 68 t.Parallel() 69 cst, err := createConsensusSetTester(t.Name()) 70 if err != nil { 71 t.Fatal(err) 72 } 73 defer cst.Close() 74 pb := cst.cs.dbCurrentProcessedBlock() 75 76 // Revert to a grandparent and verify the returned array is correct. 77 parent, err := cst.cs.dbGetBlockMap(pb.Block.ParentID) 78 if err != nil { 79 t.Fatal(err) 80 } 81 grandParent, err := cst.cs.dbGetBlockMap(parent.Block.ParentID) 82 if err != nil { 83 t.Fatal(err) 84 } 85 revertedNodes := cst.cs.dbRevertToNode(grandParent) 86 if len(revertedNodes) != 2 { 87 t.Error("wrong number of nodes reverted") 88 } 89 if revertedNodes[0].Block.ID() != pb.Block.ID() { 90 t.Error("wrong composition of reverted nodes") 91 } 92 if revertedNodes[1].Block.ID() != parent.Block.ID() { 93 t.Error("wrong composition of reverted nodes") 94 } 95 96 // Trigger a panic by trying to revert to a node outside of the current 97 // path. 98 defer func() { 99 r := recover() 100 if r != errExternalRevert { 101 t.Error(r) 102 } 103 }() 104 cst.cs.dbRevertToNode(pb) 105 }