prysm-pulse/beacon-chain/db/attestation.go

73 lines
1.7 KiB
Go
Raw Normal View History

2018-10-05 17:14:50 +00:00
package db
import (
2018-10-17 06:11:24 +00:00
"fmt"
2018-10-05 17:14:50 +00:00
2018-10-17 06:11:24 +00:00
"github.com/boltdb/bolt"
2018-10-05 17:14:50 +00:00
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/prysm/beacon-chain/types"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
)
// SaveAttestation puts the attestation record into the beacon chain db.
func (db *BeaconDB) SaveAttestation(attestation *types.Attestation) error {
hash := attestation.Key()
encodedState, err := attestation.Marshal()
if err != nil {
return err
}
2018-10-17 06:11:24 +00:00
return db.update(func(tx *bolt.Tx) error {
a := tx.Bucket(attestationBucket)
2018-10-05 17:14:50 +00:00
2018-10-17 06:11:24 +00:00
return a.Put(hash[:], encodedState)
})
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
// GetAttestation retrieves an attestation record from the db using its hash.
func (db *BeaconDB) GetAttestation(hash [32]byte) (*types.Attestation, error) {
var attestation *types.Attestation
err := db.view(func(tx *bolt.Tx) error {
a := tx.Bucket(attestationBucket)
2018-10-05 17:14:50 +00:00
2018-10-17 06:11:24 +00:00
enc := a.Get(hash[:])
if enc == nil {
return nil
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
var err error
attestation, err = createAttestation(enc)
return err
})
2018-10-05 17:14:50 +00:00
2018-10-17 06:11:24 +00:00
return attestation, err
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
// HasAttestation checks if the attestation exists.
func (db *BeaconDB) HasAttestation(hash [32]byte) bool {
exists := false
// #nosec G104
2018-10-17 06:11:24 +00:00
db.view(func(tx *bolt.Tx) error {
a := tx.Bucket(attestationBucket)
2018-10-05 17:14:50 +00:00
2018-10-17 06:11:24 +00:00
exists = a.Get(hash[:]) != nil
return nil
})
return exists
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
func createAttestation(enc []byte) (*types.Attestation, error) {
protoAttestation := &pb.AggregatedAttestation{}
err := proto.Unmarshal(enc, protoAttestation)
2018-10-05 17:14:50 +00:00
if err != nil {
2018-10-17 06:11:24 +00:00
return nil, fmt.Errorf("failed to unmarshal encoding: %v", err)
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
attestation := types.NewAttestation(protoAttestation)
2018-10-05 17:14:50 +00:00
if err != nil {
2018-10-17 06:11:24 +00:00
return nil, fmt.Errorf("failed to instantiate a block from the encoding: %v", err)
2018-10-05 17:14:50 +00:00
}
2018-10-17 06:11:24 +00:00
return attestation, nil
2018-10-05 17:14:50 +00:00
}