accept_test.go 35.8 KB
Newer Older
1 2 3
package consensus

import (
4 5
	"bytes"
	"errors"
6
	"testing"
7
	"time"
David Vorick's avatar
David Vorick committed
8
	"unsafe"
9

10 11 12
	"gitlab.com/NebulousLabs/Sia/modules"
	"gitlab.com/NebulousLabs/Sia/persist"
	"gitlab.com/NebulousLabs/Sia/types"
13

14
	"github.com/coreos/bbolt"
15 16
)

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
var (
	// validateBlockParamsGot stores the parameters passed to the most recent call
	// to mockBlockValidator.ValidateBlock.
	validateBlockParamsGot validateBlockParams

	mockValidBlock = types.Block{
		Timestamp: 100,
		ParentID:  mockParentID(),
	}
	mockInvalidBlock = types.Block{
		Timestamp: 500,
		ParentID:  mockParentID(),
	}
	// parentBlockSerialized is a mock serialized form of a processedBlock.
	parentBlockSerialized = []byte{3, 2, 1}

	parentBlockUnmarshaler = mockBlockMarshaler{
		[]predefinedBlockUnmarshal{
			{parentBlockSerialized, mockParent(), nil},
		},
	}

39 40 41 42 43 44 45 46 47 48 49 50
	parentBlockHighTargetUnmarshaler = mockBlockMarshaler{
		[]predefinedBlockUnmarshal{
			{parentBlockSerialized, mockParentHighTarget(), nil},
		},
	}

	parentBlockLowTargetUnmarshaler = mockBlockMarshaler{
		[]predefinedBlockUnmarshal{
			{parentBlockSerialized, mockParentLowTarget(), nil},
		},
	}

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	unmarshalFailedErr = errors.New("mock unmarshal failed")

	failingBlockUnmarshaler = mockBlockMarshaler{
		[]predefinedBlockUnmarshal{
			{parentBlockSerialized, processedBlock{}, unmarshalFailedErr},
		},
	}

	serializedParentBlockMap = []blockMapPair{
		{mockValidBlock.ParentID[:], parentBlockSerialized},
	}
)

type (
	// mockDbBucket is an implementation of dbBucket for unit testing.
	mockDbBucket struct {
		values map[string][]byte
	}

	// mockDbTx is an implementation of dbTx for unit testing. It uses an
	// in-memory key/value store to mock a database.
	mockDbTx struct {
		buckets map[string]dbBucket
	}

	// predefinedBlockUnmarshal is a predefined response from mockBlockMarshaler.
	// It defines the unmarshaled processedBlock and error code that
	// mockBlockMarshaler should return in response to an input serialized byte
	// slice.
	predefinedBlockUnmarshal struct {
		serialized  []byte
		unmarshaled processedBlock
		err         error
	}

	// mockBlockMarshaler is an implementation of the encoding.GenericMarshaler
	// interface for unit testing. It allows clients to specify mappings of
	// serialized bytes into unmarshaled blocks.
	mockBlockMarshaler struct {
		p []predefinedBlockUnmarshal
	}

	// mockBlockRuleHelper is an implementation of the blockRuleHelper interface
	// for unit testing.
	mockBlockRuleHelper struct {
		minTimestamp types.Timestamp
	}

	// mockBlockValidator is an implementation of the blockValidator interface for
	// unit testing.
	mockBlockValidator struct {
		err error
	}

	// validateBlockParams stores the set of parameters passed to ValidateBlock.
	validateBlockParams struct {
		called       bool
		b            types.Block
		minTimestamp types.Timestamp
		target       types.Target
		height       types.BlockHeight
	}

	// blockMapPair represents a key-value pair in the mock block map.
	blockMapPair struct {
		key []byte
		val []byte
	}
)
120

121
// Get returns the value associated with a given key.
122
func (bucket mockDbBucket) Get(key []byte) []byte {
123 124 125 126 127 128
	return bucket.values[string(key)]
}

// Set adds a named value to a mockDbBucket.
func (bucket mockDbBucket) Set(key []byte, value []byte) {
	bucket.values[string(key)] = value
129 130
}

