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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
|
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package client verifies responses from the Trillian log.
package client
import (
"bytes"
"context"
"fmt"
"sort"
"sync"
"time"
"github.com/google/trillian"
"github.com/google/trillian/client/backoff"
"github.com/google/trillian/types"
"github.com/transparency-dev/merkle"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// LogClient represents a client for a given Trillian log instance.
type LogClient struct {
*LogVerifier
LogID int64
MinMergeDelay time.Duration
client trillian.TrillianLogClient
root types.LogRootV1
rootLock sync.Mutex
updateLock sync.Mutex
}
// New returns a new LogClient.
func New(logID int64, client trillian.TrillianLogClient, verifier *LogVerifier, root types.LogRootV1) *LogClient {
return &LogClient{
LogVerifier: verifier,
LogID: logID,
client: client,
root: root,
}
}
// NewFromTree creates a new LogClient given a tree config.
func NewFromTree(client trillian.TrillianLogClient, config *trillian.Tree, root types.LogRootV1) (*LogClient, error) {
verifier, err := NewLogVerifierFromTree(config)
if err != nil {
return nil, err
}
return New(config.GetTreeId(), client, verifier, root), nil
}
// AddLeaf adds leaf to the append only log.
// Blocks and continuously updates the trusted root until a successful inclusion proof
// can be retrieved.
func (c *LogClient) AddLeaf(ctx context.Context, data []byte) error {
if err := c.QueueLeaf(ctx, data); err != nil {
return fmt.Errorf("QueueLeaf(): %v", err)
}
if err := c.WaitForInclusion(ctx, data); err != nil {
return fmt.Errorf("WaitForInclusion(): %v", err)
}
return nil
}
// ListByIndex returns the requested leaves by index.
func (c *LogClient) ListByIndex(ctx context.Context, start, count int64) ([]*trillian.LogLeaf, error) {
resp, err := c.client.GetLeavesByRange(ctx,
&trillian.GetLeavesByRangeRequest{
LogId: c.LogID,
StartIndex: start,
Count: count,
})
if err != nil {
return nil, err
}
// Verify that we got back the requested leaves.
if len(resp.Leaves) < int(count) {
return nil, fmt.Errorf("len(Leaves)=%d, want %d", len(resp.Leaves), count)
}
for i, l := range resp.Leaves {
if want := start + int64(i); l.LeafIndex != want {
return nil, fmt.Errorf("Leaves[%d].LeafIndex=%d, want %d", i, l.LeafIndex, want)
}
}
return resp.Leaves, nil
}
// WaitForRootUpdate repeatedly fetches the latest root until there is an
// update, which it then applies, or until ctx times out.
func (c *LogClient) WaitForRootUpdate(ctx context.Context) (*types.LogRootV1, error) {
b := &backoff.Backoff{
Min: 100 * time.Millisecond,
Max: 10 * time.Second,
Factor: 2,
Jitter: true,
}
for {
newTrusted, err := c.UpdateRoot(ctx)
switch status.Code(err) {
case codes.OK:
if newTrusted != nil {
return newTrusted, nil
}
case codes.Unavailable, codes.NotFound, codes.FailedPrecondition:
// Retry.
default:
return nil, err
}
select {
case <-ctx.Done():
return nil, status.Errorf(codes.DeadlineExceeded, "%v", ctx.Err())
case <-time.After(b.Duration()):
}
}
}
// getAndVerifyLatestRoot fetches and verifies the latest root against a trusted root, seen in the past.
// Pass nil for trusted if this is the first time querying this log.
func (c *LogClient) getAndVerifyLatestRoot(ctx context.Context, trusted *types.LogRootV1) (*types.LogRootV1, error) {
resp, err := c.client.GetLatestSignedLogRoot(ctx,
&trillian.GetLatestSignedLogRootRequest{
LogId: c.LogID,
FirstTreeSize: int64(trusted.TreeSize),
})
if err != nil {
return nil, err
}
// TODO(gbelvin): Turn on root verification.
/*
logRoot, err := c.VerifyRoot(&types.LogRootV1{}, resp.GetSignedLogRoot(), nil)
if err != nil {
return nil, err
}
*/
// TODO(gbelvin): Remove this hack when all implementations store digital signatures.
var logRoot types.LogRootV1
if err := logRoot.UnmarshalBinary(resp.GetSignedLogRoot().LogRoot); err != nil {
return nil, err
}
if trusted.TreeSize > 0 &&
logRoot.TreeSize == trusted.TreeSize &&
bytes.Equal(logRoot.RootHash, trusted.RootHash) {
// Tree has not been updated.
return &logRoot, nil
}
// Verify root update if the tree / the latest signed log root isn't empty.
if logRoot.TreeSize > 0 {
if _, err := c.VerifyRoot(trusted, resp.GetSignedLogRoot(), resp.GetProof().GetHashes()); err != nil {
return nil, err
}
}
return &logRoot, nil
}
// GetRoot returns a copy of the latest trusted root.
func (c *LogClient) GetRoot() *types.LogRootV1 {
c.rootLock.Lock()
defer c.rootLock.Unlock()
// Copy the internal trusted root in order to prevent clients from modifying it.
ret := c.root
return &ret
}
// UpdateRoot retrieves the current SignedLogRoot, verifying it against roots this client has
// seen in the past, and updating the currently trusted root if the new root verifies, and is
// newer than the currently trusted root.
func (c *LogClient) UpdateRoot(ctx context.Context) (*types.LogRootV1, error) {
// Only one root update should be running at any point in time, because
// the update involves a consistency proof from the old value, and if the
// old value could change along the way (in another goroutine) then the
// result could be inconsistent.
//
// For example, if the current root is A and two root updates A->B and A->C
// happen in parallel, then we might end up with the transitions A->B->C:
// cur := A cur := A
// getRoot() => B getRoot() => C
// proof(A->B) ok proof(A->C) ok
// c.root = B
// c.root = C
// and the last step (B->C) has no proof and so could hide a forked tree.
c.updateLock.Lock()
defer c.updateLock.Unlock()
currentlyTrusted := c.GetRoot()
newTrusted, err := c.getAndVerifyLatestRoot(ctx, currentlyTrusted)
if err != nil {
return nil, err
}
// Lock "rootLock" for the "root" update.
c.rootLock.Lock()
defer c.rootLock.Unlock()
if newTrusted.TimestampNanos > currentlyTrusted.TimestampNanos &&
newTrusted.TreeSize >= currentlyTrusted.TreeSize {
// Take a copy of the new trusted root in order to prevent clients from modifying it.
c.root = *newTrusted
return newTrusted, nil
}
return nil, nil
}
// WaitForInclusion blocks until the requested data has been verified with an
// inclusion proof.
//
// It will continuously update the root to the latest one available until the
// data is found, or an error is returned.
//
// It is best to call this method with a context that will timeout to avoid
// waiting forever.
func (c *LogClient) WaitForInclusion(ctx context.Context, data []byte) error {
leaf := prepareLeaf(c.hasher, data)
// If a minimum merge delay has been configured, wait at least that long before
// starting to poll
if c.MinMergeDelay > 0 {
select {
case <-ctx.Done():
return status.Errorf(codes.DeadlineExceeded, "%v", ctx.Err())
case <-time.After(c.MinMergeDelay):
}
}
var root *types.LogRootV1
for {
root = c.GetRoot()
// It is illegal to ask for an inclusion proof with TreeSize = 0.
if root.TreeSize >= 1 {
ok, err := c.getAndVerifyInclusionProof(ctx, leaf.MerkleLeafHash, root)
if err != nil && status.Code(err) != codes.NotFound {
return err
} else if ok {
return nil
}
}
// If not found or tree is empty, wait for a root update before retrying again.
if _, err := c.WaitForRootUpdate(ctx); err != nil {
return err
}
// Retry
}
}
func (c *LogClient) getAndVerifyInclusionProof(ctx context.Context, leafHash []byte, sth *types.LogRootV1) (bool, error) {
resp, err := c.client.GetInclusionProofByHash(ctx,
&trillian.GetInclusionProofByHashRequest{
LogId: c.LogID,
LeafHash: leafHash,
TreeSize: int64(sth.TreeSize),
})
if err != nil {
return false, err
}
if len(resp.Proof) < 1 {
return false, nil
}
for _, proof := range resp.Proof {
if err := c.VerifyInclusionByHash(sth, leafHash, proof); err != nil {
return false, fmt.Errorf("VerifyInclusionByHash(): %v", err)
}
}
return true, nil
}
// AddSequencedLeaves adds any number of pre-sequenced leaves to the log.
// Indexes must be contiguous.
func (c *LogClient) AddSequencedLeaves(ctx context.Context, dataByIndex map[int64][]byte) error {
if len(dataByIndex) == 0 {
return nil
}
leaves := make([]*trillian.LogLeaf, 0, len(dataByIndex))
indexes := make([]int64, 0, len(dataByIndex))
for index := range dataByIndex {
indexes = append(indexes, index)
}
sort.Slice(indexes, func(a, b int) bool { return indexes[a] < indexes[b] })
for i, index := range indexes {
// Check index continuity.
if want := indexes[0] + int64(i); index != want {
return fmt.Errorf("missing index in contiugous index range. got: %v, want: %v", index, want)
}
leaf := prepareLeaf(c.hasher, dataByIndex[index])
leaf.LeafIndex = index
leaves = append(leaves, leaf)
}
resp, err := c.client.AddSequencedLeaves(ctx, &trillian.AddSequencedLeavesRequest{
LogId: c.LogID,
Leaves: leaves,
})
for _, leaf := range resp.GetResults() {
if s := status.FromProto(leaf.GetStatus()); s.Code() != codes.OK && s.Code() != codes.AlreadyExists {
return status.Errorf(s.Code(), "unexpected fail status in AddSequencedLeaves: %+v, err: %v", leaf, s.Message())
}
}
return err
}
// QueueLeaf adds a leaf to a Trillian log without blocking.
// AlreadyExists is considered a success case by this function.
func (c *LogClient) QueueLeaf(ctx context.Context, data []byte) error {
leaf := prepareLeaf(c.hasher, data)
_, err := c.client.QueueLeaf(ctx, &trillian.QueueLeafRequest{
LogId: c.LogID,
Leaf: leaf,
})
return err
}
// prepareLeaf returns a trillian.LogLeaf prepopulated with leaf data and hash.
func prepareLeaf(hasher merkle.LogHasher, data []byte) *trillian.LogLeaf {
leafHash := hasher.HashLeaf(data)
return &trillian.LogLeaf{
LeafValue: data,
MerkleLeafHash: leafHash,
}
}
|