/
msg_anchor.go
109 lines (85 loc) · 2.69 KB
/
msg_anchor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
package server
import (
"context"
gogotypes "github.com/gogo/protobuf/types"
"cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/orm/types/ormerrors"
sdk "github.com/cosmos/cosmos-sdk/types"
api "github.com/regen-network/regen-ledger/api/v2/regen/data/v1"
"github.com/regen-network/regen-ledger/types/v2"
"github.com/regen-network/regen-ledger/x/data/v2"
)
type ToIRI interface {
ToIRI() (string, error)
}
// Anchor anchors a piece of data to the blockchain based on its secure hash.
func (s serverImpl) Anchor(ctx context.Context, request *data.MsgAnchor) (*data.MsgAnchorResponse, error) {
iri, _, timestamp, err := s.anchorAndGetIRI(ctx, request.ContentHash)
if err != nil {
return nil, err
}
return &data.MsgAnchorResponse{
Iri: iri,
Timestamp: timestamp,
}, nil
}
func (s serverImpl) anchorAndGetIRI(ctx context.Context, ch ToIRI) (iri string, id []byte, timestamp *gogotypes.Timestamp, err error) {
iri, err = ch.ToIRI()
if err != nil {
return "", nil, nil, err
}
id, err = s.getOrCreateDataID(ctx, iri)
if err != nil {
return "", nil, nil, err
}
timestamp, err = s.anchorAndGetTimestamp(ctx, id, iri)
if err != nil {
return "", nil, nil, err
}
return iri, id, timestamp, err
}
func (s serverImpl) getOrCreateDataID(ctx context.Context, iri string) (id []byte, err error) {
dataID := &api.DataID{Iri: ""}
for collisions := 0; dataID.Iri != iri; collisions++ {
id = s.iriHasher.CreateID([]byte(iri), collisions)
dataID, err = s.stateStore.DataIDTable().Get(ctx, id)
if err != nil {
if !ormerrors.IsNotFound(err) {
return nil, err
}
dataID = &api.DataID{
Id: id,
Iri: iri,
}
err = s.stateStore.DataIDTable().Insert(ctx, dataID)
if err != nil {
return nil, err
}
}
// consume additional gas whenever we create or verify the data ID
sdk.UnwrapSDKContext(ctx).GasMeter().ConsumeGas(data.GasCostPerIteration, "create/verify data id")
}
return id, nil
}
func (s serverImpl) anchorAndGetTimestamp(ctx context.Context, id []byte, iri string) (*gogotypes.Timestamp, error) {
dataAnchor, err := s.stateStore.DataAnchorTable().Get(ctx, id)
if err != nil {
if !ormerrors.IsNotFound(err) {
return nil, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
timestamp, err := gogotypes.TimestampProto(sdkCtx.BlockTime())
if err != nil {
return nil, errors.Wrap(err, "invalid block time")
}
err = s.stateStore.DataAnchorTable().Insert(ctx, &api.DataAnchor{
Id: id,
Timestamp: types.GogoToProtobufTimestamp(timestamp),
})
if err != nil {
return nil, err
}
return timestamp, sdkCtx.EventManager().EmitTypedEvent(&data.EventAnchor{Iri: iri})
}
return types.ProtobufToGogoTimestamp(dataAnchor.Timestamp), nil
}