131
// Bucket returns a mock dbBucket object associated with the given bucket name.
132 133 134 135
func (db mockDbTx) Bucket(name []byte) dbBucket {
	return db.buckets[string(name)]
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
// Marshal is not implemented and panics if called.
func (m mockBlockMarshaler) Marshal(interface{}) []byte {
	panic("not implemented")
}

// Unmarshal unmarshals a byte slice into an object based on a pre-defined map
// of deserialized objects.
func (m mockBlockMarshaler) Unmarshal(b []byte, v interface{}) error {
	for _, pu := range m.p {
		if bytes.Equal(b[:], pu.serialized[:]) {
			pv, ok := v.(*processedBlock)
			if !ok {
				panic("mockBlockMarshaler.Unmarshal expected v to be of type processedBlock")
			}
			*pv = pu.unmarshaled
			return pu.err
		}
	}
	panic("unmarshal failed: predefined unmarshal not found")
}

// AddPredefinedUnmarshal adds a predefinedBlockUnmarshal to mockBlockMarshaler.
func (m *mockBlockMarshaler) AddPredefinedUnmarshal(u predefinedBlockUnmarshal) {
	m.p = append(m.p, u)
}

// minimumValidChildTimestamp returns the minimum timestamp of pb that can be
// considered a valid block.
func (brh mockBlockRuleHelper) minimumValidChildTimestamp(blockMap dbBucket, pb *processedBlock) types.Timestamp {
	return brh.minTimestamp
}

// ValidateBlock stores the parameters it receives and returns the mock error
// defined by mockBlockValidator.err.
170
func (bv mockBlockValidator) ValidateBlock(b types.Block, id types.BlockID, minTimestamp types.Timestamp, target types.Target, height types.BlockHeight, log *persist.Logger) error {
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	validateBlockParamsGot = validateBlockParams{true, b, minTimestamp, target, height}
	return bv.err
}

// mockParentID returns a mock BlockID value.
func mockParentID() (parentID types.BlockID) {
	parentID[0] = 42
	return parentID
}

// mockParent returns a mock processedBlock with its ChildTarget member
// initialized to a dummy value.
func mockParent() (parent processedBlock) {
	var mockTarget types.Target
	mockTarget[0] = 56
	parent.ChildTarget = mockTarget
	return parent
}

190 191 192 193 194 195 196 197 198 199 200 201 202
// mockParent returns a mock processedBlock with its ChildTarget member
// initialized to a the maximum value.
func mockParentHighTarget() (parent processedBlock) {
	parent.ChildTarget = types.RootDepth
	return parent
}

// mockParent returns a mock processedBlock with its ChildTarget member
// initialized to the minimum value.
func mockParentLowTarget() (parent processedBlock) {
	return parent
}

203 204
// TestUnitValidateHeaderAndBlock runs a series of unit tests for validateHeaderAndBlock.
func TestUnitValidateHeaderAndBlock(t *testing.T) {
205 206 207 208 209 210 211 212 213 214 215 216
	var tests = []struct {
		block                  types.Block
		dosBlocks              map[types.BlockID]struct{}
		blockMapPairs          []blockMapPair
		earliestValidTimestamp types.Timestamp
		marshaler              mockBlockMarshaler
		useNilBlockMap         bool
		validateBlockErr       error
		errWant                error
		msg                    string
	}{
		{
217 218
			block:                  mockValidBlock,
			dosBlocks:              make(map[types.BlockID]struct{}),
219
			useNilBlockMap:         true,
220
			earliestValidTimestamp: mockValidBlock.Timestamp,
221 222
			marshaler:              parentBlockUnmarshaler,
			errWant:                errNoBlockMap,
223
			msg:                    "validateHeaderAndBlock should fail when no block map is found in the database",
224 225
		},
		{
226 227
			block: mockValidBlock,
			// Create a dosBlocks map where mockValidBlock is marked as a bad block.
228
			dosBlocks: map[types.BlockID]struct{}{
Luke Champine's avatar
Luke Champine committed
229
				mockValidBlock.ID(): {},
230
			},
231
			earliestValidTimestamp: mockValidBlock.Timestamp,
232 233
			marshaler:              parentBlockUnmarshaler,
			errWant:                errDoSBlock,
234
			msg:                    "validateHeaderAndBlock should reject known bad blocks",
235 236
		},
		{
237 238 239
			block:                  mockValidBlock,
			dosBlocks:              make(map[types.BlockID]struct{}),
			earliestValidTimestamp: mockValidBlock.Timestamp,
240 241
			marshaler:              parentBlockUnmarshaler,
			errWant:                errOrphan,
242
			msg:                    "validateHeaderAndBlock should reject a block if its parent block does not appear in the block database",
243 244
		},
		{
245 246
			block:                  mockValidBlock,
			dosBlocks:              make(map[types.BlockID]struct{}),
247
			blockMapPairs:          serializedParentBlockMap,
248
			earliestValidTimestamp: mockValidBlock.Timestamp,
249 250
			marshaler:              failingBlockUnmarshaler,
			errWant:                unmarshalFailedErr,
251
			msg:                    "validateHeaderAndBlock should fail when unmarshaling the parent block fails",
252 253
		},
		{
254 255
			block:     mockInvalidBlock,
			dosBlocks: make(map[types.BlockID]struct{}),
256
			blockMapPairs: []blockMapPair{
257
				{mockInvalidBlock.ParentID[:], parentBlockSerialized},
258
			},
259
			earliestValidTimestamp: mockInvalidBlock.Timestamp,
260 261 262
			marshaler:              parentBlockUnmarshaler,
			validateBlockErr:       errBadMinerPayouts,
			errWant:                errBadMinerPayouts,
263
			msg:                    "validateHeaderAndBlock should reject a block if ValidateBlock returns an error for the block",
264 265
		},
		{
266 267
			block:                  mockValidBlock,
			dosBlocks:              make(map[types.BlockID]struct{}),
268
			blockMapPairs:          serializedParentBlockMap,
269
			earliestValidTimestamp: mockValidBlock.Timestamp,
270 271
			marshaler:              parentBlockUnmarshaler,
			errWant:                nil,
272
			msg:                    "validateHeaderAndBlock should accept a valid block",
273 274 275
		},
	}
	for _, tt := range tests {
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
		// Initialize the blockmap in the tx.
		bucket := mockDbBucket{map[string][]byte{}}
		for _, mapPair := range tt.blockMapPairs {
			bucket.Set(mapPair.key, mapPair.val)
		}
		dbBucketMap := map[string]dbBucket{}
		if tt.useNilBlockMap {
			dbBucketMap[string(BlockMap)] = nil
		} else {
			dbBucketMap[string(BlockMap)] = bucket
		}
		tx := mockDbTx{dbBucketMap}

		mockParent := mockParent()
		cs := ConsensusSet{
			dosBlocks: tt.dosBlocks,
			marshaler: tt.marshaler,
			blockRuleHelper: mockBlockRuleHelper{
				minTimestamp: tt.earliestValidTimestamp,
			},
			blockValidator: mockBlockValidator{tt.validateBlockErr},
		}
		// Reset the stored parameters to ValidateBlock.
		validateBlockParamsGot = validateBlockParams{}
300
		_, err := cs.validateHeaderAndBlock(tx, tt.block, tt.block.ID())
301 302 303
		if err != tt.errWant {
			t.Errorf("%s: expected to fail with `%v', got: `%v'", tt.msg, tt.errWant, err)
		}
304 305 306 307 308 309 310 311 312 313 314
		if err == nil || validateBlockParamsGot.called {
			if validateBlockParamsGot.b.ID() != tt.block.ID() {
				t.Errorf("%s: incorrect parameter passed to ValidateBlock - got: %v, want: %v", tt.msg, validateBlockParamsGot.b, tt.block)
			}
			if validateBlockParamsGot.minTimestamp != tt.earliestValidTimestamp {
				t.Errorf("%s: incorrect parameter passed to ValidateBlock - got: %v, want: %v", tt.msg, validateBlockParamsGot.minTimestamp, tt.earliestValidTimestamp)
			}
			if validateBlockParamsGot.target != mockParent.ChildTarget {
				t.Errorf("%s: incorrect parameter passed to ValidateBlock - got: %v, want: %v", tt.msg, validateBlockParamsGot.target, mockParent.ChildTarget)
			}
		}
315 316 317
	}
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
// TestCheckHeaderTarget probes the checkHeaderTarget function and checks that
// the result matches the result of checkTarget.
func TestCheckHeaderTarget(t *testing.T) {
	var b types.Block
	var h types.BlockHeader

	tests := []struct {
		target   types.Target
		expected bool
		msg      string
	}{
		{types.RootDepth, true, "checkHeaderTarget failed for a low target"},
		{types.Target{}, false, "checkHeaderTarget passed for a high target"},
		{types.Target(h.ID()), true, "checkHeaderTarget failed for a same target"},
	}
	for _, tt := range tests {
		if checkHeaderTarget(h, tt.target) != tt.expected {
			t.Error(tt.msg)
		}
337
		if checkHeaderTarget(h, tt.target) != checkTarget(b, b.ID(), tt.target) {
338 339 340 341 342
			t.Errorf("checkHeaderTarget and checkTarget do not match for target %v", tt.target)
		}
	}
}

343 344 345
// TestUnitValidateHeader runs a series of unit tests for validateHeader.
func TestUnitValidateHeader(t *testing.T) {
	mockValidBlockID := mockValidBlock.ID()
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	var tests = []struct {
		header                 types.BlockHeader
		dosBlocks              map[types.BlockID]struct{}
		blockMapPairs          []blockMapPair
		earliestValidTimestamp types.Timestamp
		marshaler              mockBlockMarshaler
		useNilBlockMap         bool
		errWant                error
		msg                    string
	}{
		// Test that known dos blocks are rejected.
		{
			header: mockValidBlock.Header(),
			// Create a dosBlocks map where mockValidBlock is marked as a bad block.
			dosBlocks: map[types.BlockID]struct{}{
Luke Champine's avatar
Luke Champine committed
362
				mockValidBlock.ID(): {},
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
			},
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockUnmarshaler,
			errWant:                errDoSBlock,
			msg:                    "validateHeader should reject known bad blocks",
		},
		// Test that blocks are rejected if a block map doesn't exist.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockUnmarshaler,
			useNilBlockMap:         true,
			errWant:                errNoBlockMap,
			msg:                    "validateHeader should fail when no block map is found in the database",
		},
		// Test that known blocks are rejected.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          []blockMapPair{{mockValidBlockID[:], []byte{}}},
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockUnmarshaler,
			errWant:                modules.ErrBlockKnown,
			msg:                    "validateHeader should fail when the block has been seen before",
		},
		// Test that blocks with unknown parents (orphans) are rejected.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockUnmarshaler,
			errWant:                errOrphan,
			msg:                    "validateHeader should reject a block if its parent block does not appear in the block database",
		},
		// Test that blocks whose parents don't unmarshal are rejected.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              failingBlockUnmarshaler,
			errWant:                unmarshalFailedErr,
			msg:                    "validateHeader should fail when unmarshaling the parent block fails",
		},
		// Test that blocks with too early of a timestamp are rejected.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp + 1,
