本文整理匯總了Golang中github.com/NebulousLabs/Sia/crypto.HashObject函數的典型用法代碼示例。如果您正苦於以下問題:Golang HashObject函數的具體用法?Golang HashObject怎麽用?Golang HashObject使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了HashObject函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: removeTailTransaction
// removeTailTransaction removes the most recent transaction from the pool. The
// most recent transaction is guaranteed not to have any dependents or
// children.
func (tp *TransactionPool) removeTailTransaction() {
// Sanity check - the transaction list should not be empty if
// removeTailTransaction has been called.
if len(tp.transactionList) == 0 {
if build.DEBUG {
panic("calling removeTailTransaction when transaction list is empty")
}
return
}
// Grab the most recent transaction and remove it from the unconfirmed
// consensus set piecemeal.
t := tp.transactionList[len(tp.transactionList)-1]
tp.removeSiacoinInputs(t)
tp.removeSiacoinOutputs(t)
tp.removeFileContracts(t)
tp.removeFileContractRevisions(t)
tp.removeStorageProofs(t)
tp.removeSiafundInputs(t)
tp.removeSiafundOutputs(t)
// Sanity check - transaction hash should be in the list of transactions.
if build.DEBUG {
_, exists := tp.transactions[crypto.HashObject(t)]
if !exists {
panic("transaction not available in transaction list")
}
}
// Remove the transaction from the transaction lists.
delete(tp.transactions, crypto.HashObject(t))
tp.transactionList = tp.transactionList[:len(tp.transactionList)-1]
return
}
示例2: TestIntegrationBlankEncryption
// TestIntegrationBlankEncryption probes the encryption process when the user
// supplies a blank encryption key during the encryption process.
func TestIntegrationBlankEncryption(t *testing.T) {
// Create the wallet.
wt, err := createBlankWalletTester("TestIntegrationBlankEncryption")
if err != nil {
t.Fatal(err)
}
defer wt.closeWt()
// Encrypt the wallet using a blank key.
seed, err := wt.wallet.Encrypt(crypto.TwofishKey{})
if err != nil {
t.Error(err)
}
// Try unlocking the wallet using a blank key.
err = wt.wallet.Unlock(crypto.TwofishKey{})
if err != modules.ErrBadEncryptionKey {
t.Fatal(err)
}
// Try unlocking the wallet using the correct key.
err = wt.wallet.Unlock(crypto.TwofishKey(crypto.HashObject(seed)))
if err != nil {
t.Fatal(err)
}
err = wt.wallet.Lock()
if err != nil {
t.Fatal(err)
}
postEncryptionTesting(wt.miner, wt.wallet, crypto.TwofishKey(crypto.HashObject(seed)))
}
示例3: encryptionKeys
// encryptionKeys enumerates the possible encryption keys that can be derived
// from an input string.
func encryptionKeys(seedStr string) (validKeys []crypto.TwofishKey) {
dicts := []mnemonics.DictionaryID{"english", "german", "japanese"}
for _, dict := range dicts {
seed, err := modules.StringToSeed(seedStr, dict)
if err != nil {
continue
}
validKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(seed)))
}
validKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(seedStr)))
return validKeys
}
示例4: TestIntegrationMinerHeader
// TestIntegrationMinerHeader checks that the header GET and POST calls are
// useful tools for mining blocks.
func TestIntegrationMinerHeader(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
st, err := createServerTester("TestIntegrationMinerHeader")
if err != nil {
t.Fatal(err)
}
defer st.server.Close()
startingHeight := st.cs.Height()
// Get a header that can be used for mining.
resp, err := HttpGET("http://" + st.server.listener.Addr().String() + "/miner/header")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
targetAndHeader, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
// Twiddle the header bits until a block has been found.
//
// Note: this test treats the target as hardcoded, if the testing target is
// changed, this test will also need to be changed.
if types.RootTarget[0] != 128 {
t.Fatal("test will fail because the testing constants have been unexpectedly changed")
}
var header [80]byte
copy(header[:], targetAndHeader[32:])
headerHash := crypto.HashObject(header)
for headerHash[0] >= types.RootTarget[0] {
header[35]++
headerHash = crypto.HashObject(header)
}
// Submit the solved header through the api and check that the height of
// the blockchain increases.
resp, err = HttpPOST("http://"+st.server.listener.Addr().String()+"/miner/header", string(header[:]))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
time.Sleep(500 * time.Millisecond)
if st.cs.Height() != startingHeight+1 {
t.Errorf("block height did not increase after trying to mine a block through the api, started at %v and ended at %v", startingHeight, st.cs.Height())
}
}
示例5: acceptTransactionSet
// acceptTransactionSet verifies that a transaction set is allowed to be in the
// transaction pool, and then adds it to the transaction pool.
func (tp *TransactionPool) acceptTransactionSet(ts []types.Transaction) error {
if len(ts) == 0 {
return errEmptySet
}
// Remove all transactions that have been confirmed in the transaction set.
err := tp.db.Update(func(tx *bolt.Tx) error {
oldTS := ts
ts = []types.Transaction{}
for _, txn := range oldTS {
if !tp.transactionConfirmed(tx, txn.ID()) {
ts = append(ts, txn)
}
}
return nil
})
if err != nil {
return err
}
// If no transactions remain, return a dublicate error.
if len(ts) == 0 {
return modules.ErrDuplicateTransactionSet
}
// Check the composition of the transaction set, including fees and
// IsStandard rules.
err = tp.checkTransactionSetComposition(ts)
if err != nil {
return err
}
// Check for conflicts with other transactions, which would indicate a
// double-spend. Legal children of a transaction set will also trigger the
// conflict-detector.
oids := relatedObjectIDs(ts)
var conflicts []TransactionSetID
for _, oid := range oids {
conflict, exists := tp.knownObjects[oid]
if exists {
conflicts = append(conflicts, conflict)
}
}
if len(conflicts) > 0 {
return tp.handleConflicts(ts, conflicts)
}
cc, err := tp.consensusSet.TryTransactionSet(ts)
if err != nil {
return modules.NewConsensusConflict(err.Error())
}
// Add the transaction set to the pool.
setID := TransactionSetID(crypto.HashObject(ts))
tp.transactionSets[setID] = ts
for _, oid := range oids {
tp.knownObjects[oid] = setID
}
tp.transactionSetDiffs[setID] = cc
tp.transactionListSize += len(encoding.Marshal(ts))
return nil
}
示例6: TestDeleteNonexistentSector
// TestDeleteNonexistentSector checks that attempting to delete a storage
// sector that doesn't exist will fail with the appropriate error.
func TestDeleteNonexistentSector(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
st, err := createServerTester("TestDeleteNonexistentSector")
if err != nil {
t.Fatal(err)
}
defer st.server.Close()
// These calls to delete imaginary sectors should fail for a few reasons:
// - the given sector root strings are invalid
// - the renter hasn't uploaded anything
// - the host has no storage folders yet
// Right now, the calls fail for the first reason. This test will report if that behavior changes.
badHash := crypto.HashObject("fake object").String()
err = st.stdPostAPI("/host/storage/sectors/delete/"+badHash, url.Values{})
if err == nil || err.Error() != storagemanager.ErrSectorNotFound.Error() {
t.Fatalf("expected error to be %v; got %v", storagemanager.ErrSectorNotFound, err)
}
wrongSize := "wrong size string"
err = st.stdPostAPI("/host/storage/sectors/delete/"+wrongSize, url.Values{})
if err == nil || err.Error() != crypto.ErrHashWrongLen.Error() {
t.Fatalf("expected error to be %v; got %v", crypto.ErrHashWrongLen, err)
}
}
示例7: repeatCheckHelper
// repeatCheckHelper recursively goes through nodes in the host map and adds
// them to the repeat maps.
func (hn *hostNode) repeatCheckHelper(ipMap, pkMap map[string]struct{}) error {
ipStr := string(hn.hostEntry.NetAddress)
pkStr := crypto.HashObject(hn.hostEntry.PublicKey).String()
_, exists := ipMap[ipStr]
if exists && hn.taken {
return errors.New("found a duplicate ip address in the hostdb: " + ipStr)
}
_, exists = pkMap[pkStr]
if exists && hn.taken {
return errors.New("found a duplicate pubkey in the hostdb: " + ipStr + " " + pkStr)
}
if hn.taken {
ipMap[ipStr] = struct{}{}
pkMap[pkStr] = struct{}{}
}
if hn.left != nil {
err := hn.left.repeatCheckHelper(ipMap, pkMap)
if err != nil {
return err
}
}
if hn.right != nil {
err := hn.right.repeatCheckHelper(ipMap, pkMap)
if err != nil {
return err
}
}
return nil
}
示例8: GetHashInfo
// GetHashInfo returns sufficient data about the hash that was
// provided to do more extensive lookups
func (e *Explorer) GetHashInfo(hash []byte) (interface{}, error) {
if len(hash) < crypto.HashSize {
return nil, errors.New("requested hash not long enough")
}
lockID := e.mu.RLock()
defer e.mu.RUnlock(lockID)
// Perform a lookup to tell which type of hash it is
typeBytes, err := e.db.GetFromBucket("Hashes", hash[:crypto.HashSize])
if err != nil {
return nil, err
}
var hashType int
err = encoding.Unmarshal(typeBytes, &hashType)
if err != nil {
return nil, err
}
switch hashType {
case hashBlock:
var id types.BlockID
copy(id[:], hash[:])
return e.db.getBlock(types.BlockID(id))
case hashTransaction:
var id crypto.Hash
copy(id[:], hash[:])
return e.db.getTransaction(id)
case hashFilecontract:
var id types.FileContractID
copy(id[:], hash[:])
return e.db.getFileContract(id)
case hashCoinOutputID:
var id types.SiacoinOutputID
copy(id[:], hash[:])
return e.db.getSiacoinOutput(id)
case hashFundOutputID:
var id types.SiafundOutputID
copy(id[:], hash[:])
return e.db.getSiafundOutput(id)
case hashUnlockHash:
// Check that the address is valid before doing a lookup
if len(hash) != crypto.HashSize+types.UnlockHashChecksumSize {
return nil, errors.New("address does not have a valid checksum")
}
var id types.UnlockHash
copy(id[:], hash[:crypto.HashSize])
uhChecksum := crypto.HashObject(id)
givenChecksum := hash[crypto.HashSize : crypto.HashSize+types.UnlockHashChecksumSize]
if !bytes.Equal(givenChecksum, uhChecksum[:types.UnlockHashChecksumSize]) {
return nil, errors.New("address does not have a valid checksum")
}
return e.db.getAddressTransactions(id)
default:
return nil, errors.New("bad hash type")
}
}
示例9: checkTransactionSetComposition
// checkTransactionSetComposition checks if the transaction set is valid given
// the state of the pool. It does not check that each individual transaction
// would be legal in the next block, but does check things like miner fees and
// IsStandard.
func (tp *TransactionPool) checkTransactionSetComposition(ts []types.Transaction) error {
// Check that the transaction set is not already known.
setID := TransactionSetID(crypto.HashObject(ts))
_, exists := tp.transactionSets[setID]
if exists {
return modules.ErrDuplicateTransactionSet
}
// Check that the transaction set has enough fees to justify adding it to
// the transaction list.
err := tp.checkMinerFees(ts)
if err != nil {
return err
}
// All checks after this are expensive.
//
// TODO: There is no DoS prevention mechanism in place to prevent repeated
// expensive verifications of invalid transactions that are created on the
// fly.
// Check that all transactions follow 'Standard.md' guidelines.
err = tp.IsStandardTransactionSet(ts)
if err != nil {
return err
}
return nil
}
示例10: DecodeAnnouncement
// DecodeAnnouncement decodes announcement bytes into a host announcement,
// verifying the prefix and the signature.
func DecodeAnnouncement(fullAnnouncement []byte) (na NetAddress, spk types.SiaPublicKey, err error) {
// Read the first part of the announcement to get the intended host
// announcement.
var ha HostAnnouncement
dec := encoding.NewDecoder(bytes.NewReader(fullAnnouncement))
err = dec.Decode(&ha)
if err != nil {
return "", types.SiaPublicKey{}, err
}
// Check that the announcement was registered as a host announcement.
if ha.Specifier != PrefixHostAnnouncement {
return "", types.SiaPublicKey{}, ErrAnnNotAnnouncement
}
// Check that the public key is a recognized type of public key.
if ha.PublicKey.Algorithm != types.SignatureEd25519 {
return "", types.SiaPublicKey{}, ErrAnnUnrecognizedSignature
}
// Read the signature out of the reader.
var sig crypto.Signature
err = dec.Decode(&sig)
if err != nil {
return "", types.SiaPublicKey{}, err
}
// Verify the signature.
var pk crypto.PublicKey
copy(pk[:], ha.PublicKey.Key)
annHash := crypto.HashObject(ha)
err = crypto.VerifyHash(annHash, pk, sig)
if err != nil {
return "", types.SiaPublicKey{}, err
}
return ha.NetAddress, ha.PublicKey, nil
}
示例11: SeedToString
// SeedToString converts a wallet seed to a human friendly string.
func SeedToString(seed Seed, did mnemonics.DictionaryID) (string, error) {
fullChecksum := crypto.HashObject(seed)
checksumSeed := append(seed[:], fullChecksum[:SeedChecksumSize]...)
phrase, err := mnemonics.ToPhrase(checksumSeed, did)
if err != nil {
return "", err
}
return phrase.String(), nil
}
示例12: TestIntegrationBlocksMined
// TestIntegrationBlocksMined checks that the BlocksMined function correctly
// indicates the number of real blocks and stale blocks that have been mined.
func TestIntegrationBlocksMined(t *testing.T) {
mt, err := createMinerTester("TestIntegrationBlocksMined")
if err != nil {
t.Fatal(err)
}
// Get an unsolved header.
unsolvedHeader, target, err := mt.miner.HeaderForWork()
if err != nil {
t.Fatal(err)
}
// Unsolve the header.
for {
unsolvedHeader.Nonce[0]++
id := crypto.HashObject(unsolvedHeader)
if bytes.Compare(target[:], id[:]) < 0 {
break
}
}
// Get two solved headers.
header1, target, err := mt.miner.HeaderForWork()
if err != nil {
t.Fatal(err)
}
header1 = solveHeader(header1, target)
header2, target, err := mt.miner.HeaderForWork()
if err != nil {
t.Fatal(err)
}
header2 = solveHeader(header2, target)
// Submit the unsolved header followed by the two solved headers, this
// should result in 1 real block mined and 1 stale block mined.
err = mt.miner.SubmitHeader(unsolvedHeader)
if err != modules.ErrBlockUnsolved {
t.Fatal(err)
}
err = mt.miner.SubmitHeader(header1)
if err != nil {
t.Fatal(err)
}
err = mt.miner.SubmitHeader(header2)
if err != modules.ErrNonExtendingBlock {
t.Fatal(err)
}
goodBlocks, staleBlocks := mt.miner.BlocksMined()
if goodBlocks != 1 {
t.Error("expexting 1 good block")
}
if staleBlocks != 1 {
t.Error(len(mt.miner.blocksFound))
t.Error("expecting 1 stale block, got", staleBlocks)
}
}
示例13: solveHeader
// solveHeader takes a block header as input and returns a solved block header
// as output.
func solveHeader(header types.BlockHeader, target types.Target) types.BlockHeader {
// Solve the header.
for {
// Increment the nonce first to guarantee that a new header is formed
// - this helps check for pointer errors.
header.Nonce[0]++
id := crypto.HashObject(header)
if bytes.Compare(target[:], id[:]) >= 0 {
break
}
}
return header
}
示例14: SubmitHeader
// SubmitHeader accepts a block header.
func (m *Miner) SubmitHeader(bh types.BlockHeader) error {
if err := m.tg.Add(); err != nil {
return err
}
defer m.tg.Done()
// Because a call to managedSubmitBlock is required at the end of this
// function, the first part needs to be wrapped in an anonymous function
// for lock safety.
var b types.Block
err := func() error {
m.mu.Lock()
defer m.mu.Unlock()
// Lookup the block that corresponds to the provided header.
nonce := bh.Nonce
bh.Nonce = [8]byte{}
bPointer, bExists := m.blockMem[bh]
arbData, arbExists := m.arbDataMem[bh]
if !bExists || !arbExists {
return errLateHeader
}
// Block is going to be passed to external memory, but the memory pointed
// to by the transactions slice is still being modified - needs to be
// copied. Same with the memory being pointed to by the arb data slice.
b = *bPointer
txns := make([]types.Transaction, len(b.Transactions))
copy(txns, b.Transactions)
b.Transactions = txns
b.Transactions[0].ArbitraryData = [][]byte{arbData[:]}
b.Nonce = nonce
// Sanity check - block should have same id as header.
bh.Nonce = nonce
if types.BlockID(crypto.HashObject(bh)) != b.ID() {
m.log.Critical("block reconstruction failed")
}
return nil
}()
if err != nil {
m.log.Println("ERROR during call to SubmitHeader, pre SubmitBlock:", err)
return err
}
err = m.managedSubmitBlock(b)
if err != nil {
m.log.Println("ERROR returned by managedSubmitBlock:", err)
return err
}
return nil
}
示例15: StringToSeed
// StringToSeed converts a string to a wallet seed.
func StringToSeed(str string, did mnemonics.DictionaryID) (Seed, error) {
// Decode the string into the checksummed byte slice.
checksumSeedBytes, err := mnemonics.FromString(str, did)
if err != nil {
return Seed{}, err
}
// Copy the seed from the checksummed slice.
var seed Seed
copy(seed[:], checksumSeedBytes)
fullChecksum := crypto.HashObject(seed)
if len(checksumSeedBytes) != crypto.EntropySize+SeedChecksumSize || !bytes.Equal(fullChecksum[:SeedChecksumSize], checksumSeedBytes[crypto.EntropySize:]) {
return Seed{}, errors.New("seed failed checksum verification")
}
return seed, nil
}