本文整理匯總了Golang中github.com/NebulousLabs/Sia/types.CurrentTimestamp函數的典型用法代碼示例。如果您正苦於以下問題:Golang CurrentTimestamp函數的具體用法?Golang CurrentTimestamp怎麽用?Golang CurrentTimestamp使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了CurrentTimestamp函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: validHeader
// validHeader does some early, low computation verification on the block.
func (cs *State) validHeader(b types.Block) error {
// Grab the parent of the block and verify the ID of the child meets the
// target. This is done as early as possible to enforce that any
// block-related DoS must use blocks that have sufficient work.
parent, exists := cs.blockMap[b.ParentID]
if !exists {
return ErrOrphan
}
if !b.CheckTarget(parent.childTarget) {
return ErrMissedTarget
}
// Check that the block is below the size limit.
if uint64(len(encoding.Marshal(b))) > types.BlockSizeLimit {
return ErrLargeBlock
}
// Check that the timestamp is not in 'the past', where the past is defined
// by earliestChildTimestamp.
if parent.earliestChildTimestamp() > b.Timestamp {
return ErrEarlyTimestamp
}
// If the block is in the extreme future, return an error and do nothing
// more with the block. There is an assumption that by the time the extreme
// future arrives, this block will no longer be a part of the longest fork
// because it will have been ignored by all of the miners.
if b.Timestamp > types.CurrentTimestamp()+types.ExtremeFutureThreshold {
return ErrExtremeFutureTimestamp
}
// Verify that the miner payouts are valid.
if !b.CheckMinerPayouts(parent.height + 1) {
return ErrBadMinerPayouts
}
// If the block is in the near future, but too far to be acceptable, then
// the block will be saved and added to the consensus set after it is no
// longer too far in the future. This is the last check because it's an
// expensive check, and not worth performing if the payouts are incorrect.
if b.Timestamp > types.CurrentTimestamp()+types.FutureThreshold {
go func() {
time.Sleep(time.Duration(b.Timestamp-(types.CurrentTimestamp()+types.FutureThreshold)) * time.Second)
lockID := cs.mu.Lock()
defer cs.mu.Unlock(lockID)
cs.acceptBlock(b) // NOTE: Error is not handled.
}()
return ErrFutureTimestamp
}
return nil
}
示例2: TestFutureTimestampHandling
// testFutureTimestampHandling checks that blocks in the future (but not
// extreme future) are handled correctly.
func TestFutureTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
cst, err := createConsensusSetTester("TestFutureTimestampHandling")
if err != nil {
t.Fatal(err)
}
defer cst.closeCst()
// Submit a block with a timestamp in the future, but not the extreme
// future.
block, target, err := cst.miner.BlockForWork()
if err != nil {
t.Fatal(err)
}
block.Timestamp = types.CurrentTimestamp() + 2 + types.FutureThreshold
solvedBlock, _ := cst.miner.SolveBlock(block, target)
err = cst.cs.AcceptBlock(solvedBlock)
if err != errFutureTimestamp {
t.Fatalf("expected %v, got %v", errFutureTimestamp, err)
}
// Check that after waiting until the block is no longer too far in the
// future, the block gets added to the consensus set.
time.Sleep(time.Second * 3) // 3 seconds, as the block was originally 2 seconds too far into the future.
_, err = cst.cs.dbGetBlockMap(solvedBlock.ID())
if err == errNilItem {
t.Fatalf("future block was not added to the consensus set after waiting the appropriate amount of time")
}
}
示例3: TestExtremeFutureTimestampHandling
// TestExtremeFutureTimestampHandling checks that blocks with extreme future
// timestamps handled correclty.
func TestExtremeFutureTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
cst, err := createConsensusSetTester("TestExtremeFutureTimestampHandling")
if err != nil {
t.Fatal(err)
}
// Submit a block with a timestamp in the extreme future.
block, _, target := cst.miner.BlockForWork()
block.Timestamp = types.CurrentTimestamp() + 2 + types.ExtremeFutureThreshold
solvedBlock, _ := cst.miner.SolveBlock(block, target)
err = cst.cs.acceptBlock(solvedBlock)
if err != ErrExtremeFutureTimestamp {
t.Error("Expecting ErrExtremeFutureTimestamp", err)
}
// Check that after waiting until the block is no longer in the future, the
// block still has not been added to the consensus set (prove that the
// block was correctly discarded).
time.Sleep(time.Second * time.Duration(3+types.ExtremeFutureThreshold))
lockID := cst.cs.mu.RLock()
defer cst.cs.mu.RUnlock(lockID)
_, exists := cst.cs.blockMap[solvedBlock.ID()]
if exists {
t.Error("extreme future block made it into the consensus set after waiting")
}
}
示例4: TestEarlyTimestampHandling
// TestEarlyTimestampHandling checks that blocks too far in the past are
// rejected.
func TestEarlyTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestEarlyTimestampHandling")
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)
}
}
示例5: TestExtremeFutureTimestampHandling
// TestExtremeFutureTimestampHandling checks that blocks with extreme future
// timestamps handled correclty.
func TestExtremeFutureTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
cst, err := createConsensusSetTester("TestExtremeFutureTimestampHandling")
if err != nil {
t.Fatal(err)
}
defer cst.closeCst()
// 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", errExtremeFutureTimestamp, err)
}
// Check that after waiting until the block is no longer in the future, the
// block still has not been added to the consensus set (prove that the
// block was correctly discarded).
time.Sleep(time.Second * time.Duration(3+types.ExtremeFutureThreshold))
_, err = cst.cs.dbGetBlockMap(solvedBlock.ID())
if err != errNilItem {
t.Error("extreme future block made it into the consensus set after waiting")
}
}
示例6: TestBuriedBadFork
// TestBuriedBadFork creates a block with an invalid transaction that's not on
// the longest fork. The consensus set will not validate that block. Then valid
// blocks are added on top of it to make it the longest fork. When it becomes
// the longest fork, all the blocks should be fully validated and thrown out
// because a parent is invalid.
func TestBuriedBadFork(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestBuriedBadFork")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
pb := cst.cs.dbCurrentProcessedBlock()
// Create a bad block that builds on a parent, so that it is part of not
// the longest fork.
badBlock := types.Block{
ParentID: pb.Block.ParentID,
Timestamp: types.CurrentTimestamp(),
MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height)}},
Transactions: []types.Transaction{{
SiacoinInputs: []types.SiacoinInput{{}}, // Will trigger an error on full verification but not partial verification.
}},
}
parent, err := cst.cs.dbGetBlockMap(pb.Block.ParentID)
if err != nil {
t.Fatal(err)
}
badBlock, _ = cst.miner.SolveBlock(badBlock, parent.ChildTarget)
err = cst.cs.AcceptBlock(badBlock)
if err != modules.ErrNonExtendingBlock {
t.Fatal(err)
}
// Build another bock on top of the bad block that is fully valid, this
// will cause a fork and full validation of the bad block, both the bad
// block and this block should be thrown away.
block := types.Block{
ParentID: badBlock.ID(),
Timestamp: types.CurrentTimestamp(),
MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height + 1)}},
}
block, _ = cst.miner.SolveBlock(block, parent.ChildTarget) // okay because the target will not change
err = cst.cs.AcceptBlock(block)
if err == nil {
t.Fatal("a bad block failed to cause an error")
}
}
示例7: validateHeader
// validateHeader does some early, low computation verification on the header
// to determine if the block should be downloaded. Callers should not assume
// that validation will happen in a particular order.
func (cs *ConsensusSet) validateHeader(tx dbTx, h types.BlockHeader) error {
// Check if the block is a DoS block - a known invalid block that is expensive
// to validate.
id := h.ID()
_, exists := cs.dosBlocks[id]
if exists {
return errDoSBlock
}
// Check if the block is already known.
blockMap := tx.Bucket(BlockMap)
if blockMap == nil {
return errNoBlockMap
}
if blockMap.Get(id[:]) != nil {
return modules.ErrBlockKnown
}
// Check for the parent.
parentID := h.ParentID
parentBytes := blockMap.Get(parentID[:])
if parentBytes == nil {
return errOrphan
}
var parent processedBlock
err := cs.marshaler.Unmarshal(parentBytes, &parent)
if err != nil {
return err
}
// Check that the target of the new block is sufficient.
if !checkHeaderTarget(h, parent.ChildTarget) {
return modules.ErrBlockUnsolved
}
// TODO: check if the block is a non extending block once headers-first
// downloads are implemented.
// Check that the timestamp is not too far in the past to be acceptable.
minTimestamp := cs.blockRuleHelper.minimumValidChildTimestamp(blockMap, &parent)
if minTimestamp > h.Timestamp {
return errEarlyTimestamp
}
// Check if the block is in the extreme future. We make a distinction between
// future and extreme future because there is an assumption that by the time
// the extreme future arrives, this block will no longer be a part of the
// longest fork because it will have been ignored by all of the miners.
if h.Timestamp > types.CurrentTimestamp()+types.ExtremeFutureThreshold {
return errExtremeFutureTimestamp
}
// We do not check if the header is in the near future here, because we want
// to get the corresponding block as soon as possible, even if the block is in
// the near future.
return nil
}
示例8: blockForWork
// blockForWork returns a block that is ready for nonce grinding, including
// correct miner payouts and a random transaction to prevent collisions and
// overlapping work with other blocks being mined in parallel or for different
// forks (during testing).
func (m *Miner) blockForWork() types.Block {
b := m.unsolvedBlock
// Update the timestmap.
if b.Timestamp < types.CurrentTimestamp() {
b.Timestamp = types.CurrentTimestamp()
}
// Update the address + payouts.
_ = m.checkAddress() // Err is ignored - address generation failed but can't do anything about it (log maybe).
b.MinerPayouts = []types.SiacoinOutput{{Value: b.CalculateSubsidy(m.height + 1), UnlockHash: m.address}}
// Add an arb-data txn to the block to create a unique merkle root.
randBytes, _ := crypto.RandBytes(types.SpecifierLen)
randTxn := types.Transaction{
ArbitraryData: [][]byte{append(modules.PrefixNonSia[:], randBytes...)},
}
b.Transactions = append([]types.Transaction{randTxn}, b.Transactions...)
return b
}
示例9: blockForWork
// blockForWork returns a block that is ready for nonce grinding, including
// correct miner payouts and a random transaction to prevent collisions and
// overlapping work with other blocks being mined in parallel or for different
// forks (during testing).
func (m *Miner) blockForWork() types.Block {
b := m.persist.UnsolvedBlock
// Update the timestmap.
if b.Timestamp < types.CurrentTimestamp() {
b.Timestamp = types.CurrentTimestamp()
}
// Update the address + payouts.
err := m.checkAddress()
if err != nil {
m.log.Println(err)
}
b.MinerPayouts = []types.SiacoinOutput{{Value: b.CalculateSubsidy(m.persist.Height + 1), UnlockHash: m.persist.Address}}
// Add an arb-data txn to the block to create a unique merkle root.
randBytes, _ := crypto.RandBytes(types.SpecifierLen)
randTxn := types.Transaction{
ArbitraryData: [][]byte{append(modules.PrefixNonSia[:], randBytes...)},
}
b.Transactions = append([]types.Transaction{randTxn}, b.Transactions...)
return b
}
示例10: TestBuriedBadTransaction
// TestBuriedBadTransaction tries submitting a block with a bad transaction
// that is buried under good transactions.
func TestBuriedBadTransaction(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestBuriedBadTransaction")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
pb := cst.cs.dbCurrentProcessedBlock()
// Create a good transaction using the wallet.
txnValue := types.NewCurrency64(1200)
txnBuilder := cst.wallet.StartTransaction()
err = txnBuilder.FundSiacoins(txnValue)
if err != nil {
t.Fatal(err)
}
txnBuilder.AddSiacoinOutput(types.SiacoinOutput{Value: txnValue})
txnSet, err := txnBuilder.Sign(true)
if err != nil {
t.Fatal(err)
}
err = cst.tpool.AcceptTransactionSet(txnSet)
if err != nil {
t.Fatal(err)
}
// Create a bad transaction
badTxn := types.Transaction{
SiacoinInputs: []types.SiacoinInput{{}},
}
txns := append(cst.tpool.TransactionList(), badTxn)
// Create a block with a buried bad transaction.
block := types.Block{
ParentID: pb.Block.ID(),
Timestamp: types.CurrentTimestamp(),
MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height + 1)}},
Transactions: txns,
}
block, _ = cst.miner.SolveBlock(block, pb.ChildTarget)
err = cst.cs.AcceptBlock(block)
if err == nil {
t.Error("buried transaction didn't cause an error")
}
}
示例11: blockForWork
// Creates a block ready for nonce grinding, also returning the MerkleRoot of
// the block. Getting the MerkleRoot of a block requires encoding and hashing
// in a specific way, which are implementation details we didn't want to
// require external miners to need to worry about. All blocks returned are
// unique, which means all miners can safely start at the '0' nonce.
func (m *Miner) blockForWork() (types.Block, types.Target) {
// Determine the timestamp.
blockTimestamp := types.CurrentTimestamp()
if blockTimestamp < m.earliestTimestamp {
blockTimestamp = m.earliestTimestamp
}
// Create the miner payouts.
subsidy := types.CalculateCoinbase(m.height)
for _, txn := range m.transactions {
for _, fee := range txn.MinerFees {
subsidy = subsidy.Add(fee)
}
}
blockPayouts := []types.SiacoinOutput{types.SiacoinOutput{Value: subsidy, UnlockHash: m.address}}
// Create the list of transacitons, including the randomized transaction.
// The transactions are assembled by calling append(singleElem,
// existingSlic) because doing it the reverse way has some side effects,
// creating a race condition and ultimately changing the block hash for
// other parts of the program. This is related to the fact that slices are
// pointers, and not immutable objects. Use of the builtin `copy` function
// when passing objects like blocks around may fix this problem.
randBytes := make([]byte, types.SpecifierLen)
rand.Read(randBytes)
randTxn := types.Transaction{
ArbitraryData: [][]byte{append(modules.PrefixNonSia[:], randBytes...)},
}
blockTransactions := append([]types.Transaction{randTxn}, m.transactions...)
// Assemble the block
b := types.Block{
ParentID: m.parent,
Timestamp: blockTimestamp,
MinerPayouts: blockPayouts,
Transactions: blockTransactions,
}
return b, m.target
}
示例12: testFutureTimestampHandling
// testFutureTimestampHandling checks that blocks in the future (but not
// extreme future) are handled correctly.
func (cst *consensusSetTester) testFutureTimestampHandling() error {
// Submit a block with a timestamp in the future, but not the extreme
// future.
block, _, target := cst.miner.BlockForWork()
block.Timestamp = types.CurrentTimestamp() + 2 + types.FutureThreshold
solvedBlock, _ := cst.miner.SolveBlock(block, target)
err := cst.cs.acceptBlock(solvedBlock)
if err != ErrFutureTimestamp {
return errors.New("Expecting ErrExtremeFutureTimestamp: " + err.Error())
}
// Check that after waiting until the block is no longer too far in the
// future, the block gets added to the consensus set.
time.Sleep(time.Second * 3) // 3 seconds, as the block was originally 2 seconds too far into the future.
lockID := cst.cs.mu.RLock()
defer cst.cs.mu.RUnlock(lockID)
_, exists := cst.cs.blockMap[solvedBlock.ID()]
if !exists {
return errors.New("future block was not added to the consensus set after waiting the appropriate amount of time.")
}
return nil
}
示例13: TestExtremeFutureTimestampHandling
// TestExtremeFutureTimestampHandling checks that blocks in the extreme future
// are rejected.
func TestExtremeFutureTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestExtremeFutureTimestampHandling")
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)
}
}
示例14: TestFutureTimestampHandling
// testFutureTimestampHandling checks that blocks in the future (but not
// extreme future) are handled correctly.
func TestFutureTimestampHandling(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestFutureTimestampHandling")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
// Submit a block with a timestamp in the future, but not the extreme
// future.
block, target, err := cst.miner.BlockForWork()
if err != nil {
t.Fatal(err)
}
block.Timestamp = types.CurrentTimestamp() + 2 + types.FutureThreshold
solvedBlock, _ := cst.miner.SolveBlock(block, target)
err = cst.cs.AcceptBlock(solvedBlock)
if err != errFutureTimestamp {
t.Fatalf("expected %v, got %v", errFutureTimestamp, err)
}
// Poll the consensus set until the future block appears.
for i := 0; i < 30; i++ {
time.Sleep(time.Second * 3)
_, err = cst.cs.dbGetBlockMap(solvedBlock.ID())
if err == nil {
break
}
}
_, 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)
}
}
示例15: TestRelayHeader
// TestRelayHeader tests that rpcRelayHeader requests the corresponding blocks
// to valid headers with known parents, or requests the block history to orphan
// headers.
func TestRelayHeader(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
cst, err := blankConsensusSetTester("TestRelayHeader")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
mg := &mockGatewayCallsRPC{
Gateway: cst.cs.gateway,
rpcCalled: make(chan string),
}
cst.cs.gateway = mg
p1, p2 := net.Pipe()
mockP2 := mockPeerConn{p2}
// Valid block that rpcRelayHeader should accept.
validBlock, err := cst.miner.FindBlock()
if err != nil {
t.Fatal(err)
}
// A block in the near future that rpcRelayHeader return an error for, but
// still request the corresponding block.
block, target, err := cst.miner.BlockForWork()
if err != nil {
t.Fatal(err)
}
block.Timestamp = types.CurrentTimestamp() + 2 + types.FutureThreshold
futureBlock, _ := cst.miner.SolveBlock(block, target)
tests := []struct {
header types.BlockHeader
errWant error
errMSG string
rpcWant string
rpcMSG string
}{
// Test that rpcRelayHeader rejects known blocks.
{
header: types.GenesisBlock.Header(),
errWant: modules.ErrBlockKnown,
errMSG: "rpcRelayHeader should reject headers to known blocks",
},
// Test that rpcRelayHeader requests the parent blocks of orphan headers.
{
header: types.BlockHeader{},
errWant: nil,
errMSG: "rpcRelayHeader should not return an error for orphan headers",
rpcWant: "SendBlocks",
rpcMSG: "rpcRelayHeader should request blocks when the relayed header is an orphan",
},
// Test that rpcRelayHeader accepts a valid header that extends the longest chain.
{
header: validBlock.Header(),
errWant: nil,
errMSG: "rpcRelayHeader should accept a valid header",
rpcWant: "SendBlk",
rpcMSG: "rpcRelayHeader should request the block of a valid header",
},
// Test that rpcRelayHeader requests a future, but otherwise valid block.
{
header: futureBlock.Header(),
errWant: nil,
errMSG: "rpcRelayHeader should not return an error for a future header",
rpcWant: "SendBlk",
rpcMSG: "rpcRelayHeader should request the corresponding block to a future, but otherwise valid header",
},
}
errChan := make(chan error)
for _, tt := range tests {
go func() {
errChan <- encoding.WriteObject(p1, tt.header)
}()
err = cst.cs.threadedRPCRelayHeader(mockP2)
if err != tt.errWant {
t.Errorf("%s: expected '%v', got '%v'", tt.errMSG, tt.errWant, err)
}
err = <-errChan
if err != nil {
t.Fatal(err)
}
if tt.rpcWant == "" {
select {
case rpc := <-mg.rpcCalled:
t.Errorf("no RPC call expected, but '%v' was called", rpc)
case <-time.After(10 * time.Millisecond):
}
} else {
select {
case rpc := <-mg.rpcCalled:
if rpc != tt.rpcWant {
t.Errorf("%s: expected '%v', got '%v'", tt.rpcMSG, tt.rpcWant, rpc)
}
//.........這裏部分代碼省略.........