416
			marshaler:              parentBlockHighTargetUnmarshaler,
417 418 419
			errWant:                errEarlyTimestamp,
			msg:                    "validateHeader should fail when the header's timestamp is too early",
		},
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
		// Test that headers in the extreme future are rejected.
		{
			header: types.BlockHeader{
				Timestamp: types.CurrentTimestamp() + types.ExtremeFutureThreshold + 2,
				ParentID:  mockParentID(),
			},
			dosBlocks:     make(map[types.BlockID]struct{}),
			blockMapPairs: serializedParentBlockMap,
			marshaler:     parentBlockHighTargetUnmarshaler,
			errWant:       errExtremeFutureTimestamp,
			msg:           "validateHeader should fail when the header's timestamp is in the extreme future",
		},
		// Test that headers in the near future are not rejected.
		{
			header: types.BlockHeader{
				Timestamp: types.CurrentTimestamp() + types.FutureThreshold + 2,
				ParentID:  mockParentID(),
			},
			dosBlocks:     make(map[types.BlockID]struct{}),
			blockMapPairs: serializedParentBlockMap,
			marshaler:     parentBlockHighTargetUnmarshaler,
			errWant:       nil,
			msg:           "validateHeader should not reject headers whose timestamps are in the near future",
		},
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
		// Test that blocks with too large of a target are rejected.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockLowTargetUnmarshaler,
			errWant:                modules.ErrBlockUnsolved,
			msg:                    "validateHeader should reject blocks with an insufficiently low target",
		},
		// Test that valid blocks are accepted.
		{
			header:                 mockValidBlock.Header(),
			dosBlocks:              make(map[types.BlockID]struct{}),
			blockMapPairs:          serializedParentBlockMap,
			earliestValidTimestamp: mockValidBlock.Timestamp,
			marshaler:              parentBlockHighTargetUnmarshaler,
			errWant:                nil,
			msg:                    "validateHeader should accept a valid block",
		},
	}
	for _, tt := range tests {
		// Initialize the blockmap in the tx.
		bucket := mockDbBucket{map[string][]byte{}}
		for _, mapPair := range tt.blockMapPairs {
			bucket.Set(mapPair.key, mapPair.val)
		}
		dbBucketMap := map[string]dbBucket{}
		if tt.useNilBlockMap {
			dbBucketMap[string(BlockMap)] = nil
		} else {
			dbBucketMap[string(BlockMap)] = bucket
		}
		tx := mockDbTx{dbBucketMap}

		cs := ConsensusSet{
			dosBlocks: tt.dosBlocks,
			marshaler: tt.marshaler,
			blockRuleHelper: mockBlockRuleHelper{
				minTimestamp: tt.earliestValidTimestamp,
			},
		}
		err := cs.validateHeader(tx, tt.header)
		if err != tt.errWant {
			t.Errorf("%s: expected to fail with `%v', got: `%v'", tt.msg, tt.errWant, err)
		}
	}
}

