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

66 lines
1.6 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"
att "github.com/prysmaticlabs/prysm/beacon-chain/core/attestations"
2018-10-05 17:14:50 +00:00
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
)
// SaveAttestation puts the attestation record into the beacon chain db.
func (db *BeaconDB) SaveAttestation(attestation *pb.Attestation) error {
hash := att.Key(attestation.Data)
encodedState, err := proto.Marshal(attestation)
2018-10-05 17:14:50 +00:00
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) (*pb.Attestation, error) {
var attestation *pb.Attestation
2018-10-17 06:11:24 +00:00
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
}
func createAttestation(enc []byte) (*pb.Attestation, error) {
protoAttestation := &pb.Attestation{}
if err := proto.Unmarshal(enc, protoAttestation); 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
}
return protoAttestation, nil
2018-10-05 17:14:50 +00:00
}