demo_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package trillian
  2. import (
  3. "context"
  4. "github.com/davecgh/go-spew/spew"
  5. "github.com/google/trillian"
  6. "github.com/google/trillian/client"
  7. "github.com/google/trillian/merkle/rfc6962"
  8. tt "github.com/google/trillian/types"
  9. "github.com/sirupsen/logrus"
  10. "google.golang.org/grpc"
  11. "google.golang.org/protobuf/types/known/durationpb"
  12. "strconv"
  13. "testing"
  14. "time"
  15. )
  16. var admin_api_client trillian.TrillianAdminClient
  17. var logClient trillian.TrillianLogClient
  18. var ctx context.Context
  19. func TestMain(m *testing.M) {
  20. con, err := grpc.Dial("192.168.3.106:8090", grpc.WithInsecure())
  21. if err != nil {
  22. logrus.Error("consumer connect err:", err.Error())
  23. }
  24. admin_api_client = trillian.NewTrillianAdminClient(con)
  25. logClient = trillian.NewTrillianLogClient(con)
  26. ctx = context.Background()
  27. m.Run()
  28. }
  29. //单条插入
  30. func TestQueueLeafRequest(t *testing.T) {
  31. //1 创建基础树
  32. resp, err := admin_api_client.CreateTree(ctx, &trillian.CreateTreeRequest{
  33. Tree: &trillian.Tree{
  34. TreeState: trillian.TreeState_ACTIVE, //ACTIVE:正常状态 FROZEN:只读,禁止写入 DRAINING:继续构建排队的数据,不接受新数据
  35. TreeType: trillian.TreeType_LOG, // LOG:树表示可验证的日志,自动分配叶子索引序列号 PREORDERED_LOG:手动分配序列号
  36. DisplayName: time.Now().Format("2006-01-02 15:04:05"), //名称
  37. Description: "Description", //简介
  38. MaxRootDuration: durationpb.New(time.Hour), //一定时间没提交,也会产生新的签名根.如果为零,则禁用此行为
  39. },
  40. })
  41. if err != nil {
  42. logrus.Errorf("CreateTree:" + err.Error())
  43. return
  44. }
  45. //树id
  46. var logId = resp.TreeId
  47. //2 初始化树
  48. _, err = logClient.InitLog(ctx, &trillian.InitLogRequest{
  49. LogId: logId,
  50. //绑定多个指定外联id
  51. //ChargeTo: &trillian.ChargeTo{
  52. // User: []string{"id1","id2"},
  53. //},
  54. })
  55. if err != nil {
  56. logrus.Errorf("InitLog:" + err.Error())
  57. return
  58. }
  59. //3 加入叶子节点
  60. var data = "测试数据" + time.Now().String()
  61. _, err = logClient.QueueLeaf(ctx, &trillian.QueueLeafRequest{
  62. LogId: logId,
  63. Leaf: &trillian.LogLeaf{
  64. LeafValue: []byte(data),
  65. ExtraData: []byte("额外数据" + time.Now().String()),
  66. //LeafIdentityHash: //自定义hash 为空默认为交易hash
  67. },
  68. })
  69. if err != nil {
  70. logrus.Errorf("QueueLeaf:" + err.Error())
  71. return
  72. }
  73. time.Sleep(time.Second * 2) //延迟,树可能还没更新
  74. //4 交易验证
  75. //4.1 获取当前树TreeSize
  76. resLogRoot, err := logClient.GetLatestSignedLogRoot(ctx, &trillian.GetLatestSignedLogRootRequest{
  77. LogId: logId,
  78. })
  79. if err != nil {
  80. logrus.Errorf("GetLatestSignedLogRoot:" + err.Error())
  81. return
  82. }
  83. //4.2 解析根树数据
  84. var logRoot tt.LogRootV1
  85. if err := logRoot.UnmarshalBinary(resLogRoot.SignedLogRoot.LogRoot); err != nil {
  86. logrus.Errorf("UnmarshalBinary:" + err.Error())
  87. return
  88. }
  89. treeSize := logRoot.TreeSize
  90. //4.3 按交易hash获取默克尔树证明
  91. hash := rfc6962.DefaultHasher.HashLeaf([]byte(data))
  92. resInclusionByHash, err := logClient.GetInclusionProofByHash(ctx, &trillian.GetInclusionProofByHashRequest{
  93. LogId: logId,
  94. LeafHash: hash,
  95. TreeSize: int64(treeSize), //多实例服务器可能存在偏差,请求的 tree_size 大于服务器上可用的值,proof证明为空,会返回最新根数据
  96. })
  97. if err != nil {
  98. logrus.Errorf("GetInclusionProofByHash:" + err.Error())
  99. return
  100. }
  101. //4.4 验证交易有效性
  102. err = client.NewLogVerifier(rfc6962.DefaultHasher).VerifyInclusionByHash(&logRoot, hash, resInclusionByHash.Proof[0])
  103. if err != nil {
  104. logrus.Errorf("交易验证失败:" + err.Error())
  105. } else {
  106. logrus.Infof("验证成功")
  107. }
  108. }
  109. //批量插入
  110. func TestAddSequencedLeavesRequest(t *testing.T) {
  111. //1 创建基础树
  112. resp, err := admin_api_client.CreateTree(ctx, &trillian.CreateTreeRequest{
  113. Tree: &trillian.Tree{
  114. TreeState: trillian.TreeState_ACTIVE, //ACTIVE:正常状态 FROZEN:只读,禁止写入 DRAINING:继续构建排队的数据,不接受新数据
  115. TreeType: trillian.TreeType_PREORDERED_LOG, // LOG:树表示可验证的日志,自动分配叶子索引序列号 PREORDERED_LOG:手动分配序列号
  116. DisplayName: time.Now().Format("2006-01-02 15:04:05"), //名称
  117. Description: "Description", //简介
  118. MaxRootDuration: durationpb.New(time.Hour), //一定时间没提交,也会产生新的签名根.如果为零,则禁用此行为
  119. },
  120. })
  121. if err != nil {
  122. logrus.Errorf("CreateTree:" + err.Error())
  123. return
  124. }
  125. //树id
  126. var logId = resp.TreeId
  127. //2 初始化树3
  128. _, err = logClient.InitLog(ctx, &trillian.InitLogRequest{
  129. LogId: logId,
  130. //绑定多个指定外联id
  131. //ChargeTo: &trillian.ChargeTo{
  132. // User: []string{"id1","id2"},
  133. //},
  134. })
  135. if err != nil {
  136. logrus.Errorf("InitLog:" + err.Error())
  137. return
  138. }
  139. //3 批量添加数据
  140. var leaves []*trillian.LogLeaf
  141. //3.1 按序组装数据
  142. for i := 0; i < 2; i++ {
  143. leaves = append(leaves, &trillian.LogLeaf{
  144. LeafValue: []byte("data" + strconv.Itoa(i)),
  145. ExtraData: []byte("ok22"),
  146. LeafIndex: int64(i),
  147. })
  148. }
  149. //leaves = append(leaves, &trillian.LogLeaf{
  150. // LeafValue: []byte("data" + strconv.Itoa(0)),
  151. // ExtraData: []byte("ok22"),
  152. // LeafIndex: int64(0),
  153. //})
  154. //leaves = append(leaves, &trillian.LogLeaf{
  155. // LeafValue: []byte("data" + strconv.Itoa(1)),
  156. // ExtraData: []byte("ok22"),
  157. // LeafIndex: int64(1),
  158. //})
  159. //3.2 报错数据
  160. _, err = logClient.AddSequencedLeaves(context.Background(), &trillian.AddSequencedLeavesRequest{
  161. LogId: logId,
  162. Leaves: leaves,
  163. })
  164. if err != nil {
  165. logrus.Error("TestInitLogRequest connect err:", err.Error())
  166. }
  167. time.Sleep(time.Second * 2) //延迟,树可能还没更新
  168. //4 交易验证
  169. //4.1 获取当前树TreeSize
  170. resLogRoot, err := logClient.GetLatestSignedLogRoot(ctx, &trillian.GetLatestSignedLogRootRequest{
  171. LogId: logId,
  172. })
  173. if err != nil {
  174. logrus.Errorf("GetLatestSignedLogRoot:" + err.Error())
  175. return
  176. }
  177. //4.2 解析根树数据
  178. var logRoot tt.LogRootV1
  179. if err := logRoot.UnmarshalBinary(resLogRoot.SignedLogRoot.LogRoot); err != nil {
  180. logrus.Errorf("UnmarshalBinary:" + err.Error())
  181. return
  182. }
  183. treeSize := logRoot.TreeSize
  184. //4.3 按交易hash获取默克尔树证明
  185. var data = "data" + strconv.Itoa(0)//模拟交易数据
  186. hash := rfc6962.DefaultHasher.HashLeaf([]byte(data))
  187. resInclusionByHash, err := logClient.GetInclusionProofByHash(ctx, &trillian.GetInclusionProofByHashRequest{
  188. LogId: logId,
  189. LeafHash: hash,
  190. TreeSize: int64(treeSize), //多实例服务器可能存在偏差,请求的 tree_size 大于服务器上可用的值,proof证明为空,会返回最新根数据
  191. })
  192. if err != nil {
  193. logrus.Errorf("GetInclusionProofByHash:" + err.Error())
  194. return
  195. }
  196. //4.4 验证交易有效性
  197. err = client.NewLogVerifier(rfc6962.DefaultHasher).VerifyInclusionByHash(&logRoot, hash, resInclusionByHash.Proof[0])
  198. if err != nil {
  199. logrus.Errorf("交易验证失败:" + err.Error())
  200. } else {
  201. logrus.Infof("验证成功")
  202. }
  203. }
  204. func TestGetRange(t *testing.T) {
  205. res, err := logClient.GetLeavesByRange(ctx, &trillian.GetLeavesByRangeRequest{
  206. LogId: 4821037117312290399,
  207. StartIndex: 2,
  208. Count: 1,
  209. })
  210. if err != nil {
  211. logrus.Errorf("GetLeavesByRange:" + err.Error())
  212. }
  213. r, err := logClient.GetEntryAndProof(ctx, &trillian.GetEntryAndProofRequest{
  214. LogId: 4821037117312290399,
  215. LeafIndex: res.Leaves[0].LeafIndex,
  216. TreeSize: int64(13),
  217. })
  218. if err != nil {
  219. logrus.Errorf("GetLeavesByRange:" + err.Error())
  220. }
  221. spew.Dump(r)
  222. }