493 494
// TestIntegrationDoSBlockHandling checks that saved bad blocks are correctly
// ignored.
495
func TestIntegrationDoSBlockHandling(t *testing.T) {
496 497 498
	if testing.Short() {
		t.SkipNow()
	}
499
	t.Parallel()
500
	cst, err := createConsensusSetTester(t.Name())
501
	if err != nil {
502
		t.Fatal(err)
503
	}
504
	defer cst.Close()
505

David Vorick's avatar
David Vorick committed
506 507
	// Mine a block that is valid except for containing a buried invalid
	// transaction. The transaction has more siacoin inputs than outputs.
508 509 510 511
	txnBuilder, err := cst.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
512
	err = txnBuilder.FundSiacoins(types.NewCurrency64(50))
513
	if err != nil {
514
		t.Fatal(err)
515
	}
516
	txnSet, err := txnBuilder.Sign(true) // true sets the 'wholeTransaction' flag
517
	if err != nil {
518 519
		t.Fatal(err)
	}
520

David Vorick's avatar
David Vorick committed
521 522
	// Mine and submit the invalid block to the consensus set. The first time
	// around, the complaint should be about the rule-breaking transaction.
David Vorick's avatar
David Vorick committed
523
	block, target, err := cst.miner.BlockForWork()
524 525 526
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
527
	block.Transactions = append(block.Transactions, txnSet...)
528
	dosBlock, _ := cst.miner.SolveBlock(block, target)
529
	err = cst.cs.AcceptBlock(dosBlock)
David Vorick's avatar
David Vorick committed
530 531
	if err != errSiacoinInputOutputMismatch {
		t.Fatalf("expected %v, got %v", errSiacoinInputOutputMismatch, err)
532 533
	}

David Vorick's avatar
David Vorick committed
534 535
	// Submit the same block a second time. The complaint should be that the
	// block is already known to be invalid.
536
	err = cst.cs.AcceptBlock(dosBlock)
David Vorick's avatar
David Vorick committed
537 538
	if err != errDoSBlock {
		t.Fatalf("expected %v, got %v", errDoSBlock, err)
539
	}
540 541
}

542 543 544 545 546
// TestBlockKnownHandling submits known blocks to the consensus set.
func TestBlockKnownHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
547
	t.Parallel()
548
	cst, err := createConsensusSetTester(t.Name())
549 550 551
	if err != nil {
		t.Fatal(err)
	}
552
	defer cst.Close()
553

554
	// Get a block destined to be stale.
David Vorick's avatar
David Vorick committed
555
	block, target, err := cst.miner.BlockForWork()
556
	if err != nil {
557
		t.Fatal(err)
558
	}
559 560 561
	staleBlock, _ := cst.miner.SolveBlock(block, target)

	// Add two new blocks to the consensus set to block the stale block.
562
	block1, err := cst.miner.AddBlock()
563
	if err != nil {
564
		t.Fatal(err)
565
	}
566
	block2, err := cst.miner.AddBlock()
567
	if err != nil {
568
		t.Fatal(err)
569 570 571
	}

	// Submit the stale block.
572
	err = cst.cs.AcceptBlock(staleBlock)
573
	if err != nil && err != modules.ErrNonExtendingBlock {
574
		t.Fatal(err)
575 576
	}

577
	// Submit all the blocks again, looking for a 'stale block' error.
578
	err = cst.cs.AcceptBlock(block1)
579 580
	if err == nil {
		t.Fatal("expected an error upon submitting the block")
581
	}
582
	err = cst.cs.AcceptBlock(block2)
583 584
	if err == nil {
		t.Fatal("expected an error upon submitting the block")
585
	}
586
	err = cst.cs.AcceptBlock(staleBlock)
587 588
	if err == nil {
		t.Fatal("expected an error upon submitting the block")
589 590
	}

591
	// Try submitting the genesis block.
592 593 594 595 596 597 598 599
	id, err := cst.cs.dbGetPath(0)
	if err != nil {
		t.Fatal(err)
	}
	genesisBlock, err := cst.cs.dbGetBlockMap(id)
	if err != nil {
		t.Fatal(err)
	}
600
	err = cst.cs.AcceptBlock(genesisBlock.Block)
601 602
	if err == nil {
		t.Fatal("expected an error upon submitting the block")
603 604 605 606 607 608 609 610
	}
}

// TestOrphanHandling passes an orphan block to the consensus set.
func TestOrphanHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
611
	t.Parallel()
612
	cst, err := createConsensusSetTester(t.Name())
613 614 615
	if err != nil {
		t.Fatal(err)
	}
616
	defer cst.Close()
617

618 619 620
	// Try submitting an orphan block to the consensus set. The empty block can
	// be used, because looking for a parent is one of the first checks the
	// consensus set performs.
621
	orphan := types.Block{}
622
	err = cst.cs.AcceptBlock(orphan)
David Vorick's avatar
David Vorick committed
623 624
	if err != errOrphan {
		t.Fatalf("expected %v, got %v", errOrphan, err)
625
	}
626
	err = cst.cs.AcceptBlock(orphan)
David Vorick's avatar
David Vorick committed
627 628
	if err != errOrphan {
		t.Fatalf("expected %v, got %v", errOrphan, err)
629 630 631 632 633 634 635 636
	}
}

// TestMissedTarget submits a block that does not meet the required target.
func TestMissedTarget(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
637
	t.Parallel()
638
	cst, err := createConsensusSetTester(t.Name())
639 640 641
	if err != nil {
		t.Fatal(err)
	}
642
	defer cst.Close()
643 644

	// Mine a block that doesn't meet the target.
David Vorick's avatar
David Vorick committed
645
	block, target, err := cst.miner.BlockForWork()
646 647 648
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
649 650
	for checkTarget(block, block.ID(), target) {
		*(*uint64)(unsafe.Pointer(&block.Nonce)) += types.ASICHardforkFactor
651
	}
652
	if checkTarget(block, block.ID(), target) {
653
		t.Fatal("unable to find a failing target")
654
	}
655
	err = cst.cs.AcceptBlock(block)
David Vorick's avatar
David Vorick committed
656 657
	if err != modules.ErrBlockUnsolved {
		t.Fatalf("expected %v, got %v", modules.ErrBlockUnsolved, err)
658
	}
659 660
}

661 662 663 664 665 666
// TestMinerPayoutHandling checks that blocks with incorrect payouts are
// rejected.
func TestMinerPayoutHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
667
	t.Parallel()
668
	cst, err := createConsensusSetTester(t.Name())
669 670 671
	if err != nil {
		t.Fatal(err)
	}
672
	defer cst.Close()
673 674 675 676

	// Create a block with the wrong miner payout structure - testing can be
	// light here because there is heavier testing in the 'types' package,
	// where the logic is defined.
David Vorick's avatar
David Vorick committed
677
	block, target, err := cst.miner.BlockForWork()
678 679 680
	if err != nil {
		t.Fatal(err)
	}
681 682
	block.MinerPayouts = append(block.MinerPayouts, types.SiacoinOutput{Value: types.NewCurrency64(1)})
	solvedBlock, _ := cst.miner.SolveBlock(block, target)
683
	err = cst.cs.AcceptBlock(solvedBlock)
David Vorick's avatar
David Vorick committed
684 685
	if err != errBadMinerPayouts {
		t.Fatalf("expected %v, got %v", errBadMinerPayouts, err)
686 687 688
	}
}

Jordan Horwich's avatar
Jordan Horwich committed
689 690 691 692 693 694
// TestEarlyTimestampHandling checks that blocks too far in the past are
// rejected.
func TestEarlyTimestampHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
695
	t.Parallel()
696
	cst, err := createConsensusSetTester(t.Name())
Jordan Horwich's avatar
Jordan Horwich committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
	if err != nil {
		t.Fatal(err)
	}
	defer cst.Close()
	minTimestamp := types.CurrentTimestamp()
	cst.cs.blockRuleHelper = mockBlockRuleHelper{
		minTimestamp: minTimestamp,
	}

	// Submit a block with a timestamp in the past, before minTimestamp.
	block, target, err := cst.miner.BlockForWork()
	if err != nil {
		t.Fatal(err)
	}
	block.Timestamp = minTimestamp - 1
	solvedBlock, _ := cst.miner.SolveBlock(block, target)
	err = cst.cs.AcceptBlock(solvedBlock)
	if err != errEarlyTimestamp {
		t.Fatalf("expected %v, got %v", errEarlyTimestamp, err)
	}
}

719 720
// testFutureTimestampHandling checks that blocks in the future (but not
// extreme future) are handled correctly.
721 722 723 724
func TestFutureTimestampHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
725
	t.Parallel()
726
	cst, err := createConsensusSetTester(t.Name())
727 728 729
	if err != nil {
		t.Fatal(err)
	}
730
	defer cst.Close()
731

732 733
	// Submit a block with a timestamp in the future, but not the extreme
	// future.
David Vorick's avatar
David Vorick committed
734
	block, target, err := cst.miner.BlockForWork()
735
	if err != nil {
736
		t.Fatal(err)
737
	}
738 739
	block.Timestamp = types.CurrentTimestamp() + 2 + types.FutureThreshold
	solvedBlock, _ := cst.miner.SolveBlock(block, target)
740
	err = cst.cs.AcceptBlock(solvedBlock)
David Vorick's avatar
David Vorick committed
741
	if err != errFutureTimestamp {
742
		t.Fatalf("expected %v, got %v", errFutureTimestamp, err)
743 744
	}

745 746
	// Poll the consensus set until the future block appears.
	for i := 0; i < 30; i++ {
747 748
		time.Sleep(time.Second * 3)
		_, err = cst.cs.dbGetBlockMap(solvedBlock.ID())
749 750
		if err == nil {
			break
751
		}
752
	}
753 754 755 756
	_, err = cst.cs.dbGetBlockMap(solvedBlock.ID())
	if err != nil {
		t.Errorf("Future block not added to consensus set.\nCurrent Timestamp %v\nFutureThreshold: %v\nBlock Timestamp %v\n", types.CurrentTimestamp(), types.FutureThreshold, block.Timestamp)
	}
757 758
}

759 760 761 762 763 764
// TestExtremeFutureTimestampHandling checks that blocks in the extreme future
// are rejected.
func TestExtremeFutureTimestampHandling(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
765
	t.Parallel()
766
	cst, err := createConsensusSetTester(t.Name())
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
	if err != nil {
		t.Fatal(err)
	}
	defer cst.Close()

	// Submit a block with a timestamp in the extreme future.
	block, target, err := cst.miner.BlockForWork()
	if err != nil {
		t.Fatal(err)
	}
	block.Timestamp = types.CurrentTimestamp() + 2 + types.ExtremeFutureThreshold
	solvedBlock, _ := cst.miner.SolveBlock(block, target)
	err = cst.cs.AcceptBlock(solvedBlock)
	if err != errExtremeFutureTimestamp {
		t.Fatalf("expected %v, got %v", errFutureTimestamp, err)
	}
}

785 786 787
// TestBuriedBadTransaction tries submitting a block with a bad transaction
// that is buried under good transactions.
func TestBuriedBadTransaction(t *testing.T) {
788
	if testing.Short() {
789 790
		t.SkipNow()
	}
791
	t.Parallel()
792
	cst, err := createConsensusSetTester(t.Name())
793 794 795
	if err != nil {
		t.Fatal(err)
	}
796
	defer cst.Close()
797
	pb := cst.cs.dbCurrentProcessedBlock()
798 799 800

	// Create a good transaction using the wallet.
	txnValue := types.NewCurrency64(1200)
801 802 803 804
	txnBuilder, err := cst.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
805
	err = txnBuilder.FundSiacoins(txnValue)
806 807 808
	if err != nil {
		t.Fatal(err)
	}
809 810
	txnBuilder.AddSiacoinOutput(types.SiacoinOutput{Value: txnValue})
	txnSet, err := txnBuilder.Sign(true)
811 812 813
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
814
	err = cst.tpool.AcceptTransactionSet(txnSet)
815 816 817 818 819 820 821 822
	if err != nil {
		t.Fatal(err)
	}

	// Create a bad transaction
	badTxn := types.Transaction{
		SiacoinInputs: []types.SiacoinInput{{}},
	}
823
	txns := append(cst.tpool.TransactionList(), badTxn)
824 825 826

	// Create a block with a buried bad transaction.
	block := types.Block{
triazo's avatar
triazo committed
827
		ParentID:     pb.Block.ID(),
828
		Timestamp:    types.CurrentTimestamp(),
triazo's avatar
triazo committed
829
		MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height + 1)}},
830 831
		Transactions: txns,
	}
triazo's avatar
triazo committed
832
	block, _ = cst.miner.SolveBlock(block, pb.ChildTarget)
833 834 835 836 837
	err = cst.cs.AcceptBlock(block)
	if err == nil {
		t.Error("buried transaction didn't cause an error")
	}
}
838

839 840 841 842 843 844
// TestInconsistencyCheck puts the consensus set in to an inconsistent state
// and makes sure that the santiy checks are triggering panics.
func TestInconsistentCheck(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
845
	t.Parallel()
846
	cst, err := createConsensusSetTester(t.Name())
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	if err != nil {
		t.Fatal(err)
	}

	// Corrupt the consensus set by adding a new siafund output.
	sfo := types.SiafundOutput{
		Value: types.NewCurrency64(1),
	}
	cst.cs.dbAddSiafundOutput(types.SiafundOutputID{}, sfo)

	// Catch a panic that should be caused by the inconsistency check after a
	// block is mined.
	defer func() {
		r := recover()
		if r == nil {
			t.Fatalf("inconsistency panic not triggered by corrupted database")
		}
	}()
865 866 867 868
	_, err = cst.miner.AddBlock()
	if err != nil {
		t.Fatal(err)
	}
869 870
}

871 872
// COMPATv0.4.0
//
David Vorick's avatar
David Vorick committed
873
// This test checks that the hardfork scheduled for block 21,000 rolls through
874 875 876 877 878
// smoothly.
func TestTaxHardfork(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
879
	t.Parallel()
880
	cst, err := createConsensusSetTester(t.Name())
881 882 883
	if err != nil {
		t.Fatal(err)
	}
884
	defer cst.Close()
885 886 887 888

	// Create a file contract with a payout that is put into the blockchain
	// before the hardfork block but expires after the hardfork block.
	payout := types.NewCurrency64(400e6)
David Vorick's avatar
David Vorick committed
889
	outputSize := types.PostTax(cst.cs.dbBlockHeight(), payout)
890
	fc := types.FileContract{
David Vorick's avatar
David Vorick committed
891 892
		WindowStart:        cst.cs.dbBlockHeight() + 12,
		WindowEnd:          cst.cs.dbBlockHeight() + 14,
893
		Payout:             payout,
David Vorick's avatar
David Vorick committed
894 895 896
		ValidProofOutputs:  []types.SiacoinOutput{{Value: outputSize}},
		MissedProofOutputs: []types.SiacoinOutput{{Value: outputSize}},
		UnlockHash:         types.UnlockConditions{}.UnlockHash(), // The empty UC is anyone-can-spend
897 898 899
	}

	// Create and fund a transaction with a file contract.
900 901 902 903
	txnBuilder, err := cst.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
904
	err = txnBuilder.FundSiacoins(payout)
905 906 907
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
908
	fcIndex := txnBuilder.AddFileContract(fc)
909
	txnSet, err := txnBuilder.Sign(true)
910 911 912
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
913
	err = cst.tpool.AcceptTransactionSet(txnSet)
914 915 916
	if err != nil {
		t.Fatal(err)
	}
917
	_, err = cst.miner.AddBlock()
918 919 920 921
	if err != nil {
		t.Fatal(err)
	}

David Vorick's avatar
David Vorick committed
922 923
	// Check that the siafund pool was increased by the faulty float amount.
	siafundPool := cst.cs.dbGetSiafundPool()
Luke Champine's avatar
Luke Champine committed
924
	if !siafundPool.Equals64(15590e3) {
925 926 927
		t.Fatal("siafund pool was not increased correctly")
	}

David Vorick's avatar
David Vorick committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	// Mine blocks until the hardfork is reached.
	for i := 0; i < 10; i++ {
		_, err = cst.miner.AddBlock()
		if err != nil {
			t.Fatal(err)
		}
	}

	// Submit a file contract revision and check that the payouts are able to
	// be the same.
	fcid := txnSet[len(txnSet)-1].FileContractID(fcIndex)
	fcr := types.FileContractRevision{
		ParentID:          fcid,
		UnlockConditions:  types.UnlockConditions{},
		NewRevisionNumber: 1,

		NewFileSize:           1,
		NewWindowStart:        cst.cs.dbBlockHeight() + 2,
		NewWindowEnd:          cst.cs.dbBlockHeight() + 4,
		NewValidProofOutputs:  fc.ValidProofOutputs,
		NewMissedProofOutputs: fc.MissedProofOutputs,
	}
950 951 952 953
	txnBuilder, err = cst.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
	txnBuilder.AddFileContractRevision(fcr)
	txnSet, err = txnBuilder.Sign(true)
	if err != nil {
		t.Fatal(err)
	}
	err = cst.tpool.AcceptTransactionSet(txnSet)
	if err != nil {
		t.Fatal(err)
	}
	_, err = cst.miner.AddBlock()
	if err != nil {
		t.Fatal(err)
	}

	// Mine blocks until the revision goes through, such that the sanity checks
	// can be run.
	for i := 0; i < 6; i++ {
971
		_, err = cst.miner.AddBlock()
972 973 974 975
		if err != nil {
			t.Fatal(err)
		}
	}
David Vorick's avatar
David Vorick committed
976 977 978

	// Check that the siafund pool did not change after the submitted revision.
	siafundPool = cst.cs.dbGetSiafundPool()
Luke Champine's avatar
Luke Champine committed
979
	if !siafundPool.Equals64(15590e3) {
David Vorick's avatar
David Vorick committed
980 981
		t.Fatal("siafund pool was not increased correctly")
	}
982
}
983

984 985 986
// mockGatewayDoesBroadcast implements modules.Gateway to mock the Broadcast
// method.
type mockGatewayDoesBroadcast struct {
987
	modules.Gateway
988
	broadcastCalled chan struct{}
989 990
}

991 992
// Broadcast is a mock implementation of modules.Gateway.Broadcast that
// sends a sentinel value down a channel to signal it's been called.
993 994
func (g *mockGatewayDoesBroadcast) Broadcast(name string, obj interface{}, peers []modules.Peer) {
	g.Gateway.Broadcast(name, obj, peers)
995
	g.broadcastCalled <- struct{}{}
996 997 998 999 1000
}

// TestAcceptBlockBroadcasts tests that AcceptBlock broadcasts valid blocks and
// that managedAcceptBlock does not.
func TestAcceptBlockBroadcasts(t *testing.T) {
1001 1002 1003
	if testing.Short() {
		t.SkipNow()
	}
1004
	t.Parallel()
1005
	cst, err := blankConsensusSetTester(t.Name(), modules.ProdDependencies)
1006 1007 1008 1009
	if err != nil {
		t.Fatal(err)
	}
	defer cst.Close()
1010 1011 1012
	mg := &mockGatewayDoesBroadcast{
		Gateway:         cst.cs.gateway,
		broadcastCalled: make(chan struct{}),
1013
	}
1014 1015 1016 1017 1018 1019 1020 1021
	cst.cs.gateway = mg

	// Test that Broadcast is called for valid blocks.
	b, _ := cst.miner.FindBlock()
	err = cst.cs.AcceptBlock(b)
	if err != nil {
		t.Fatal(err)
	}
1022 1023 1024 1025
	select {
	case <-mg.broadcastCalled:
	case <-time.After(10 * time.Millisecond):
		t.Error("expected AcceptBlock to broadcast a valid block")
1026 1027 1028 1029 1030 1031 1032
	}

	// Test that Broadcast is not called for invalid blocks.
	err = cst.cs.AcceptBlock(types.Block{})
	if err == nil {
		t.Fatal("expected AcceptBlock to error on an invalid block")
	}
1033 1034
	select {
	case <-mg.broadcastCalled:
1035
		t.Error("AcceptBlock broadcasted an invalid block")
1036
	case <-time.After(10 * time.Millisecond):
1037 1038 1039 1040
	}

	// Test that Broadcast is not called in managedAcceptBlock.
	b, _ = cst.miner.FindBlock()
1041
	_, err = cst.cs.managedAcceptBlocks([]types.Block{b})
1042 1043 1044
	if err != nil {
		t.Fatal(err)
	}
1045 1046 1047 1048
	select {
	case <-mg.broadcastCalled:
		t.Errorf("managedAcceptBlock should not broadcast blocks")
	case <-time.After(10 * time.Millisecond):
1049 1050
	}
}
1051 1052 1053 1054 1055

// blockCountingSubscriber counts the number of blocks that get submitted to the
// subscriber, as well as the number of times that the subscriber has been given
// changes at all.
type blockCountingSubscriber struct {
1056 1057
	changes []modules.ConsensusChangeID

1058 1059 1060 1061 1062 1063 1064
	appliedBlocks  int
	revertedBlocks int
}

// ProcessConsensusChange fills the subscription interface for the
// blockCountingSubscriber.
func (bcs *blockCountingSubscriber) ProcessConsensusChange(cc modules.ConsensusChange) {
1065
	bcs.changes = append(bcs.changes, cc.ID)
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	bcs.revertedBlocks += len(cc.RevertedBlocks)
	bcs.appliedBlocks += len(cc.AppliedBlocks)
}

// TestChainedAcceptBlock creates series of blocks, some of which are valid,
// some invalid, and submits them to the consensus set, verifying that the
// consensus set updates correctly each time.
func TestChainedAcceptBlock(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	t.Parallel()
	// Create a tester to send blocks in a batch to the other tester.
	cst, err := createConsensusSetTester(t.Name())
	if err != nil {
		t.Fatal(err)
	}
	defer cst.Close()
1084
	cst2, err := blankConsensusSetTester(t.Name()+"2", modules.ProdDependencies)
1085 1086 1087 1088 1089 1090
	if err != nil {
		t.Fatal(err)
	}
	defer cst2.Close()
	// Subscribe a blockCountingSubscriber to cst2.
	var bcs blockCountingSubscriber
Christopher Schinnerl's avatar
Christopher Schinnerl committed
1091
	cst2.cs.ConsensusSetSubscribe(&bcs, modules.ConsensusChangeBeginning, cst2.cs.tg.StopChan())
1092
	if len(bcs.changes) != 1 || bcs.appliedBlocks != 1 || bcs.revertedBlocks != 0 {
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
		t.Error("consensus changes do not seem to be getting passed to subscribers correctly")
	}

	// Grab all of the blocks in cst, with the intention of giving them to cst2.
	var blocks []types.Block
	height := cst.cs.Height()
	for i := types.BlockHeight(0); i <= height; i++ {
		id, err := cst.cs.dbGetPath(i)
		if err != nil {
			t.Fatal(err)
		}
		pb, err := cst.cs.dbGetBlockMap(id)
		if err != nil {
			t.Fatal(err)
		}
		blocks = append(blocks, pb.Block)
	}

	// Create a jumbling of the blocks, so that the set is not in order.
	jumble := make([]types.Block, len(blocks))
	jumble[0] = blocks[0]
	jumble[1] = blocks[2]
	jumble[2] = blocks[1]
	for i := 3; i < len(jumble); i++ {
		jumble[i] = blocks[i]
	}
	// Try to submit the blocks out-of-order, which would violate one of the
	// assumptions in managedAcceptBlocks.
	_, err = cst2.cs.managedAcceptBlocks(jumble)
	if err != errNonLinearChain {
		t.Fatal(err)
	}
	if cst2.cs.Height() != 0 {
		t.Fatal("blocks added even though the inputs were jumbled")
	}
1128
	if len(bcs.changes) != 1 || bcs.appliedBlocks != 1 || bcs.revertedBlocks != 0 {
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
		t.Error("consensus changes do not seem to be getting passed to subscribers correctly")
	}

	// Tag an invalid block onto the end of blocks.
	block, err := cst.miner.AddBlock()
	if err != nil {
		t.Fatal(err)
	}
	// Adding an invalid transaction to make the block invalid.
	badBlock := block
	badBlock.Transactions = append(badBlock.Transactions, types.Transaction{
		SiacoinInputs: []types.SiacoinInput{{
			ParentID: types.SiacoinOutputID{1},
		}},
	})
	// Append the invalid transaction to the block.
David Vorick's avatar
David Vorick committed
1145 1146 1147
	badBlocks := append(blocks, badBlock)
	// Submit the whole invalid set. Result should be that nothing is added.
	_, err = cst2.cs.managedAcceptBlocks(badBlocks)
1148 1149 1150
	if err == nil {
		t.Fatal(err)
	}
David Vorick's avatar
David Vorick committed
1151
	if cst2.cs.Height() != 0 {
1152 1153
		t.Log(cst2.cs.Height())
		t.Log(cst.cs.Height())
David Vorick's avatar
David Vorick committed
1154
		t.Fatal("height is not correct, seems that blocks were added")
1155
	}
David Vorick's avatar
David Vorick committed
1156
	if bcs.appliedBlocks != 1 || bcs.revertedBlocks != 0 {
1157 1158 1159
		t.Error("consensus changes do not seem to be getting passed to subscribers correctly")
	}

David Vorick's avatar
David Vorick committed
1160 1161
	// Try submitting the good blocks.
	_, err = cst2.cs.managedAcceptBlocks(blocks)
1162 1163 1164
	if err != nil {
		t.Fatal(err)
	}
1165
	if bcs.appliedBlocks != int(cst2.cs.Height()+1) || bcs.revertedBlocks != 0 {
1166 1167
		t.Error("consensus changes do not seem to be getting passed to subscribers correctly")
	}
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

	// Check that every change recorded in 'bcs' is also available in the
	// consensus set.
	for _, change := range bcs.changes {
		err := cst2.cs.db.Update(func(tx *bolt.Tx) error {
			_, exists := getEntry(tx, change)
			if !exists {
				t.Error("an entry was provided that doesn't exist")
			}
			return nil
		})
		if err != nil {
			t.Fatal(err)
		}
	}
1183
}