第三新熵熱踢道場 (taichu-crypto)

注意 !工事進行中!

Github dltdojo/taichu-crypto: 道場線上練習環境建置專案

QR Code

k19.dltdojo.org

預計使用網址 https://k19.dltdojo.org 當示範網站,目前選定 Kubernetes on DigitalOcean :: DigitalOcean Product Documentation 環境來安裝。

TOC

上線需安裝服務

Forum 論壇

使用現有常見配置如 Forum - Kusama 是使用 discourse/discourse: A platform for community discussion. Free, open, simple.,缺點是使用者配置有兩套,直接掛鏈上的用可以參考 Joystream/substrate-forum-module: An on-chain forum.,只是掛鏈缺點是小眾,不像泛用型論壇軟體 discourse 的 UI 現成美美的,手機板也不用自己來寫。

TODO

  • 測試一個月以及最後費用說明
  • 所需安裝服務與指引

POC 概念驗證

道場專案預期做個分散式帳本技術的練習場所,第一次嘗試於 16 年使用 ssh 連線遠端 ubuntu 機器操作指令模式(下稱 SSH-ONLY),不過界面不易入門學習曲線太高,後來加入 Visual Studio Code@Windows 掛 samba-file-server@ubuntu 來編輯,執行指令還是用 ssh 連接機器模式(下稱 SSH-SMB),由於 IDE 支援 SSH-SMB 學習效率有所增加,不過設定使用方式需要雙協定還是太複雜,隨著 code-server 專案的逐漸成熟,道場練習場設置改為 HTTP-ONLY 模式,學習端只用瀏覽器,不須下載其他軟體安裝或是開啟其他連線工具即可開始進行學習活動。

  • SSH-ONLY, SSH-SMB, HTTP-ONLY
  • https://code.visualstudio.com/
  • https://github.com/cdr/code-server

TAICHU RAW

DLTDOJO3 安裝執行軟體專案

MAD WHITE

以 Visual Studio Code Server 為主的學習軟體概念驗證

MAD RED

以 Veloren 體素遊戲為主的學習軟體概念驗證

UML 圖

DLTDOJO1-2 序列圖

DLTDOJO3 序列圖

DLTDOHJO3 組件圖

  • CS cdr/code-server: Run VS Code on a remote server. https://github.com/cdr/code-server
  • K8S ubuntu/microk8s: A kubernetes cluster in a snap https://github.com/ubuntu/microk8s

每次活動開啟 VM 建置 microk8s 環境,配置每個練習者一個 CS 環境取得密碼與對外連線 URL,練習者瀏覽器登入後執行練習任務。

VM 環境與預算

估算基礎單次練習約五人兩小時。

Digital Ocean

MEMORY  VCPUS   SSD DISK    TRANSFER  PRICE
64GB    16      1,280 GB    9TB	      $0.476/hr

體驗

Web 1.0

  • apache http server
  • html
  • build
  • test
  • deploy

Web 2.0

  • JavaScript
  • ajax

Web 3.0

  • blockchain
  • hyperledger
  • bitcoin
  • ethereum

Artifact

一九八四 再生金鑰書 2015

2016年中秋後開 DLTDOJO 道場專案前曾有過一次「2+2=5」的小型比特幣科幻出版物實驗性專案,當時二手市場容易找到 1984 年出版的一九八四約十幾本,請幾個朋友測試後變成回憶。

1984 front

1984 back

暗黑通信團書鑰 2019

得到

  • 「素数表150000個」 書一本,內有公私鑰,背道場貼紙。
  • 「円周率0x100000桁表」 書一本,內有公私鑰,背道場貼紙。
  • 公鑰地址上有一杯咖啡等值虛擬通貨。

書源

Amazon.co.jp

出版關鍵字

  • 真実のみを記述する会
  • 暗黒通信団
  • 円周率0x100000桁表
  • 素数表150000個

參考資源

商業委託 - 著作財產權歸出資人

DLTDOJO是個開放原始碼專案,出版書鑰或是作品需要數位媒材需要對外作商業委託,採用 智慧財產局著作權主題網-使用與授權-契約範本-文創產業著作權相關契約範本及使用說明 之出資聘人完成著作契約-著作財產權歸出資人合約範本,範本內條款異動部份主要是甲方作品集不須乙方同意以及確認草稿後全額付款,全部異動說明如下。

  • 第三條 甲方同意於民國○○年○○月○○日前完成全部工作並交付乙方進行驗收。預設三個月。
  • 第五條 雙方同意,本著作之首次公開發表由乙方為之。乙方於公開發表及利用本著作時,就著作人之標示,以甲方指定之名稱○○○標示為本著作之著作人。
  • 第七條 甲方如擬將本著作收錄於其個人之作品集對外發表或發行,不須乙方之同意。
  • 第八條 甲方應依本契約第三條所定期限將本著作交付乙方進行驗收。乙方應於甲方依約繳交本著作後之 10 日內通知甲方其驗收結果。
  • 第十二條 甲方完成本著作草稿並交付乙方確認後,乙方應支付甲方新台幣○○元之報酬。
  • 第十八條 因本契約所生爭執,雙方同意本於誠信原則協商解決;若無法協商而涉訟,將以台灣臺中地方法院為第一審管轄法院,並以中華民國法律為準據法。

POC TAICHU-RAW

如何編譯

參考安裝 Rust說明將 rust 環境安裝好。該專案目錄為 rust/taichu-raw

cd rust/taichu-raw
cargo run -- -h

TODO

201909

Apache Big5

一個 HTTP/HTML 網路的買賣故事

img

Index of TAICHU-RAW

Apache Big5

HTML 表裡

index.html of taichu-raw 為執行 taichu-raw 的預設首頁,上圖塗黑為示範效果。

Apahce Big5 Html Sources

HTML 原

.big5

httpd-1.3.x/htdocs/index.html.zh-tw.big5

html

httpd-1.3.x/htdocs/index.html.zh-tw.big5

HTTP

$ cd taichu-crypto (master)
$ curl -vk https://127.0.0.1:8443

curl-vk.txt 為 curl 對 taichu-raw 做 HTTP 通訊的往來紀錄,裡面有大量 HTML 容易引起 mdbook 錯誤解析,請開啟另外網頁查看。

> GET / HTTP/2
> Host: 127.0.0.1:8443
> User-Agent: curl/7.57.0
> Accept: */*
>

< HTTP/2 200 
< content-length: 5256
< date: Sat, 31 Aug 2019 04:40:02 GMT
< 
HTML BODY....

差異

  • big5
  • HTML5
  • HTTP/2
  • TLSv1.2

PlantUML code

@startuml
header DLTDOJO3
footer https://dltdojo.github.io/taichu-crypto/\nLicensed under the Apache License Version 2.0
title dltdojo3-seq-http
legend top
一個 HTTP/HTML 網路的買賣故事
endlegend
skinparam handwritten true
actor "消費者" as Alice #red
participant "Browser\n瀏覽器"  as Browser
collections "HTTP Server\n超文本傳輸協定服務" as HTTPD
actor "生產者" as Bob #yellow
== 寫 HTML ==
autonumber 101
Bob -> HTTPD : 上傳寫作檔 HTML
note left
<img:../images/apache-big5-html-src.png{scale=0.5}>
end note
== 要 HTTP REQUEST ==
autonumber 201
Alice -> Browser : "要求 http://127.0.0.1/"
Browser -> HTTPD : "要求 HTML 檔案\nGET / HTTP/1.1"
== 給 HTTP RESPONSE ==
autonumber 301
HTTPD -> Browser : "回傳 HTML 檔案\nHTTP/1.1 200 OK\n...."  
note left
<img:../images/apache-big5-html-src.png{scale=0.5}>
end note  
Browser -> Alice : browser  
note right
<img:../images/apache-big5.png{scale=0.5}>
end note
== 免費 ? 白吃的午餐 ? 注意力與隱私商品化 ==
Alice -> Bob : :-)  
Bob -> Alice : $$$  
@enduml

OpenAPI v3

OpenAPI v3 Petstore

$ curl -kd '{"name":"dltdojo", "number":3}' -H "Content-Type: application/json" -X POST https://localhost:8443/echo
{"name":"dltdojo","number":3}

spec yaml

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore (測試用)
  license:
    name: MIT
servers:
  - url: https://127.0.0.1:8443/api/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:    
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
components:
  schemas:
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string

HTTPS 服務型態

Prometheus Support

actix-web-prom

$ taichu-raw -s
$ curl -k https://127.0.0.1:8443/metrics
# HELP api_http_requests_duration_seconds HTTP request duration in seconds for all requests   
# TYPE api_http_requests_duration_seconds histogram
api_http_requests_duration_seconds_bucket{endpoint="/",method="GET",status="200",le="0.005"} 8
api_http_requests_duration_seconds_bucket{endpoint="/",method="GET",status="200",le="0.01"} 8 
api_http_requests_duration_seconds_bucket{endpoint="/",method="GET",status="200",le="0.025"} 8
api_http_requests_duration_seconds_bucket{endpoint="/",method="GET",status="200",le="0.05"} 8 
api_http_requests_duration_seconds_bucket{endpoint="/",method="GET",status="200",le="0.1"} 8  
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="0.1"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="0.25"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="0.5"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="1"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="2.5"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="5"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="10"} 8
api_http_requests_duration_seconds_bucket{endpoint="/favicon.ico",method="GET",status="200",le="+Inf"} 8
api_http_requests_duration_seconds_sum{endpoint="/favicon.ico",method="GET",status="200"} 0.0209961
api_http_requests_duration_seconds_count{endpoint="/favicon.ico",method="GET",status="200"} 8
# HELP api_http_requests_total Total number of HTTP requests
# TYPE api_http_requests_total counter
api_http_requests_total{endpoint="/",method="GET",status="200"} 8
api_http_requests_total{endpoint="/favicon.ico",method="GET",status="200"} 8

CLI 命令列型態

生成臨時性 TLS 憑證與金鑰

基於 rcgen 功能生成金鑰與憑證。

$ taichu-raw -c
-----BEGIN CERTIFICATE-----
MIIBZTCCAQygAwIBAgIBKjAKBggqhkjOPQQDAjAhMR8wHQYDVQQDDBZyY2dlbiBz
ZWxmIHNpZ25lZCBjZXJ0MCIYDzE5NzUwMTAxMDAwMDAwWhgPNDA5NjAxMDEwMDAw
MDBaMCExHzAdBgNVBAMMFnJjZ2VuIHNlbGYgc2lnbmVkIGNlcnQwWTATBgcqhkjO
PQIBBggqhkjOPQMBBwNCAARBkJ9KK6fQthT5Q8ZA9m/eSt1ZcAB2ArDVk9yTMe2w
nxx5BneFOtchlHu2ZF3KanOhlQi2jI7aQ/7Tw2rkmar3ozEwLzAtBgNVHREEJjAk
ghd0YWljaHUtcmF3LWRldjMxMC5sb2NhbIIJbG9jYWxob3N0MAoGCCqGSM49BAMC
A0cAMEQCIHwJaFKRyCTRH2SH53ZgOmiqQdz6ktNHDBDh2zceY3EOAiB8iQX0Puu7
hFQS1/4vwj/M2xMOwlmSTTcgaMYA2zlAJA==
-----END CERTIFICATE-----

-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgaecm/rfSsuxMgOug
nVXwu4/kA0Gn4Nm1HAeuVlpV7AWhRANCAARBkJ9KK6fQthT5Q8ZA9m/eSt1ZcAB2
ArDVk9yTMe2wnxx5BneFOtchlHu2ZF3KanOhlQi2jI7aQ/7Tw2rkmar3
-----END PRIVATE KEY-----

RCRPG - Rosetta Code

互動遊戲功能與規則:

  • 房間座標軸 room-based navigation in three integer dimensions (x,y,z)
  • 置物箱 player inventory
  • 錘梯金三種物件 three types of item: sledge, gold and ladder
  • 任務座標 a goal coordinate

通道用錘打開,有梯在地非手持才能爬上層房間,金無用。

TODO

  • 中英文對照
  • 加虛擬通貨錢包(BIP39/Keys)配置
  • 加學習路線
$ cargo run

Grab the sledge and make your way to room 1,1,5 for a non-existant prize!

You need a sledge to dig rooms and ladders to go upwards.
Valid commands are: directions (north, south...), dig, take, drop, equip, inventory and look.
Additionally you can tag rooms with the 'name' command and alias commands with 'alias'.      
Have fun!
look
The room where it all started... On the floor you can see: a sledge, a ladder. There are no exits in this room.
north
There's no exit in that direction!
dig north
With your bare hands?
equip sledge
Item equipped
dig north
There is now an exit northward
north
Room at (0, -1, 0). On the floor you can see: a sledge. There is one exit: south.

Rosetta Code 範例程式碼轉入本案的 Apache License 授權問題,該網站寫到授權為 GFDL

Content is available under GNU Free Documentation License 1.2 unless otherwise noted.

引用GNU自由文檔許可證說明

GNU自由檔案授權條款與GNU通用公眾授權條款(GPL)雙向不相容,導致範例程式碼必須雙重授權才能既使用在檔案又使用在程式內。這點受到批評。

重製範例碼改作放在 Apache License 授權專案可能有爭議,這裡改作置入當成程式碼著作權說明案例。

MAD WHITE

MAD WHITE 目的為試驗使用 cdr/code-server 專案的 codercom/code-server image 為基底做出區塊鏈學習環境建置用 image ,目標是學習端不需安裝除了瀏覽器之外的軟體,就能學習、驗證與撰寫各種線上教材的設計學習情境。

TOC

Getting Started

如何使用 docker image 啟動

Docker 標籤為 dltdojo/ddj3base:mad-white

  • https://hub.docker.com/r/dltdojo/ddj3base/tags
bash tc.sh --drun

or

docker run -it --rm -p 8443:8443 -v "${PWD}:/home/coder/project" \
  dltdojo/ddj3base:mad-white --allow-http --no-auth 

Dockerfile 繼承自 codercom/code-server 再加上練習所需工具。

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=1.1156-vsc1.33.1
FROM codercom/code-server:${CS_VER}
USER root
# NOTE: upgrade all packages for kaniko build
# Must remove all files in /var/lib/apt/lists to avoid caching mechanism
RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get update && apt-get upgrade -y
RUN apt-get install -y git tree jq software-properties-common curl gpg-agent cowsay openssl
RUN add-apt-repository ppa:rmescandon/yq && apt-get update && apt-get install -y yq
USER coder
RUN set -eux  && \
    code-server --install-extension cssho.vscode-svgviewer
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
COPY settings.json ${PATH_SETTINGS}
COPY trier.sh /usr/local/bin/trier
#  /usr/games/cowsay
ENV PATH /usr/games:$PATH
# /usr/games:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN sudo chown -R coder.coder /home/coder && \
    sudo chmod +x /usr/local/bin/trier && \
	echo '\nexport PATH="/usr/games:$PATH"' >> /home/coder/.bashrc
# WORKDIR is /home/coder/project
RUN trier --enable nodejs10
COPY dojos /home/coder/dojos
RUN pwd && tree /home/coder/dojos && \
    sudo chown -R coder.coder /home/coder
# TEST build
# TODO mktemp -d permission issue
# docker build -t foo .
# mkdir -p ~/test/foo
# docker run -it -p 8443:8443 -v "${HOME}/test/foo:/home/coder/project" foo --allow-http --no-auth

Kubernetes

bash mad-white.sh install|delete|info

WIP Steps

  • gogs must wait at least 3 mins
  • gogs url http://127.0.0.1:30521
  • register alice@gogs and create a new project
  • drone url http://127.0.0.1:30531
  • login drone with alice@gogs's password

WIP 圖說

組件圖

x

201909

VS Code Server

TOC

Code Server Docker

WIP: vscode-dltdojo3r1.vsix extension

vscode-dltdojo3-v191025.png

kubectl/helm/mdbook/vscode-yarm 191026 版 (707M)

  • add kubectl and helm to image
  • add mdbook and mdbook-toc to image
  • add redhat.vscode-yaml extension to image
  • bump codercom/code-server version 2.1638-vsc1.39.2
  • bump node version 10.17.0
  • bump yarn version 1.19.1
# https://hub.docker.com/r/codercom/code-server/tags
# codercom/code-server:2.1638-vsc1.39.2 b0873f48b93a 439MB
# 
# node/npm/yarn/kubectl/helm/mdbook/vscode-yaml (707M)
#
FROM node:10.17.0-buster AS node-buster
ARG CS_VER=2.1638-vsc1.39.2
FROM codercom/code-server:2.1638-vsc1.39.2
COPY --from=node-buster /usr/local/bin/node /usr/local/bin/node
COPY --from=node-buster /usr/local/lib/node_modules /usr/local/lib/node_modules
#
# copy yarn
#
ENV YARN_VERSION v1.19.1
COPY --from=node-buster /opt/yarn-$YARN_VERSION /opt/yarn-$YARN_VERSION
USER root
RUN ls -al /usr/local/bin && \
    ln -s /usr/local/bin/node /usr/local/bin/nodejs && \
    ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
    ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npx && \
    ls -al /opt && \
    ln -s /opt/yarn-$YARN_VERSION/bin/yarn /usr/local/bin/yarn && \
    ln -s /opt/yarn-$YARN_VERSION/bin/yarnpkg /usr/local/bin/yarnpkg && \
    node --version && yarn --version && npm version

#
# kubectl download 
# https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl-binary-with-curl-on-linux
# 
ENV KUBECTL_VERSION=v1.15.3
RUN curl -sLO https://storage.googleapis.com/kubernetes-release/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl && \
    chmod +x ./kubectl && mv ./kubectl /usr/local/bin/kubectl && kubectl version --client

#
# helm download 
# 
ENV HELM_VERSION=v2.14.3
RUN curl -sL https://storage.googleapis.com/kubernetes-helm/helm-${HELM_VERSION}-linux-amd64.tar.gz | tar -xvz && \
    mv linux-amd64/helm /usr/local/bin/ && rm -rf linux-amd64 && helm version --client

#
# mdbook download
#
ENV MDBOOK_VERSION=v0.3.1
RUN curl -sL https://github.com/rust-lang-nursery/mdBook/releases/download/${MDBOOK_VERSION}/mdbook-${MDBOOK_VERSION}-x86_64-unknown-linux-gnu.tar.gz | tar -xvz && \
    mv mdbook /usr/local/bin/ && mdbook --version
#
# mdbook-toc download
#
ENV MDBOOK_TOC_VERSION=0.2.2
RUN curl -sL https://github.com/badboy/mdbook-toc/releases/download/${MDBOOK_TOC_VERSION}/mdbook-toc-${MDBOOK_TOC_VERSION}-x86_64-unknown-linux-gnu.tar.gz | tar -xvz && \
    mv mdbook-toc /usr/local/bin/ && mdbook-toc --version

#
# redhat vscode yaml extension
#
RUN curl -sL https://github.com/redhat-developer/vscode-yaml/releases/download/0.5.2-beta/0.5.2-beta7.vsix \
    -o /usr/local/share/vscode-yaml.vsix

#
# Hyperledger Fabric Binaries
# [hyperledger/fabric-tools Tags - Docker Hub](https://hub.docker.com/r/hyperledger/fabric-tools/tags)
# [hyperledger/fabric-ca Tags - Docker Hub](https://hub.docker.com/r/hyperledger/fabric-ca/tags)
# [Commands Reference — hyperledger-fabricdocs master documentation](https://hyperledger-fabric.readthedocs.io/en/release-1.4/command_ref.html)
#
# COPY --from=docker.io/hyperledger/fabric-ca:1.4.3 /usr/local/bin/fabric-ca-client /usr/local/bin/
# COPY --from=docker.io/hyperledger/fabric-tools:1.4.3 /usr/local/bin/peer /usr/local/bin/
# COPY --from=docker.io/hyperledger/fabric-tools:1.4.3 /usr/local/bin/cryptogen /usr/local/bin/
# COPY --from=docker.io/hyperledger/fabric-tools:1.4.3 /usr/local/bin/configtxgen /usr/local/bin/
# COPY --from=docker.io/hyperledger/fabric-tools:1.4.3 /usr/local/bin/configtxlator /usr/local/bin/
# RUN fabric-ca-client version && cryptogen version && configtxgen -version && configtxlator version && peer version


USER coder
#
# npm global install witout root
# https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
#
RUN npm config set prefix=/home/coder/.npm-packages \
    && echo '\nexport PATH="/home/coder/.npm-packages/bin:$PATH"' >> /home/coder/.bashrc

RUN mkdir -p /home/coder/.local/share/code-server/User/
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

RUN set -eux  && \
    code-server --install-extension /usr/local/share/vscode-yaml.vsix

#
# curl https://dltdojo.github.io/taichu-crypto/dockerfiles/v191026/Dockerfile  | docker build -t foo -
# or download Dockerfile
# curl https://dltdojo.github.io/taichu-crypto/dockerfiles/v191026/Dockerfile -o Dockerfile
# docker build -t foo .
# docker run -it --rm -v $PWD:/home/coder/project -p 8080:8080 foo 
# http://localhost:8080/?folder=/home/coder/project/
#

Dockerfile

$ curl https://dltdojo.github.io/taichu-crypto/dockerfiles/v191026/Dockerfile -o Dockerfile
$ docker build -t foo .

# or docker build from STDIN

$ curl https://dltdojo.github.io/taichu-crypto/dockerfiles/v191026/Dockerfile  | docker build -t foo -
$ docker run -it --rm -v $PWD:/home/coder/project -p 8080:8080 foo 

info  Server listening on http://0.0.0.0:8080
info    - Password is 1c578b76fcd86e7e4a68e178
info      - To use your own password, set the PASSWORD environment variable
info      - To disable use `--auth none`
info    - Not serving HTTPS

kaniko job example

apiVersion: batch/v1
kind: Job
metadata:
  name: kanikojob
spec:
  completions: 1
  template:
    metadata:
      name: kanikojob
    spec:
      restartPolicy: Never
      initContainers:
      - name: init-context
        image: curlimages/curl:latest
        args:
            - -sL
            - https://dltdojo.github.io/taichu-crypto/dockerfiles/v191026/Dockerfile
            - -o
            - /context/Dockerfile
        volumeMounts:
        - name: context
          mountPath: /context
      containers:
      # 
      # Working with MicroK8s’ registry add-on
      # registry.container-registry.svc.cluster.local:5000
      # curl http://127.0.0.1:32000/v2/_catalog
      #
      - name: kaniko
        image: gcr.io/kaniko-project/executor:latest
        args: ["--dockerfile=/context/Dockerfile",
              "--context=/context",
              "--destination=registry.container-registry.svc.cluster.local:5000/dltdojo3/mad-white:v191026"]
        volumeMounts:
          - name: context
            mountPath: /context
      volumes:
        - name: context
          emptyDir: {}

Node/NPM/Yarn 版 (508M)

目前 codercom/code-server:v2 計 146.17 MB 為 FROM ubuntu:18.04 製作。node/yarn 直接複製用 COPY --from=node:10.16.3-buster 還是 COPY --from=node:10.16.3-jessie 看起來差不多都是取自 nodejs.org/dist/latest-v10.x/

$ docker run --rm -it node:10.16.3-buster ls -al /usr/local/bin
total 40192
drwxrwxr-x  2 root root     4096 Oct 18 01:46 .
drwxr-xr-x 20 root root     4096 Oct 18 01:46 ..
-rwxrwxr-x  1 root root      116 Oct 18 01:46 docker-entrypoint.sh
-rwxrwxr-x  1 root root 41142280 Aug 15 18:50 node
lrwxrwxrwx  1 root root       19 Oct 18 01:46 nodejs -> /usr/local/bin/node
lrwxrwxrwx  1 root root       38 Aug 15 18:51 npm -> ../lib/node_modules/npm/bin/npm-cli.js
lrwxrwxrwx  1 root root       38 Aug 15 18:51 npx -> ../lib/node_modules/npm/bin/npx-cli.js
lrwxrwxrwx  1 root root       26 Oct 18 01:46 yarn -> /opt/yarn-v1.17.3/bin/yarn
lrwxrwxrwx  1 root root       29 Oct 18 01:46 yarnpkg -> /opt/yarn-v1.17.3/bin/yarnpkg

Dockfile

# image size 508 MB (node/npm/yarn)
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=v2
FROM codercom/code-server:${CS_VER}
RUN ls -al /usr/local/bin
COPY --from=node:10.16.3-buster /usr/local/bin/node /usr/local/bin/node
# docker run --rm -it node:10.16.3-buster ls -al /usr/local/bin
# docker run --rm -it node:10.16.3-buster ls /usr/local/lib/node_modules/npm/lib
COPY --from=node:10.16.3-buster /usr/local/lib/node_modules /usr/local/lib/node_modules
COPY --from=node:10.16.3-buster /opt/yarn-v1.17.3 /opt/yarn-v1.17.3
USER root
RUN ln -s /usr/local/bin/node /usr/local/bin/nodejs && \
    ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
    ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npx && \
    ln -s /opt/yarn-v1.17.3/bin/yarn /usr/local/bin/yarn && \
    ln -s /opt/yarn-v1.17.3/bin/yarnpkg /usr/local/bin/yarnpkg && \
    ls -al /usr/local/bin && \
    node --version && yarn --version && npm version

USER coder
#
# npm global install witout root
# https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
#
RUN npm config set prefix=/home/coder/.npm-packages \
    && echo '\nexport PATH="/home/coder/.npm-packages/bin:$PATH"' >> /home/coder/.bashrc

RUN mkdir -p /home/coder/.local/share/code-server/User/
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

rust + webassembly 開發環境 v2

效果跟 wasdk/WebAssemblyStudio: Learn, Teach, Work and Play in the WebAssembly Studio 差不多,只是多出 bash, cargo, nodejs, npm 可用。

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=v2
FROM codercom/code-server:${CS_VER}
USER root
RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        build-essential \
        ca-certificates \
        curl \
        git \
        ssh \
        gnupg \
        libssl-dev \
        pkg-config && \
    curl -sL https://deb.nodesource.com/setup_10.x | bash && \
    apt-get install nodejs -yq && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

USER coder
#
# install rust
#
RUN curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain stable -y
ENV USER=coder
RUN export PATH="/home/coder/.cargo/bin:$PATH" && \
    curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s && \
    cargo install cargo-generate
#
# npm global install witout root
# https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
#
RUN npm config set prefix=/home/coder/.npm-packages && \
    echo '\nexport PATH="/home/coder/.npm-packages/bin:$PATH"' >> /home/coder/.bashrc && \
    echo '\nexport PATH="/home/coder/.cargo/bin:$PATH"' >> /home/coder/.bashrc

RUN set -eux  && \
    code-server --install-extension ms-ceintl.vscode-language-pack-zh-hant
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
ARG PATH_LOCALE=/home/coder/.local/share/code-server/User/locale.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

# https://code.visualstudio.com/docs/getstarted/locales
RUN echo '{ \n\
    "locale": "zh-tw" \n\
}' > ${PATH_LOCALE}
#
# docker build -t foo .
# docker run -it --rm -v $PWD:/home/coder/project -p 8080-8089:8080-8089 foo 
# http://localhost:8080/?folder=/home/coder/project/
#
# npm init rust-webpack my-app
# cd my-app && npm run start
# You must give "--host 0.0.0.0" option to webpack-dev-server in the container 

rust 開發環境 v2

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=v2
FROM codercom/code-server:${CS_VER}
USER root
RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        build-essential \
        ca-certificates \
        curl \
        git \
        ssh \
        libssl-dev \
        pkg-config && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

USER coder
#
# install rust
#
RUN curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain stable -y
ENV USER=coder
RUN cat $HOME/.cargo/env && echo -e '\nexport PATH="/home/coder/.cargo/bin:$PATH"' >> /home/coder/.bashrc

RUN set -eux  && \
    code-server --install-extension ms-ceintl.vscode-language-pack-zh-hant
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
ARG PATH_LOCALE=/home/coder/.local/share/code-server/User/locale.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

# https://code.visualstudio.com/docs/getstarted/locales
RUN echo '{ \n\
    "locale": "zh-tw" \n\
}' > ${PATH_LOCALE}
#
# docker build -t foo .
# docker run -it --rm -v $PWD:/home/coder/project -p 8080:8080 foo 
# http://localhost:8080/?folder=/home/coder/project/
# cargo new --bin hello-world 
# cd hello-world && cargo run

code-server v2 正式版本加上 vue 開發環境

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=v2
FROM codercom/code-server:${CS_VER}
USER root
RUN apt-get update -yq \
    && apt-get install curl gnupg -yq \
    && curl -sL https://deb.nodesource.com/setup_10.x | bash \
    && apt-get install nodejs -yq


USER coder
#
# npm global install witout root
# https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
#
RUN npm config set prefix=/home/coder/.npm-packages \
    && echo -e '\nexport PATH="/home/coder/.npm-packages/bin:$PATH"' >> /home/coder/.bashrc
RUN npm install -g @vue/cli

RUN set -eux  && \
    code-server --install-extension ms-ceintl.vscode-language-pack-zh-hant && \
    code-server --install-extension octref.vetur
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
ARG PATH_LOCALE=/home/coder/.local/share/code-server/User/locale.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

# https://code.visualstudio.com/docs/getstarted/locales
RUN echo '{ \n\
    "locale": "zh-tw" \n\
}' > ${PATH_LOCALE}
#
# docker build -t foo .
# docker run -it --rm -v $PWD:/home/coder/project -p 8080-8099:8080-8099 foo 
# http://localhost:8080/?folder=/home/coder/project/
#

一開始需先知道每一個使用者設定的 dev server port 才能對應

  • docker run 需要先開 port
  • package.json 裡面 vue-cli-service serve -port 8081 需要一致
docker run -it --rm -v $PWD:/home/coder/project -p 8080:8080 -p 8081:8081 foo

後來直接開 8080-8099 不用改 package.json 裡面的 port 設定。

docker run -it --rm -v $PWD:/home/coder/project -p 8080-8099:8080-8099 foo

剩下兩個問題

  • 開發時的 dev server 服務沒權限設定,每個知道 dev server port 的人都可以看到使用者正在開發的內容。
  • 有些環境只適合 443 通過如何讓使用者可以開自己的 dev server 起來用。

code-server v2 正式版本

預載中文(繁體)語言套件

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=v2
FROM codercom/code-server:${CS_VER}
USER coder
RUN set -eux  && \
    code-server --install-extension ms-ceintl.vscode-language-pack-zh-hant
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
ARG PATH_LOCALE=/home/coder/.local/share/code-server/User/locale.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

# https://code.visualstudio.com/docs/getstarted/locales
RUN echo '{ \n\
    "locale": "zh-tw" \n\
}' > ${PATH_LOCALE}

# docker build -t foo .
# docker run -it --rm -v $PWD:/home/coder/project -p 8080:8080 foo 
# http://localhost:8080/?folder=/home/coder/project/

DEPRECATED : codercom/code-server:2.1472-vsc1.38.1

測試 code-server/Dockerfile at 2.1472-vsc1.38.1 · cdr/code-server 版本,folder 網址參數可用來切換不同學員的目錄例如

  • http://localhost:8080/?folder=/home/coder/project/alice
  • http://localhost:8080/?folder=/home/coder/project/bob
  • http://localhost:8080/?folder=/home/coder/project/Y12345
# tc.sh --run-code-server $PWD 2.1472-vsc1.38.1
run_code_server(){
    need_cmd docker
    set -x
    PROJECT_DIR=$1
    VERSION=$2
    docker run -it -p 127.0.0.1:8080:8080 \
      -v "${PROJECT_DIR}:/home/coder/project" codercom/code-server:${VERSION}
}

預載 ms-ceintl.vscode-language-pack-zh-hant VS Code 的中文(繁體)語言套件

使用 microsoft/vscode-loc: VS Code Localization Extension

#
# https://hub.docker.com/r/codercom/code-server/tags
#
ARG CS_VER=2.1472-vsc1.38.1
FROM codercom/code-server:${CS_VER}
USER coder
RUN set -eux  && \
    code-server --install-extension ms-ceintl.vscode-language-pack-zh-hant
ARG PATH_SETTINGS=/home/coder/.local/share/code-server/User/settings.json
ARG PATH_LOCALE=/home/coder/.local/share/code-server/User/locale.json
# COPY settings.json ${PATH_SETTINGS}
RUN echo '{ \n\
    "terminal.integrated.shell.linux": "/bin/bash", \n\
    "files.associations": { \n\
        "[Dd]ockerfile*": "dockerfile", \n\
        "docker-compose*": "yaml" \n\
    } \n\
}' > ${PATH_SETTINGS}

# https://code.visualstudio.com/docs/getstarted/locales
RUN echo '{ \n\
    "locale": "zh-tw" \n\
}' > ${PATH_LOCALE}

TODO

link to localhost site or github pages

curl -k https://localhost:1984/dockerfiles/Dockerfile-cs-zh-tw.txt | docker build -t cslocal -
docker run -it --rm cslocal

opt-ins service in code-server docker image

  • plantuml java server ?
  • ipfs node ?
  • nginx proxy ?

helm test

DLTDOJO3R1

安裝紀錄

https://r100.ddj3.dltdojo.org

sudo snap install microk8s --classic --channel=1.15/stable
sudo snap alias microk8s.kubectl kubectl
sudo usermod -a -G microk8s dltdojo3r1
exit

microk8s.enable rbac
microk8s.enable dns
microk8s.enable ingress

cat << EOF > ddj3.crt
xxx
EOF

cat << EOF > ddj3.key
xxx
EOF

kubectl create secret tls ddj3-tls --key ddj3.key --cert ddj3.crt

kubectl 建立 Ingress 與 whoami 相關 yaml。

cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
  name: whoami
  labels:
    app: whoami

spec:
  replicas: 2
  selector:
    matchLabels:
      app: whoami
  template:
    metadata:
      labels:
        app: whoami
    spec:
      containers:
        - name: whoami
          image: containous/whoami
          ports:
            - name: web
              containerPort: 80

---

apiVersion: v1
kind: Service
metadata:
  name: whoami

spec:
  ports:
    - protocol: TCP
      name: web
      port: 80
  selector:
    app: whoami
---

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ing-root
  namespace: default
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  tls:
  - hosts:
    - r100.ddj3.dltdojo.org
    secretName: ddj3-tls
  rules:
  - host: r100.ddj3.dltdojo.org
    http:
      paths:
      - backend:
          serviceName: whoami
          servicePort: 80
        path: /
EOF

反覆重新載入頁面 r100.ddj3.dltdojo.org/ 可觀察導向不同 whoami 的 pod 服務。

Hostname: whoami-5df4df6ff5-h8vq7
IP: 127.0.0.1
IP: ::1
IP: 10.1.1.5
IP: fe80::e8da:2ff:fe9a:296d
RemoteAddr: 10.1.1.1:46834
GET / HTTP/1.1
Host: r100.ddj3.dltdojo.org
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
X-Forwarded-For: 140.110.35.68
X-Forwarded-Host: r100.ddj3.dltdojo.org
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Original-Uri: /
X-Real-Ip: 140.110.35.68
X-Request-Id: 3752e4e3fc4b77a79e1d77c045a557d8
X-Scheme: https

let's encrypt wildcard certificate

sudo certbot certonly --manual --agree-tos \
-d "*.ddj3.dltdojo.org" \
--email YOUR_EMAIL@gmail.com \
--preferred-challenges dns \
--manual-public-ip-logging-ok \
--server https://acme-v02.api.letsencrypt.org/directory \

如果不使用 let's encrypt 或是其他正式簽發的憑證可使用 nip.io 的方案,只是瀏覽器可能會多出幾個確認安全性的動作。

租用 VM 服務給的 IP 是浮動型,需設定 DNS 相對麻煩,採用 nip.io 的對應方式,假設 IP 為 192.168.99.102 則網址如用次練習編號加上 IP 會是下面格式,雖非必要,也可先產生 wildcard 憑證來搭配使用。

https://ddj3r101-192-168-99-102.nip.io

cat > openssl.cnf << EOF
[req]
prompt = no
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]
C = TW
O = DLTDOJO
OU = DLTDOJO3
CN = ddj3-127-0-0-1.nip.io

[ v3_req ]
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.nip.io
DNS.2 = localhost
IP.1 = 127.0.0.1
EOF

openssl req -x509 -days 777 -out nipio.pem \
    -keyout nipio.key -newkey rsa:2048 -nodes \
    -sha256 -extensions v3_req -config openssl.cnf

openssl x509 -text -noout -in nipio.pem

MAD-RED

TOC

Docker + Minecraft = Dockercraft

docker/dockercraft: Docker + Minecraft = Dockercraft

A simple Minecraft Docker client, to visualize and manage Docker containers.

容器啟動或關閉都可在 minecraft 裡面執行,後續可考慮實作成不須 minecraft 的 veloren 模式。

the future you dream of never comes true

Ludwig Wittgenstein - Wikipedia

You can't build clouds. And that's why the future you dream of never comes true. — Ludwig Wittgenstein

voxel-clouds-dream-190918.png

Veloren

Veloren 是一個多人RPG體素遊戲 (multiplayer voxel RPG),類似 Cube World, Legend of Zelda: Breath of the Wild, Dwarf Fortress and Minecraft

Veloren - gitlab

Veloren 新增聊天指令 /dltdojo

將 BIP39 這類工具包放進 Veloren 開源像素類遊戲專案裡面只要幾行,雖然 Veloren 還不太能夠玩,不過跟過去 BitQuest 改 Java 服務端加錢包比起來有兩個較為明顯的差異。一是 Veloren 可用 Rust 區塊鏈類工具包資源生態相對豐富,畢竟 Hyperledger/Substrate/Libra 等開源專案正在對這生態系持續注水,另一則是 BitQuest 是後端改作,採用過去 minecraft 的 GPL 程式碼修正改作,這類改作或下載某些既有資源檔等要面對的智財議題本來就多,更何況後來該遊戲還被微軟大公司買下。

訊息傳到 server 端後產生 bip 39 中文助記詞,截圖如下

git diff

diff --git a/server/Cargo.toml b/server/Cargo.toml
index 2affc8e..7efc93c 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -21,3 +21,4 @@ rand = "0.7.0"
 chrono = "0.4.7"
 hashbrown = { version = "0.5.0", features = ["serde", "nightly"] }
 crossbeam = "0.7.2"
+tiny-bip39 = "0.6.2"
\ No newline at end of file
diff --git a/server/src/cmd.rs b/server/src/cmd.rs
index 5305b8f..5384f87 100644
--- a/server/src/cmd.rs
+++ b/server/src/cmd.rs
@@ -18,6 +18,8 @@ use vek::*;
 use lazy_static::lazy_static;
 use scan_fmt::{scan_fmt, scan_fmt_some};
 
+use bip39::{Mnemonic, MnemonicType, Language};
+
 /// Struct representing a command that a user can run from server chat.
 pub struct ChatCommand {
     /// The keyword used to invoke the command, omitting the leading '/'.
@@ -137,6 +139,8 @@ lazy_static! {
         ChatCommand::new(
             "help", "", "/help: Display this message", false, handle_help),
         ChatCommand::new(
+            "dltdojo", "", "/dltdojo: Display dltdojo message", false, handle_dltdojo),
+        ChatCommand::new(
             "health",
             "{}",
             "/health : Set your current health",
@@ -489,6 +493,20 @@ fn handle_help(server: &mut Server, entity: EcsEntity, _args: String, _action: &
     }
 }
 
+
+//
+// add test chat command /dltdojo
+//
+fn handle_dltdojo(server: &mut Server, entity: EcsEntity, _args: String, _action: &ChatCommand) {
+    // create a new randomly generated mnemonic phrase, default lang is Language::English
+    let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::ChineseTraditional);
+    let phrase: &str = mnemonic.phrase();
+      server.clients.notify( entity,
+            ServerMsg::private(String::from("[DLTDOJO] MNEMONIC BIP39:")),
+        );
+    server.clients.notify(entity, ServerMsg::private(phrase.to_string()));
+}
+
 fn alignment_to_agent(alignment: &str, target: EcsEntity) -> Option<comp::Agent> {
     match alignment {
         "hostile" => Some(comp::Agent::enemy()),

Copy GenSekiGothicTW-Regular.ttf

from the ButTaiwan/genseki-font into assets/voxygen/font/

  • GenSekiGothicTW-Regular.ttf https://github.com/ButTaiwan/genseki-font
  • TW-Kai-98_1.ttf CNS11643中文標準交換碼全字庫(簡稱全字庫) https://data.gov.tw/dataset/5961
  • https://gitlab.com/veloren/veloren/blob/master/voxygen/src/hud/chat.rs
  • https://gitlab.com/veloren/veloren/blob/master/voxygen/src/menu/char_selection/ui.rs#L191
  • https://gitlab.com/search?utf8=%E2%9C%93&snippets=&scope=&repository_ref=master&search=opensans&project_id=10174980
  • Source Han Sans | 思源黑体 | 思源黑體 | 思源黑體 香港 | 源ノ角ゴシック | 본고딕 只有 OTF font 載入有問題 https://github.com/adobe-fonts/source-han-sans
$ cd assets/voxygen/font
$ mv OpenSans-Regular.ttf OpenSans-Regular-bak.ttf
$ cp GenSekiGothicTW-Regular.ttf OpenSans-Regular.ttf
$ tree

.
├── Metamorphous-Regular.ttf
├── OFL.txt
├── OpenSans-Regular-bak.ttf
├── OpenSans-Regular.ttf
└── GenSekiGothicTW-Regular.ttf

$ cd git_project_root
$ cargo run --bin veloren-server-cli
$ cargo run --bin veloren-voxygen

References

  • https://freemasen.github.io/wiredforge-wasmer-plugin-code/part_1.html
  • https://book.veloren.net/compile/troubleshooting.html#additional-required-libraries
  • https://gitlab.com/veloren/veloren/merge_requests/33
  • Basic ModLoader Implementation https://gitlab.com/veloren/veloren/commit/e5d9f34898e322a1d71e2e5df6180f99dd3f84b5
  • A typescript bitcoin library, including WASM versions of secp256k1, ripemd160, sha256, sha512, and sha1 https://github.com/bitauth/bitcoin-ts
  • https://docs.rs/wasmer-runtime/0.6.0/wasmer_runtime/
  • https://github.com/jakubtyrcha/webasm_scripting/blob/master/src/vm.rs
  • https://github.com/search?l=Rust&q=wasmer_runtime+instantiate+call&type=Code

Vox 組件開發編輯

veloren 的組件為 vox 檔,可使用 MagicaVoxel 或是 Goxel 編輯體素遊戲組件 vox 檔。

MagicVoxel

道場示意模型 40x40x40

snap

MV vox 組件庫

CC BY 姓名標示 (Creative Commons Attribution)

Mini Mike's Metro Minis 城市物件

商業

voxelmodel tag - Sketchfab

Goxel

輸入 vox 檔編輯

goxel dltdojo 190825

3D Model Viewer

匯出 glTF (GL Transmission Format) 不過不能匯入,匯出後 glTF 檔案可由 3D Viewer App 開啟。

goxel glTF export and app 3d viewer win10

Drag-and-drop preview for glTF 2.0 models in WebGL using three.js.

js glTF viewer

hujiulong/vue-3d-model 單頁展示

<body>
    <div id="app">
        <model-gltf 
            src="static/models/gltf/Duck/glTF/Duck.gltf"
            @on-mousemove="onMouseMove">
        </model-gltf>
    </div>
    <script src="vue.js"></script>
    <script src="vue-3d-model.min.js"></script>
    <script>
        new Vue({
            el: '#app'
        })
    </script>
</body>

參考連結

Voxel 相關專案

Aframe

aframe-env.html 測試網頁

<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.7.1/aframe.min.js"></script>
 <script src="https://cdn.jsdelivr.net/npm/aframe-environment-component@2.0.0/dist/aframe-environment-component.min.js"></script>
</head>
<body>
    <a-scene>
        <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
        <a-plane position="1 1 -8" rotation="45 0 0" width="3" height="3" color="#7BC8A4"></a-plane>
        <a-entity environment="preset: egypt; sunPosition: 1 5 -2; groundColor: #742"><a-entity>
    </a-scene>
</body>
</html>

(WIP) Cryptovoxels

Babylon.js Ethereum TypeScript

Cryptovoxels

Crypto-Assets

Virtual Assets

FATF 指引 RBA-VA-VASPs 用詞可能成為書寫主流用語之一。 2019 版與 2015 版的用詞差異在於新增 AEC ( Anonymity-Enhanced Cryptocurrency ) 與 VC 轉成 VA ( Virtual Asset ),VA 用詞因為包括 VC 估計用法將更為流行。AEC 用詞的出現標誌著該領域已進入監管雷達,後續 AEC 可能轉線下而消失在合規交易所,至於現階段 AEC 合約能見度不高,數年後是否會有 AEVA 用詞於指引出現讓人好奇。

Crypto Coffee

Crypto Coffee Coin Is Coming to Brazil's Countryside Farmers - Bloomberg

咖啡虛擬通貨的最終常用說法會不會是 CoffeeCoin 。

  • CoffeeCoin
  • CryptoCoffee
  • SmartContractCoffee
  • CoffeeVirtualAsset
  • CoffeeVirtualCommercialPaper
  • ScriptAssetCoffee
  • PersistentScriptCoffee
  • ScriptCoffee
  • CodeCoffee

Basic Attention Token (BAT)

Brave browser 開始進軍小螢幕,注意力商人一書裡面提到四個螢幕最後版本就是手機版,Brave browser 安裝後右上角的獅子會有明顯的數字很容易知道這個站台追蹤的資訊,建議邊看注意力商人一書邊看獅子標示更有感。

不過 firefox 隱私保護切到嚴格加上 Facebook Container 或 Ghostery 隱私廣告攔截器等,再掛個 metamask 執行合約也可以逼近 brave browser + BAT 功能,火狐加掛模式好處是不限 BAT 可用各式加密貨幣,缺點是近易用性較低,上手需時間。

Brave browser now can show its privacy-first ads on Android, too

Telegram Open Network (TON)

tpl-ton-v1.svg

Stellar XLM

Stellar

Ocean Portocol

oceanprotocol/ocean: 🌊 The Data Economy

Service Execution Agreement (SEA) or Service Agreement

A contract-like agreement between a publisher, a consumer, and a verifier, specifying what assets are to be delivered (from publisher to consumer), the conditions that must be met, and the rewards for fulfilling the conditions.

依照 Architecture Overview - Ocean Protocol Documentation 說明分為三層

  • Tier 3 - Application Layer
  • Tier 2 - Protocol Layer
  • Tier 1 - Decentralized VM Layer

Crypto

Verifiable Random Function (VRF)

Sharding

TODO

201909

  • Polkadot

Ethereum

Tools

AzBlockchain.azure-blockchain

Anonymity-Enhanced Cryptocurrency (AEC)

採用 2019 Guidance for a Risk-Based Approach to Virtual Assets and Virtual Asset Service Providers - FATF 指引 RBA-VA-VASPs 用詞 Anonymity-Enhanced Cryptocurrency (AEC) 的定義

TOC

Grin

mimblewimble/grin: Minimal implementation of the MimbleWimble protocol.

Gotts

gottstech/gotts: A blockchain for non-collateralized stable-coins, follow MimbleWimble protocol but with explicit amount.

MimbleWimble 系也出穩定幣(Decentralized non-collateralized stable-coins) 而且是 POW 鏈,宣稱可以無擔保維持幣值穩定,比 grin 的 TPS 可拉高 10 倍大概可以到 100。Gotts 的功能雖然用合約來寫也可,POW 系的穩定幣專用鏈是否可持續運轉有待觀察。

How to Ensure a Stable Price

How to Ensure a Stable Price · gottstech/gotts

In fact, Gotts price will be volatile, just like any other cryptocurrencies. Gotts coin is not a stable coin.

該鏈的原生代幣 Gotts coin 實際上會波動,並非穩定幣。

Instead, in Gotts system, the stable coins are those on-chain assets, such as GOUS, GOEU, GOCN, etc.

穩定幣是指鏈上資產

Total Value (US$) = M * R + N

Where M is the total circulation of Gotts coins,
N is the total circulation of GOUS stable-coins in the system,
R is the current Gotts coin price in US$.

穩定幣部分只有 N,假設要將 N 取出 P 來換成實際法幣,這裡先考慮只有 US$/Gotts 交易對可用。

Input = P GOUS
Output = Q Gotts

where Q = P / R, R is the current Gotts coin price in US$.

Total Value (US$) = (M + P/R)*R + (N-P) = M * R + N

N 減去 P 之後,本來的 M 位置變成 (M+P/R)

So, this means, in any time, for any amount of stablecoin assets on Gotts chain, the chain 100% ensure its face value as the pegged asset such as USD, EUR, CNY, JPN, GBP, CAD and so on.

IDDateMRNTotalNote
1012029-04-011000.10200210初始狀態
1022029-04-021000.20200220放著不動
1032029-04-031800.25180225N 轉出 20 剩 180, M 變成 (100 + 20/0.25)=180
1042029-04-0400.20216216穩定效果只有全部都是 N,將 M 清空後加上 180*0.2=36 到 N
1052029-04-0500.10216216穩定 N
1062029-04-067200.300216清空 N
1072029-04-077200.10072
1082029-05-017200.0107.2

This procedure is completely decentralized. Anybody can execute a conversion by him/her self at any time, just as simple as a normal transaction on the chain.

簡單換算可以隨時發起交易進行資產轉換,不需要先找到對手方。

It looks very like a crypto-collateralized stable-coins but actually it's NOT, here the crypto asset refers to the Gotts coin.

看起來還是很像抵押兌換,其實沒有抵押資產只是轉換。

The biggest risk to the crypto-collateralized stablecoin model is the volatility of the underlying collateral. So, normally it requires over-collateralization, moreover, once the collateral lose too much value, the liquidation procedure is forced to be enabled because under-collateralized.

不像穩定的抵押池需要持續補倉或是斷頭來維持流動水位。

For the stability, the ONLY risk is the event of the whole crypto crash, traders tend to exit to fiat currencies, not stablecoins and not Gotts coin. But that will be quite impossible once Gotts chain published, just like talking about shutdown of Bitcoin network.

唯一風險是 R 歸零如上面 108 狀態,R 需要對手方來交換,很可能根本沒人要換如小幣。

If user want to convert directly from one stablecoin to another one, for example converting GOUS to GOJP, there's no need to convert between them and Gotts coin, the chain native transaction can support these cross conversion directly among all these stablecoins.

不用對手交易方的轉換可一個交易直接兌換不同穩定幣,不需先換回 GO 如 GOUS - GO - GOEU,而是直接換 GOUS - GOEU。

Similar as Maker DAI price feed oracles, Gotts also use whitelist for price feeding.

關鍵在於外部 R 的寫入系統,類似 Maker - Feeds price feed oracles 與報價 Maker Feeds

If a block reward is 60 Gotts, 10% of this reward will go to the price feed oracles, and 90% will go to the miner. And the penalty of the fault price feed (if have) will go to the miner as the additional reward.

誠實報價獎勵經濟,這系統需要抵押的是 oracle 角色。

More price feed oracles means more safe for Gotts, but we need store these price feed data on chain, and storing all these price feed data is too expensive for the chain. So, in Gotts, we only store 15 price feed oracles data, i.e. we limit the size of vector PriceFeed to 15.

100 oracles 隨機選出 15 oracles

oracle

gottstech/gotts-oracle: Gotts Price Feed Oracle

Gotts 的設計一開始只有USD, EUR, CNY, JPN, GBP, CAD法幣對應的穩定幣,主要是這類資料被大風吹亂的機率較低,對 oracle 檢驗相對容易。

  • GOUS (pegged to fiat US dollar)
  • GOEU (pegged to fiat Euro)
  • GOCN (pegged to fiat Chinese Yuan)
  • GOJP (pegged to fiat Japanese Yen)
  • GOUK (pegged to fiat British Pound)
  • GOCA (pegged to fiat Canadian Dollar)

Stablecons

Digital Currencies: The Rise of Stablecoins – IMF Blog

Adoption of new forms of money will depend on their attractiveness as a store of value and means of payment.

FinTechs與BigTechs在支付領域之發展及影響 - 9月19日央行理監事會後記者會參考資料

電子貨幣機制與穩定幣類似,但價值穩定,未來在網路效應的推動下,可望日益普遍。IMF 甚至認為電子貨幣有可能會超越現金及銀行存款,成為民眾最常用的貨幣形式;此外,亦建議各國央行或可斟酌國情,考量透過公私部門合作方式,以中央銀行貨幣作為發行準備22,由電子貨幣機構對民眾發行「合成型 CBDC」(synthetic CBDC, sCBDC)。

DLT

TODO

Algorand

Getting Started | Algorand Developer

Oasis : Privacy-first cloud computing on blockchain

Vault blockchain backend

Protocol Buffers 小數據 ETL 練習

Protobufs-Markdown-Mdbook Extract-Transform-Load ETL 練習


#
# gen-proto-doc PROTOS_DIR DEST_FILE
# [grpc-ecosystem/grpc-gateway: gRPC to JSON proxy generator following the gRPC HTTP spec](https://github.com/grpc-ecosystem/grpc-gateway)
# go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
# go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
# go get -u github.com/golang/protobuf/protoc-gen-go
#
gen_proto_doc(){
    set -x
    PROTOS_DIR=$1
    MDFILE=md-proto-gen-tmp.md
    DEST_FILE=$2
    pushd $PROTOS_DIR
    rm /tmp/$MDFILE
    find . -type f \
       -not -path "./google/protobuf/*" \
       -not -path "./github.com/gogo/protobuf/gogoproto/*" \
       -not -path "./googleapis/google/api/*" \
       -name '*.proto' | xargs protoc -I. -I/usr/local/include \
       -I$GOPATH/src \
       -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
       --doc_out=/tmp --doc_opt=markdown,$MDFILE
    #sed -i "1i# ProtocolBuffer Doc\n## Generated Date:$(date --iso-8601=seconds)\n<!-- toc -->" /tmp/$MDFILE
    sed -i "1i# Generated Date:$(date --iso-8601=seconds)\n" /tmp/$MDFILE
    echo -e '\n# Protos File Tree\n```\n' >> /tmp/$MDFILE 
    tree -P "*.proto" . >> /tmp/$MDFILE
    echo -e '\n```\n' >> /tmp/$MDFILE 
    echo -e "# Protobuf sources\n" >> /tmp/$MDFILE
    find . -type f \
       -not -path "./google/protobuf/*" \
       -not -path "./github.com/gogo/protobuf/gogoproto/*" \
       -not -path "./googleapis/google/api/*" \
       -name '*.proto' \
       -exec echo -e '\n## src:{}\n```proto\n' \; -exec cat {} \; -exec echo -e '\n```\n' \; >> /tmp/$MDFILE
    cp -f /tmp/$MDFILE $DEST_FILE
    popd
}

blockchain projects using Protocol Buffers

FISCO BCOS

合約

FISCO BCOS平台目前支持Solidity、CRUD、Precompiled三种智能合约形式。

通訊

链上信使协议AMOP(Advanced Messages Onchain Protocol)系统旨在为联盟链提供一个安全高效的消息信道,联盟链中的各个机构,只要部署了区块链节点,无论是共识节点还是观察节点,均可使用AMOP进行通讯

Eclipse Attack

Akropolisio

akropolisio/akropolisOS-chain-node: AkropolisOS Chain (Argos Testnet v0.1)

Fluence

fluencelabs/fluence: Fluence is an open-source, decentralized cloud computing platform

Fluence is a decentralized database network that allows to deploy many existing first-class SQL/NoSQL/GraphQL databases such as SQLite or Redis into the decentralized environment. It will support many complex database operations, such as aggregate functions, joins, or stored procedures.

NEAR Protocol

NEAR Protocol

nearprotocol/NEARStudio: IDE for building smart contracts on NEAR Protocol 主要是基於 wasdk/WebAssemblyStudio: Learn, Teach, Work and Play in the WebAssembly Studio 修改的 IDE,執行程式會被轉到 app.near.ai 網站執行,初步觀察並非在同一台機器內執行,

Webassembly.studio Hello World Rust Project 與 DLTDOJO3 使用 code-server 模式都一樣在可本機內執行模擬程式。

When building the project you'll get out/main_bg.wasm, the generated wasm filtered through the wasm-bindgen CLI tool, as well as out/main.js which is an auxiliary JS file generated by the wasm-bindgen tool, included by default in main.html. The out/main.js file is responsible for creating the wasmBindgen global and filling it in.

201909

HyperLedger Fabric

TOC

Tools

IBMBlockchain.ibm-blockchain-platform

Topics

Hyperledger Fabric Operator

Cloud native deployment support

FAB-13582 Peer and Chaincode cloud native deployment support - Hyperledger JIRA

The current runtime model of a chaincode is that it has to be in a sandbox (Docker container) since it is co-located in the hosting peer's environment. To sandbox, the hosting peer builds the chaincode Docker image and launches the container during the instantiate transaction.

在Kubernetes上运行区块链服务(BaaS) - 知乎

由于该过程是独立于Kubernetes体系之外运行的,难以对chaincode容器进行生命周期管理。无法基于Kubernetes的namaspace隔离、NetworkPolicy等机制实现对chaincode容器的安全管理。

生成 Google Protocol Buffers 文件

hyperledger/fabric-protos

git clone https://github.com/hyperledger/fabric-protos.git /tmp/src/hlf-protos
bash tc.sh --gen-proto-doc /tmp/src/hlf-protos /tmp/output.md

Generated Date:2019-09-12T14:31:57+08:00

Protocol Documentation

Table of Contents

Top

peer/transaction.proto

ChaincodeActionPayload

ChaincodeActionPayload is the message to be used for the TransactionAction's payload when the Header's type is set to CHAINCODE. It carries the chaincodeProposalPayload and an endorsed action to apply to the ledger.

FieldTypeLabelDescription
chaincode_proposal_payloadbytesThis field contains the bytes of the ChaincodeProposalPayload message from the original invocation (essentially the arguments) after the application of the visibility function. The main visibility modes are "full" (the entire ChaincodeProposalPayload message is included here), "hash" (only the hash of the ChaincodeProposalPayload message is included) or "nothing". This field will be used to check the consistency of ProposalResponsePayload.proposalHash. For the CHAINCODE type, ProposalResponsePayload.proposalHash is supposed to be H(ProposalHeader
actionChaincodeEndorsedActionThe list of actions to apply to the ledger

ChaincodeEndorsedAction

ChaincodeEndorsedAction carries information about the endorsement of a specific proposal

FieldTypeLabelDescription
proposal_response_payloadbytesThis is the bytes of the ProposalResponsePayload message signed by the endorsers. Recall that for the CHAINCODE type, the ProposalResponsePayload's extenstion field carries a ChaincodeAction
endorsementsEndorsementrepeatedThe endorsement of the proposal, basically the endorser's signature over proposalResponsePayload

ProcessedTransaction

ProcessedTransaction wraps an Envelope that includes a transaction along with an indication of whether the transaction was validated or invalidated by committing peer. The use case is that GetTransactionByID API needs to retrieve the transaction Envelope from block storage, and return it to a client, and indicate whether the transaction was validated or invalidated by committing peer. So that the originally submitted transaction Envelope is not modified, the ProcessedTransaction wrapper is returned.

FieldTypeLabelDescription
transactionEnvelopecommon.EnvelopeAn Envelope which includes a processed transaction
validationCodeint32An indication of whether the transaction was validated or invalidated by committing peer

SignedTransaction

This message is necessary to facilitate the verification of the signature (in the signature field) over the bytes of the transaction (in the transactionBytes field).

FieldTypeLabelDescription
transaction_bytesbytesThe bytes of the Transaction. NDD
signaturebytesSignature of the transactionBytes The public key of the signature is in the header field of TransactionAction There might be multiple TransactionAction, so multiple headers, but there should be same transactor identity (cert) in all headers

Transaction

The transaction to be sent to the ordering service. A transaction contains one or more TransactionAction. Each TransactionAction binds a proposal to potentially multiple actions. The transaction is atomic meaning that either all actions in the transaction will be committed or none will. Note that while a Transaction might include more than one Header, the Header.creator field must be the same in each. A single client is free to issue a number of independent Proposal, each with their header (Header) and request payload (ChaincodeProposalPayload). Each proposal is independently endorsed generating an action (ProposalResponsePayload) with one signature per Endorser. Any number of independent proposals (and their action) might be included in a transaction to ensure that they are treated atomically.

FieldTypeLabelDescription
actionsTransactionActionrepeatedThe payload is an array of TransactionAction. An array is necessary to accommodate multiple actions per transaction

TransactionAction

TransactionAction binds a proposal to its action. The type field in the header dictates the type of action to be applied to the ledger.

FieldTypeLabelDescription
headerbytesThe header of the proposal action, which is the proposal header
payloadbytesThe payload of the action as defined by the type in the header For chaincode, it's the bytes of ChaincodeActionPayload

MetaDataKeys

Reserved entries in the key-level metadata map

NameNumberDescription
VALIDATION_PARAMETER0
VALIDATION_PARAMETER_V21

TxValidationCode

NameNumberDescription
VALID0
NIL_ENVELOPE1
BAD_PAYLOAD2
BAD_COMMON_HEADER3
BAD_CREATOR_SIGNATURE4
INVALID_ENDORSER_TRANSACTION5
INVALID_CONFIG_TRANSACTION6
UNSUPPORTED_TX_PAYLOAD7
BAD_PROPOSAL_TXID8
DUPLICATE_TXID9
ENDORSEMENT_POLICY_FAILURE10
MVCC_READ_CONFLICT11
PHANTOM_READ_CONFLICT12
UNKNOWN_TX_TYPE13
TARGET_CHAIN_NOT_FOUND14
MARSHAL_TX_ERROR15
NIL_TXACTION16
EXPIRED_CHAINCODE17
CHAINCODE_VERSION_CONFLICT18
BAD_HEADER_EXTENSION19
BAD_CHANNEL_HEADER20
BAD_RESPONSE_PAYLOAD21
BAD_RWSET22
ILLEGAL_WRITESET23
INVALID_WRITESET24
INVALID_CHAINCODE25
NOT_VALIDATED254
INVALID_OTHER_REASON255

Top

peer/configuration.proto

ACLs

ACLs provides mappings for resources in a channel. APIResource encapsulates reference to a policy used to determine ACL for the resource

FieldTypeLabelDescription
aclsACLs.AclsEntryrepeated

ACLs.AclsEntry

FieldTypeLabelDescription
keystring
valueAPIResource

APIResource

APIResource represents an API resource in the peer whose ACL is determined by the policy_ref field

FieldTypeLabelDescription
policy_refstringThe policy name to use for this API

AnchorPeer

AnchorPeer message structure which provides information about anchor peer, it includes host name, port number and peer certificate.

FieldTypeLabelDescription
hoststringDNS host name of the anchor peer
portint32The port number

AnchorPeers

AnchorPeers simply represents list of anchor peers which is used in ConfigurationItem

FieldTypeLabelDescription
anchor_peersAnchorPeerrepeated

Top

peer/signed_cc_dep_spec.proto

SignedChaincodeDeploymentSpec

SignedChaincodeDeploymentSpec carries the CDS along with endorsements

FieldTypeLabelDescription
chaincode_deployment_specbytesThis is the bytes of the ChaincodeDeploymentSpec
instantiation_policybytesThis is the instantiation policy which is identical in structure to endorsement policy. This policy is checked by the VSCC at commit time on the instantiation (all peers will get the same policy as it will be part of the LSCC instantation record and will be part of the hash as well)
owner_endorsementsEndorsementrepeatedThe endorsements of the above deployment spec, the owner's signature over chaincode_deployment_spec and Endorsement.endorser.

Top

peer/chaincode.proto

CDSData

CDSData is data stored in the LSCC on instantiation of a CC for CDSPackage. This needs to be serialized for ChaincodeData hence the protobuf format

FieldTypeLabelDescription
hashbyteshash of ChaincodeDeploymentSpec.code_package
metadatahashbyteshash of ChaincodeID.name + ChaincodeID.version

ChaincodeData

ChaincodeData defines the datastructure for chaincodes to be serialized by proto Type provides an additional check by directing to use a specific package after instantiation Data is Type specific (see CDSPackage and SignedCDSPackage)

FieldTypeLabelDescription
namestringName of the chaincode
versionstringVersion of the chaincode
esccstringEscc for the chaincode instance
vsccstringVscc for the chaincode instance
policycommon.SignaturePolicyEnvelopePolicy endorsement policy for the chaincode instance
databytesData data specific to the package
idbytesId of the chaincode that's the unique fingerprint for the CC This is not currently used anywhere but serves as a good eyecatcher
instantiation_policycommon.SignaturePolicyEnvelopeInstantiationPolicy for the chaincode

ChaincodeDeploymentSpec

Specify the deployment of a chaincode. TODO: Define codePackage.

FieldTypeLabelDescription
chaincode_specChaincodeSpec
code_packagebytes

ChaincodeID

ChaincodeID contains the path as specified by the deploy transaction that created it as well as the hashCode that is generated by the system for the path. From the user level (ie, CLI, REST API and so on) deploy transaction is expected to provide the path and other requests are expected to provide the hashCode. The other value will be ignored. Internally, the structure could contain both values. For instance, the hashCode will be set when first generated using the path

FieldTypeLabelDescription
pathstringdeploy transaction will use the path
namestringall other requests will use the name (really a hashcode) generated by the deploy transaction
versionstringuser friendly version name for the chaincode

ChaincodeInput

Carries the chaincode function and its arguments. UnmarshalJSON in transaction.go converts the string-based REST/JSON input to the []byte-based current ChaincodeInput structure.

FieldTypeLabelDescription
argsbytesrepeated
decorationsChaincodeInput.DecorationsEntryrepeated
is_initboolis_init is used for the application to signal that an invocation is to be routed to the legacy 'Init' function for compatibility with chaincodes which handled Init in the old way. New applications should manage their initialized state themselves.

ChaincodeInput.DecorationsEntry

FieldTypeLabelDescription
keystring
valuebytes

ChaincodeInvocationSpec

Carries the chaincode function and its arguments.

FieldTypeLabelDescription
chaincode_specChaincodeSpec

ChaincodeSpec

Carries the chaincode specification. This is the actual metadata required for defining a chaincode.

FieldTypeLabelDescription
typeChaincodeSpec.Type
chaincode_idChaincodeID
inputChaincodeInput
timeoutint32

LifecycleEvent

LifecycleEvent is used as the payload of the chaincode event emitted by LSCC

FieldTypeLabelDescription
chaincode_namestring

ChaincodeSpec.Type

NameNumberDescription
UNDEFINED0
GOLANG1
NODE2
CAR3
JAVA4

Top

peer/proposal_response.proto

Endorsement

An endorsement is a signature of an endorser over a proposal response. By producing an endorsement message, an endorser implicitly "approves" that proposal response and the actions contained therein. When enough endorsements have been collected, a transaction can be generated out of a set of proposal responses. Note that this message only contains an identity and a signature but no signed payload. This is intentional because endorsements are supposed to be collected in a transaction, and they are all expected to endorse a single proposal response/action (many endorsements over a single proposal response)

FieldTypeLabelDescription
endorserbytesIdentity of the endorser (e.g. its certificate)
signaturebytesSignature of the payload included in ProposalResponse concatenated with the endorser's certificate; ie, sign(ProposalResponse.payload + endorser)

ProposalResponse

A ProposalResponse is returned from an endorser to the proposal submitter. The idea is that this message contains the endorser's response to the request of a client to perform an action over a chaincode (or more generically on the ledger); the response might be success/error (conveyed in the Response field) together with a description of the action and a signature over it by that endorser. If a sufficient number of distinct endorsers agree on the same action and produce signature to that effect, a transaction can be generated and sent for ordering.

FieldTypeLabelDescription
versionint32Version indicates message protocol version
timestampgoogle.protobuf.TimestampTimestamp is the time that the message was created as defined by the sender
responseResponseA response message indicating whether the endorsement of the action was successful
payloadbytesThe payload of response. It is the bytes of ProposalResponsePayload
endorsementEndorsementThe endorsement of the proposal, basically the endorser's signature over the payload

ProposalResponsePayload

ProposalResponsePayload is the payload of a proposal response. This message is the "bridge" between the client's request and the endorser's action in response to that request. Concretely, for chaincodes, it contains a hashed representation of the proposal (proposalHash) and a representation of the chaincode state changes and events inside the extension field.

FieldTypeLabelDescription
proposal_hashbytesHash of the proposal that triggered this response. The hash is used to link a response with its proposal, both for bookeeping purposes on an asynchronous system and for security reasons (accountability, non-repudiation). The hash usually covers the entire Proposal message (byte-by-byte).
extensionbytesExtension should be unmarshaled to a type-specific message. The type of the extension in any proposal response depends on the type of the proposal that the client selected when the proposal was initially sent out. In particular, this information is stored in the type field of a Header. For chaincode, it's a ChaincodeAction message

Response

A response with a representation similar to an HTTP response that can be used within another message.

FieldTypeLabelDescription
statusint32A status code that should follow the HTTP status codes.
messagestringA message associated with the response code.
payloadbytesA payload that can be used to include metadata with this response.

Top

peer/query.proto

ChaincodeInfo

ChaincodeInfo contains general information about an installed/instantiated chaincode

FieldTypeLabelDescription
namestring
versionstring
pathstringthe path as specified by the install/instantiate transaction
inputstringthe chaincode function upon instantiation and its arguments. This will be blank if the query is returning information about installed chaincodes.
esccstringthe name of the ESCC for this chaincode. This will be blank if the query is returning information about installed chaincodes.
vsccstringthe name of the VSCC for this chaincode. This will be blank if the query is returning information about installed chaincodes.
idbytesthe chaincode unique id. computed as: H( H(name

ChaincodeQueryResponse

ChaincodeQueryResponse returns information about each chaincode that pertains to a query in lscc.go, such as GetChaincodes (returns all chaincodes instantiated on a channel), and GetInstalledChaincodes (returns all chaincodes installed on a peer)

FieldTypeLabelDescription
chaincodesChaincodeInforepeated

ChannelInfo

ChannelInfo contains general information about channels

FieldTypeLabelDescription
channel_idstring

ChannelQueryResponse

ChannelQueryResponse returns information about each channel that pertains to a query in lscc.go, such as GetChannels (returns all channels for a given peer)

FieldTypeLabelDescription
channelsChannelInforepeated

Top

peer/resources.proto

ChaincodeEndorsement

ChaincodeEndorsement instructs the peer how transactions should be endorsed. The only endorsement mechanism which ships with the fabric today is the standard 'escc' mechanism. This code simply simulates the proposal to generate a RW set, then signs the result using the peer's local signing identity.

FieldTypeLabelDescription
namestringSpecifies what code to run for endorsements, defaults 'escc'

ChaincodeIdentifier

ChaincodeIdentifier identifies a piece of chaincode. For a peer to accept invocations of this chaincode, the hash of the installed code must match, as must the version string included with the install command.

FieldTypeLabelDescription
hashbytesThe hash of the chaincode bytes
versionstringA user friendly human readable name corresponding to the ID

ChaincodeValidation

ChaincodeValidation instructs the peer how transactions for this chaincode should be validated. The only validation mechanism which ships with fabric today is the standard 'vscc' validation mechanism. This built in validation method utilizes an endorsement policy which checks that a sufficient number of signatures have been included. The 'arguement' field encodes any parameters required by the validation implementation.

FieldTypeLabelDescription
namestringSpecifies which code to run to validate transactions, defaults to 'vscc'
argumentbytesWhen 'vscc' a marshaled VSCCArgs

ConfigTree

ConfigTree encapsulates channel and resources configuration of a channel. Both configurations are represented as common.Config

FieldTypeLabelDescription
channel_configcommon.Config
resources_configcommon.Config

VSCCArgs

VSCCArgs is passed (marshaled) as a parameter to the VSCC imlementation via the argument field of the ChaincodeValidation message.

FieldTypeLabelDescription
endorsement_policy_refstringA named reference to an endorsement policy,

Top

peer/events.proto

BlockAndPrivateData

BlockAndPrivateData contains Block and a map from tx_seq_in_block to rwset.TxPvtReadWriteSet

FieldTypeLabelDescription
blockcommon.Block
private_data_mapBlockAndPrivateData.PrivateDataMapEntryrepeatedmap from tx_seq_in_block to rwset.TxPvtReadWriteSet

BlockAndPrivateData.PrivateDataMapEntry

FieldTypeLabelDescription
keyuint64
valuerwset.TxPvtReadWriteSet

DeliverResponse

DeliverResponse

FieldTypeLabelDescription
statuscommon.Status
blockcommon.Block
filtered_blockFilteredBlock
block_and_private_dataBlockAndPrivateData

FilteredBlock

FilteredBlock is a minimal set of information about a block

FieldTypeLabelDescription
channel_idstring
numberuint64The position in the blockchain
filtered_transactionsFilteredTransactionrepeated

FilteredChaincodeAction

FilteredChaincodeAction is a minimal set of information about an action within a transaction

FieldTypeLabelDescription
chaincode_eventChaincodeEvent

FilteredTransaction

FilteredTransaction is a minimal set of information about a transaction within a block

FieldTypeLabelDescription
txidstring
typecommon.HeaderType
tx_validation_codeTxValidationCode
transaction_actionsFilteredTransactionActions

FilteredTransactionActions

FilteredTransactionActions is a wrapper for array of TransactionAction message from regular block

FieldTypeLabelDescription
chaincode_actionsFilteredChaincodeActionrepeated

Deliver

Method NameRequest TypeResponse TypeDescription
Deliver.common.Envelope streamDeliverResponse streamDeliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with Payload data as a marshaled orderer.SeekInfo message, then a stream of block replies is received
DeliverFiltered.common.Envelope streamDeliverResponse streamDeliverFiltered first requires an Envelope of type ab.DELIVER_SEEK_INFO with Payload data as a marshaled orderer.SeekInfo message, then a stream of filtered block replies is received
DeliverWithPrivateData.common.Envelope streamDeliverResponse streamDeliverWithPrivateData first requires an Envelope of type ab.DELIVER_SEEK_INFO with Payload data as a marshaled orderer.SeekInfo message, then a stream of block and private data replies is received

Top

peer/proposal.proto

ChaincodeAction

ChaincodeAction contains the actions the events generated by the execution of the chaincode.

FieldTypeLabelDescription
resultsbytesThis field contains the read set and the write set produced by the chaincode executing this invocation.
eventsbytesThis field contains the events generated by the chaincode executing this invocation.
responseResponseThis field contains the result of executing this invocation.
chaincode_idChaincodeIDThis field contains the ChaincodeID of executing this invocation. Endorser will set it with the ChaincodeID called by endorser while simulating proposal. Committer will validate the version matching with latest chaincode version. Adding ChaincodeID to keep version opens up the possibility of multiple ChaincodeAction per transaction.

ChaincodeHeaderExtension

ChaincodeHeaderExtension is the Header's extentions message to be used when the Header's type is CHAINCODE. This extensions is used to specify which chaincode to invoke and what should appear on the ledger.

FieldTypeLabelDescription
chaincode_idChaincodeIDThe ID of the chaincode to target.

ChaincodeProposalPayload

ChaincodeProposalPayload is the Proposal's payload message to be used when the Header's type is CHAINCODE. It contains the arguments for this invocation.

FieldTypeLabelDescription
inputbytesInput contains the arguments for this invocation. If this invocation deploys a new chaincode, ESCC/VSCC are part of this field. This is usually a marshaled ChaincodeInvocationSpec
TransientMapChaincodeProposalPayload.TransientMapEntryrepeatedTransientMap contains data (e.g. cryptographic material) that might be used to implement some form of application-level confidentiality. The contents of this field are supposed to always be omitted from the transaction and excluded from the ledger.

ChaincodeProposalPayload.TransientMapEntry

FieldTypeLabelDescription
keystring
valuebytes

Proposal

A Proposal is sent to an endorser for endorsement. The proposal contains:

  1. A header which should be unmarshaled to a Header message. Note that Header is both the header of a Proposal and of a Transaction, in that i) both headers should be unmarshaled to this message; and ii) it is used to compute cryptographic hashes and signatures. The header has fields common to all proposals/transactions. In addition it has a type field for additional customization. An example of this is the ChaincodeHeaderExtension message used to extend the Header for type CHAINCODE.
  2. A payload whose type depends on the header's type field.
  3. An extension whose type depends on the header's type field.

Let us see an example. For type CHAINCODE (see the Header message), we have the following:

  1. The header is a Header message whose extensions field is a ChaincodeHeaderExtension message.
  2. The payload is a ChaincodeProposalPayload message.
  3. The extension is a ChaincodeAction that might be used to ask the endorsers to endorse a specific ChaincodeAction, thus emulating the submitting peer model.
FieldTypeLabelDescription
headerbytesThe header of the proposal. It is the bytes of the Header
payloadbytesThe payload of the proposal as defined by the type in the proposal header.
extensionbytesOptional extensions to the proposal. Its content depends on the Header's type field. For the type CHAINCODE, it might be the bytes of a ChaincodeAction message.

SignedProposal

This structure is necessary to sign the proposal which contains the header and the payload. Without this structure, we would have to concatenate the header and the payload to verify the signature, which could be expensive with large payload

When an endorser receives a SignedProposal message, it should verify the signature over the proposal bytes. This verification requires the following steps:

  1. Verification of the validity of the certificate that was used to produce the signature. The certificate will be available once proposalBytes has been unmarshalled to a Proposal message, and Proposal.header has been unmarshalled to a Header message. While this unmarshalling-before-verifying might not be ideal, it is unavoidable because i) the signature needs to also protect the signing certificate; ii) it is desirable that Header is created once by the client and never changed (for the sake of accountability and non-repudiation). Note also that it is actually impossible to conclusively verify the validity of the certificate included in a Proposal, because the proposal needs to first be endorsed and ordered with respect to certificate expiration transactions. Still, it is useful to pre-filter expired certificates at this stage.
  2. Verification that the certificate is trusted (signed by a trusted CA) and that it is allowed to transact with us (with respect to some ACLs);
  3. Verification that the signature on proposalBytes is valid;
  4. Detect replay attacks;
FieldTypeLabelDescription
proposal_bytesbytesThe bytes of Proposal
signaturebytesSignaure over proposalBytes; this signature is to be verified against the creator identity contained in the header of the Proposal message marshaled as proposalBytes

Top

peer/policy.proto

ApplicationPolicy

ApplicationPolicy captures the diffenrent policy types that are set and evaluted at the application level.

FieldTypeLabelDescription
signature_policycommon.SignaturePolicyEnvelopeSignaturePolicy type is used if the policy is specified as a combination (using threshold gates) of signatures from MSP principals
channel_config_policy_referencestringChannelConfigPolicyReference is used when the policy is specified as a string that references a policy defined in the configuration of the channel

Top

peer/lifecycle/chaincode_definition.proto

ChaincodeEndorsementInfo

ChaincodeEndorsementInfo is (most) everything the peer needs to know in order to execute a chaincode

FieldTypeLabelDescription
versionstring
init_requiredbool
endorsement_pluginstring

ChaincodeValidationInfo

ValidationInfo is (most) everything the peer needs to know in order to validate a transaction

FieldTypeLabelDescription
validation_pluginstring
validation_parameterbytes

Top

peer/lifecycle/lifecycle.proto

ApproveChaincodeDefinitionForMyOrgArgs

ApproveChaincodeDefinitionForMyOrgArgs is the message used as arguments to _lifecycle.ApproveChaincodeDefinitionForMyOrg.

FieldTypeLabelDescription
sequenceint64
namestring
versionstring
endorsement_pluginstring
validation_pluginstring
validation_parameterbytes
collectionscommon.CollectionConfigPackage
init_requiredbool
sourceChaincodeSource

ApproveChaincodeDefinitionForMyOrgResult

ApproveChaincodeDefinitionForMyOrgResult is the message returned by _lifecycle.ApproveChaincodeDefinitionForMyOrg. Currently it returns nothing, but may be extended in the future.

ChaincodeSource

FieldTypeLabelDescription
unavailableChaincodeSource.Unavailable
local_packageChaincodeSource.Local

ChaincodeSource.Local

FieldTypeLabelDescription
package_idstring

ChaincodeSource.Unavailable

CheckCommitReadinessArgs

CheckCommitReadinessArgs is the message used as arguments to _lifecycle.CheckCommitReadiness.

FieldTypeLabelDescription
sequenceint64
namestring
versionstring
endorsement_pluginstring
validation_pluginstring
validation_parameterbytes
collectionscommon.CollectionConfigPackage
init_requiredbool

CheckCommitReadinessResult

CheckCommitReadinessResult is the message returned by _lifecycle.CheckCommitReadiness. It returns a map of orgs to their approval (true/false) for the definition supplied as args.

FieldTypeLabelDescription
approvalsCheckCommitReadinessResult.ApprovalsEntryrepeated

CheckCommitReadinessResult.ApprovalsEntry

FieldTypeLabelDescription
keystring
valuebool

CommitChaincodeDefinitionArgs

CommitChaincodeDefinitionArgs is the message used as arguments to _lifecycle.CommitChaincodeDefinition.

FieldTypeLabelDescription
sequenceint64
namestring
versionstring
endorsement_pluginstring
validation_pluginstring
validation_parameterbytes
collectionscommon.CollectionConfigPackage
init_requiredbool

CommitChaincodeDefinitionResult

CommitChaincodeDefinitionResult is the message returned by _lifecycle.CommitChaincodeDefinition. Currently it returns nothing, but may be extended in the future.

GetInstalledChaincodePackageArgs

GetInstalledChaincodePackageArgs is the message used as the argument to '_lifecycle.GetInstalledChaincodePackage'.

FieldTypeLabelDescription
package_idstring

GetInstalledChaincodePackageResult

GetInstalledChaincodePackageResult is the message returned by '_lifecycle.GetInstalledChaincodePackage'.

FieldTypeLabelDescription
chaincode_install_packagebytes

InstallChaincodeArgs

InstallChaincodeArgs is the message used as the argument to '_lifecycle.InstallChaincode'.

FieldTypeLabelDescription
chaincode_install_packagebytesThis should be a marshaled lifecycle.ChaincodePackage

InstallChaincodeResult

InstallChaincodeArgs is the message returned by '_lifecycle.InstallChaincode'.

FieldTypeLabelDescription
package_idstring
labelstring

QueryChaincodeDefinitionArgs

QueryChaincodeDefinitionArgs is the message used as arguments to _lifecycle.QueryChaincodeDefinition.

FieldTypeLabelDescription
namestring

QueryChaincodeDefinitionResult

QueryChaincodeDefinitionResult is the message returned by _lifecycle.QueryChaincodeDefinition.

FieldTypeLabelDescription
sequenceint64
versionstring
endorsement_pluginstring
validation_pluginstring
validation_parameterbytes
collectionscommon.CollectionConfigPackage
init_requiredbool
approvalsQueryChaincodeDefinitionResult.ApprovalsEntryrepeated

QueryChaincodeDefinitionResult.ApprovalsEntry

FieldTypeLabelDescription
keystring
valuebool

QueryChaincodeDefinitionsArgs

QueryChaincodeDefinitionsArgs is the message used as arguments to _lifecycle.QueryChaincodeDefinitions.

QueryChaincodeDefinitionsResult

QueryChaincodeDefinitionsResult is the message returned by _lifecycle.QueryChaincodeDefinitions.

FieldTypeLabelDescription
chaincode_definitionsQueryChaincodeDefinitionsResult.ChaincodeDefinitionrepeated

QueryChaincodeDefinitionsResult.ChaincodeDefinition

FieldTypeLabelDescription
namestring
sequenceint64
versionstring
endorsement_pluginstring
validation_pluginstring
validation_parameterbytes
collectionscommon.CollectionConfigPackage
init_requiredbool

QueryInstalledChaincodeArgs

QueryInstalledChaincodeArgs is the message used as arguments '_lifecycle.QueryInstalledChaincode'

FieldTypeLabelDescription
package_idstring

QueryInstalledChaincodeResult

QueryInstalledChaincodeResult is the message returned by '_lifecycle.QueryInstalledChaincode'

FieldTypeLabelDescription
package_idstring
labelstring
referencesQueryInstalledChaincodeResult.ReferencesEntryrepeated

QueryInstalledChaincodeResult.Chaincode

FieldTypeLabelDescription
namestring
versionstring

QueryInstalledChaincodeResult.References

FieldTypeLabelDescription
chaincodesQueryInstalledChaincodeResult.Chaincoderepeated

QueryInstalledChaincodeResult.ReferencesEntry

FieldTypeLabelDescription
keystring
valueQueryInstalledChaincodeResult.References

QueryInstalledChaincodesArgs

QueryInstalledChaincodesArgs currently is an empty argument to '_lifecycle.QueryInstalledChaincodes'. In the future, it may be extended to have parameters.

QueryInstalledChaincodesResult

QueryInstalledChaincodesResult is the message returned by '_lifecycle.QueryInstalledChaincodes'. It returns a list of installed chaincodes, including a map of channel name to chaincode name and version pairs of chaincode definitions that reference this chaincode package.

FieldTypeLabelDescription
installed_chaincodesQueryInstalledChaincodesResult.InstalledChaincoderepeated

QueryInstalledChaincodesResult.Chaincode

FieldTypeLabelDescription
namestring
versionstring

QueryInstalledChaincodesResult.InstalledChaincode

FieldTypeLabelDescription
package_idstring
labelstring
referencesQueryInstalledChaincodesResult.InstalledChaincode.ReferencesEntryrepeated

QueryInstalledChaincodesResult.InstalledChaincode.ReferencesEntry

FieldTypeLabelDescription
keystring
valueQueryInstalledChaincodesResult.References

QueryInstalledChaincodesResult.References

FieldTypeLabelDescription
chaincodesQueryInstalledChaincodesResult.Chaincoderepeated

Top

peer/lifecycle/db.proto

StateData

StateData encodes a particular field of a datatype

FieldTypeLabelDescription
Int64int64
Bytesbytes
Stringstring

StateMetadata

StateMetadata describes the keys in a namespace. It is necessary because in collections, range scans are not possible during transactions which write. Therefore we must track the keys in our namespace ourselves.

FieldTypeLabelDescription
datatypestring
fieldsstringrepeated

Top

peer/chaincode_event.proto

ChaincodeEvent

ChaincodeEvent is used for events and registrations that are specific to chaincode string type - "chaincode"

FieldTypeLabelDescription
chaincode_idstring
tx_idstring
event_namestring
payloadbytes

Top

peer/chaincode_shim.proto

ChaincodeMessage

FieldTypeLabelDescription
typeChaincodeMessage.Type
timestampgoogle.protobuf.Timestamp
payloadbytes
txidstring
proposalSignedProposal
chaincode_eventChaincodeEventevent emitted by chaincode. Used only with Init or Invoke. This event is then stored (currently) with Block.NonHashData.TransactionResult
channel_idstringchannel id

DelState

DelState is the payload of a ChaincodeMessage. It contains a key which needs to be recorded in the transaction's write set as a delete operation. If the collection is specified, the key needs to be recorded in the transaction's private write set as a delete operation.

FieldTypeLabelDescription
keystring
collectionstring

GetHistoryForKey

GetHistoryForKey is the payload of a ChaincodeMessage. It contains a key for which the historical values need to be retrieved.

FieldTypeLabelDescription
keystring

GetQueryResult

GetQueryResult is the payload of a ChaincodeMessage. It contains a query string in the form that is supported by the underlying state database. If the collection is specified, the query needs to be executed on the private data. The metadata hold the byte representation of QueryMetadata.

FieldTypeLabelDescription
querystring
collectionstring
metadatabytes

GetState

GetState is the payload of a ChaincodeMessage. It contains a key which is to be fetched from the ledger. If the collection is specified, the key would be fetched from the collection (i.e., private state)

FieldTypeLabelDescription
keystring
collectionstring

GetStateByRange

GetStateByRange is the payload of a ChaincodeMessage. It contains a start key and a end key required to execute range query. If the collection is specified, the range query needs to be executed on the private data. The metadata hold the byte representation of QueryMetadata.

FieldTypeLabelDescription
startKeystring
endKeystring
collectionstring
metadatabytes

GetStateMetadata

FieldTypeLabelDescription
keystring
collectionstring

PutState

PutState is the payload of a ChaincodeMessage. It contains a key and value which needs to be written to the transaction's write set. If the collection is specified, the key and value would be written to the transaction's private write set.

FieldTypeLabelDescription
keystring
valuebytes
collectionstring

PutStateMetadata

FieldTypeLabelDescription
keystring
collectionstring
metadataStateMetadata

QueryMetadata

QueryMetadata is the metadata of a GetStateByRange and GetQueryResult. It contains a pageSize which denotes the number of records to be fetched and a bookmark.

FieldTypeLabelDescription
pageSizeint32
bookmarkstring

QueryResponse

QueryResponse is returned by the peer as a result of a GetStateByRange, GetQueryResult, and GetHistoryForKey. It holds a bunch of records in results field, a flag to denote whether more results need to be fetched from the peer in has_more field, transaction id in id field, and a QueryResponseMetadata in metadata field.

FieldTypeLabelDescription
resultsQueryResultBytesrepeated
has_morebool
idstring
metadatabytes

QueryResponseMetadata

QueryResponseMetadata is the metadata of a QueryResponse. It contains a count which denotes the number of records fetched from the ledger and a bookmark.

FieldTypeLabelDescription
fetched_records_countint32
bookmarkstring

QueryResultBytes

QueryResultBytes hold the byte representation of a record returned by the peer.

FieldTypeLabelDescription
resultBytesbytes

QueryStateClose

FieldTypeLabelDescription
idstring

QueryStateNext

FieldTypeLabelDescription
idstring

StateMetadata

FieldTypeLabelDescription
metakeystring
valuebytes

StateMetadataResult

FieldTypeLabelDescription
entriesStateMetadatarepeated

ChaincodeMessage.Type

NameNumberDescription
UNDEFINED0
REGISTER1
REGISTERED2
INIT3
READY4
TRANSACTION5
COMPLETED6
ERROR7
GET_STATE8
PUT_STATE9
DEL_STATE10
INVOKE_CHAINCODE11
RESPONSE13
GET_STATE_BY_RANGE14
GET_QUERY_RESULT15
QUERY_STATE_NEXT16
QUERY_STATE_CLOSE17
KEEPALIVE18
GET_HISTORY_FOR_KEY19
GET_STATE_METADATA20
PUT_STATE_METADATA21
GET_PRIVATE_DATA_HASH22

ChaincodeSupport

Interface that provides support to chaincode execution. ChaincodeContext provides the context necessary for the server to respond appropriately.

Method NameRequest TypeResponse TypeDescription
RegisterChaincodeMessage streamChaincodeMessage stream

Top

peer/peer.proto

Endorser

Method NameRequest TypeResponse TypeDescription
ProcessProposalSignedProposalProposalResponse

Top

msp/msp_config.proto

FabricCryptoConfig

FabricCryptoConfig contains configuration parameters for the cryptographic algorithms used by the MSP this configuration refers to

FieldTypeLabelDescription
signature_hash_familystringSignatureHashFamily is a string representing the hash family to be used during sign and verify operations. Allowed values are "SHA2" and "SHA3".
identity_identifier_hash_functionstringIdentityIdentifierHashFunction is a string representing the hash function to be used during the computation of the identity identifier of an MSP identity. Allowed values are "SHA256", "SHA384" and "SHA3_256", "SHA3_384".

FabricMSPConfig

FabricMSPConfig collects all the configuration information for a Fabric MSP. Here we assume a default certificate validation policy, where any certificate signed by any of the listed rootCA certs would be considered as valid under this MSP. This MSP may or may not come with a signing identity. If it does, it can also issue signing identities. If it does not, it can only be used to validate and verify certificates.

FieldTypeLabelDescription
namestringName holds the identifier of the MSP; MSP identifier is chosen by the application that governs this MSP. For example, and assuming the default implementation of MSP, that is X.509-based and considers a single Issuer, this can refer to the Subject OU field or the Issuer OU field.
root_certsbytesrepeatedList of root certificates trusted by this MSP they are used upon certificate validation (see comment for IntermediateCerts below)
intermediate_certsbytesrepeatedList of intermediate certificates trusted by this MSP; they are used upon certificate validation as follows: validation attempts to build a path from the certificate to be validated (which is at one end of the path) and one of the certs in the RootCerts field (which is at the other end of the path). If the path is longer than 2, certificates in the middle are searched within the IntermediateCerts pool
adminsbytesrepeatedIdentity denoting the administrator of this MSP
revocation_listbytesrepeatedIdentity revocation list
signing_identitySigningIdentityInfoSigningIdentity holds information on the signing identity this peer is to use, and which is to be imported by the MSP defined before
organizational_unit_identifiersFabricOUIdentifierrepeatedOrganizationalUnitIdentifiers holds one or more fabric organizational unit identifiers that belong to this MSP configuration
crypto_configFabricCryptoConfigFabricCryptoConfig contains the configuration parameters for the cryptographic algorithms used by this MSP
tls_root_certsbytesrepeatedList of TLS root certificates trusted by this MSP. They are returned by GetTLSRootCerts.
tls_intermediate_certsbytesrepeatedList of TLS intermediate certificates trusted by this MSP; They are returned by GetTLSIntermediateCerts.
fabric_node_ousFabricNodeOUsfabric_node_ous contains the configuration to distinguish clients from peers from orderers based on the OUs.

FabricNodeOUs

FabricNodeOUs contains configuration to tell apart clients from peers from orderers based on OUs. If NodeOUs recognition is enabled then an msp identity that does not contain any of the specified OU will be considered invalid.

FieldTypeLabelDescription
enableboolIf true then an msp identity that does not contain any of the specified OU will be considered invalid.
client_ou_identifierFabricOUIdentifierOU Identifier of the clients
peer_ou_identifierFabricOUIdentifierOU Identifier of the peers
admin_ou_identifierFabricOUIdentifierOU Identifier of the admins
orderer_ou_identifierFabricOUIdentifierOU Identifier of the orderers

FabricOUIdentifier

FabricOUIdentifier represents an organizational unit and its related chain of trust identifier.

FieldTypeLabelDescription
certificatebytesCertificate represents the second certificate in a certification chain. (Notice that the first certificate in a certification chain is supposed to be the certificate of an identity). It must correspond to the certificate of root or intermediate CA recognized by the MSP this message belongs to. Starting from this certificate, a certification chain is computed and bound to the OrganizationUnitIdentifier specified
organizational_unit_identifierstringOrganizationUnitIdentifier defines the organizational unit under the MSP identified with MSPIdentifier

IdemixMSPConfig

IdemixMSPConfig collects all the configuration information for an Idemix MSP.

FieldTypeLabelDescription
namestringName holds the identifier of the MSP
ipkbytesipk represents the (serialized) issuer public key
signerIdemixMSPSignerConfigsigner may contain crypto material to configure a default signer
revocation_pkbytesrevocation_pk is the public key used for revocation of credentials
epochint64epoch represents the current epoch (time interval) used for revocation

IdemixMSPSignerConfig

IdemixMSPSIgnerConfig contains the crypto material to set up an idemix signing identity

FieldTypeLabelDescription
credbytescred represents the serialized idemix credential of the default signer
skbytessk is the secret key of the default signer, corresponding to credential Cred
organizational_unit_identifierstringorganizational_unit_identifier defines the organizational unit the default signer is in
roleint32role defines whether the default signer is admin, peer, member or client
enrollment_idstringenrollment_id contains the enrollment id of this signer
credential_revocation_informationbytescredential_revocation_information contains a serialized CredentialRevocationInformation

KeyInfo

KeyInfo represents a (secret) key that is either already stored in the bccsp/keystore or key material to be imported to the bccsp key-store. In later versions it may contain also a keystore identifier

FieldTypeLabelDescription
key_identifierstringIdentifier of the key inside the default keystore; this for the case of Software BCCSP as well as the HSM BCCSP would be the SKI of the key
key_materialbytesKeyMaterial (optional) for the key to be imported; this is properly encoded key bytes, prefixed by the type of the key

MSPConfig

MSPConfig collects all the configuration information for an MSP. The Config field should be unmarshalled in a way that depends on the Type

FieldTypeLabelDescription
typeint32Type holds the type of the MSP; the default one would be of type FABRIC implementing an X.509 based provider
configbytesConfig is MSP dependent configuration info

SigningIdentityInfo

SigningIdentityInfo represents the configuration information related to the signing identity the peer is to use for generating endorsements

FieldTypeLabelDescription
public_signerbytesPublicSigner carries the public information of the signing identity. For an X.509 provider this would be represented by an X.509 certificate
private_signerKeyInfoPrivateSigner denotes a reference to the private key of the peer's signing identity

Top

msp/msp_principal.proto

CombinedPrincipal

CombinedPrincipal governs the organization of the Principal field of a policy principal when principal_classification has indicated that a combined form of principals is required

FieldTypeLabelDescription
principalsMSPPrincipalrepeatedPrincipals refer to combined principals

MSPIdentityAnonymity

MSPIdentityAnonymity can be used to enforce an identity to be anonymous or nominal.

FieldTypeLabelDescription
anonymity_typeMSPIdentityAnonymity.MSPIdentityAnonymityType

MSPPrincipal

MSPPrincipal aims to represent an MSP-centric set of identities. In particular, this structure allows for definition of

  • a group of identities that are member of the same MSP
  • a group of identities that are member of the same organization unit in the same MSP
  • a group of identities that are administering a specific MSP
  • a specific identity Expressing these groups is done given two fields of the fields below
  • Classification, that defines the type of classification of identities in an MSP this principal would be defined on; Classification can take three values: (i) ByMSPRole: that represents a classification of identities within MSP based on one of the two pre-defined MSP rules, "member" and "admin" (ii) ByOrganizationUnit: that represents a classification of identities within MSP based on the organization unit an identity belongs to (iii)ByIdentity that denotes that MSPPrincipal is mapped to a single identity/certificate; this would mean that the Principal bytes message
FieldTypeLabelDescription
principal_classificationMSPPrincipal.ClassificationClassification describes the way that one should process Principal. An Classification value of "ByOrganizationUnit" reflects that "Principal" contains the name of an organization this MSP handles. A Classification value "ByIdentity" means that "Principal" contains a specific identity. Default value denotes that Principal contains one of the groups by default supported by all MSPs ("admin" or "member").
principalbytesPrincipal completes the policy principal definition. For the default principal types, Principal can be either "Admin" or "Member". For the ByOrganizationUnit/ByIdentity values of Classification, PolicyPrincipal acquires its value from an organization unit or identity, respectively. For the Combined Classification type, the Principal is a marshalled CombinedPrincipal.

MSPRole

MSPRole governs the organization of the Principal field of an MSPPrincipal when it aims to define one of the two dedicated roles within an MSP: Admin and Members.

FieldTypeLabelDescription
msp_identifierstringMSPIdentifier represents the identifier of the MSP this principal refers to
roleMSPRole.MSPRoleTypeMSPRoleType defines which of the available, pre-defined MSP-roles an identiy should posess inside the MSP with identifier MSPidentifier

OrganizationUnit

OrganizationUnit governs the organization of the Principal field of a policy principal when a specific organization unity members are to be defined within a policy principal.

FieldTypeLabelDescription
msp_identifierstringMSPIdentifier represents the identifier of the MSP this organization unit refers to
organizational_unit_identifierstringOrganizationUnitIdentifier defines the organizational unit under the MSP identified with MSPIdentifier
certifiers_identifierbytesCertifiersIdentifier is the hash of certificates chain of trust related to this organizational unit

MSPIdentityAnonymity.MSPIdentityAnonymityType

NameNumberDescription
NOMINAL0Represents a nominal MSP Identity
ANONYMOUS1Represents an anonymous MSP Identity

MSPPrincipal.Classification

NameNumberDescription
ROLE0Represents the one of the dedicated MSP roles, the
ORGANIZATION_UNIT1one of a member of MSP network, and the one of an administrator of an MSP network

Denotes a finer grained (affiliation-based) | | IDENTITY | 2 | groupping of entities, per MSP affiliation E.g., this can well be represented by an MSP's Organization unit

Denotes a principal that consists of a single | | ANONYMITY | 3 | identity

Denotes a principal that can be used to enforce | | COMBINED | 4 | an identity to be anonymous or nominal.

Denotes a combined principal |

MSPRole.MSPRoleType

NameNumberDescription
MEMBER0Represents an MSP Member
ADMIN1Represents an MSP Admin
CLIENT2Represents an MSP Client
PEER3Represents an MSP Peer
ORDERER4Represents an MSP Orderer

Top

msp/identities.proto

SerializedIdemixIdentity

This struct represents an Idemix Identity to be used to serialize it and deserialize it. The IdemixMSP will first serialize an idemix identity to bytes using this proto, and then uses these bytes as id_bytes in SerializedIdentity

FieldTypeLabelDescription
nym_xbytesnym_x is the X-component of the pseudonym elliptic curve point. It is a []byte representation of an amcl.BIG The pseudonym can be seen as a public key of the identity, it is used to verify signatures.
nym_ybytesnym_y is the Y-component of the pseudonym elliptic curve point. It is a []byte representation of an amcl.BIG The pseudonym can be seen as a public key of the identity, it is used to verify signatures.
oubytesou contains the organizational unit of the idemix identity
rolebytesrole contains the role of this identity (e.g., ADMIN or MEMBER)
proofbytesproof contains the cryptographic evidence that this identity is valid

SerializedIdentity

This struct represents an Identity (with its MSP identifier) to be used to serialize it and deserialize it

FieldTypeLabelDescription
mspidstringThe identifier of the associated membership service provider
id_bytesbytesthe Identity, serialized according to the rules of its MPS

Top

ledger/rwset/rwset.proto

CollectionHashedReadWriteSet

CollectionHashedReadWriteSet encapsulate the hashed representation for the private read-write set for a collection

FieldTypeLabelDescription
collection_namestring
hashed_rwsetbytesData model specific serialized proto message (e.g., kvrwset.HashedRWSet for KV and Document data models)
pvt_rwset_hashbytesHash of entire private read-write set for a specific collection. This helps in authenticating the private read-write set efficiently

CollectionPvtReadWriteSet

CollectionPvtReadWriteSet encapsulates the private read-write set for a collection

FieldTypeLabelDescription
collection_namestring
rwsetbytesData model specific serialized proto message (e.g., kvrwset.KVRWSet for KV and Document data models)

NsPvtReadWriteSet

NsPvtReadWriteSet encapsulates the private read-write set for a chaincode

FieldTypeLabelDescription
namespacestring
collection_pvt_rwsetCollectionPvtReadWriteSetrepeated

NsReadWriteSet

NsReadWriteSet encapsulates the read-write set for a chaincode

FieldTypeLabelDescription
namespacestring
rwsetbytesData model specific serialized proto message (e.g., kvrwset.KVRWSet for KV and Document data models)
collection_hashed_rwsetCollectionHashedReadWriteSetrepeated

TxPvtReadWriteSet

TxPvtReadWriteSet encapsulate the private read-write set for a transaction

FieldTypeLabelDescription
data_modelTxReadWriteSet.DataModel
ns_pvt_rwsetNsPvtReadWriteSetrepeated

TxReadWriteSet

TxReadWriteSet encapsulates a read-write set for a transaction DataModel specifies the enum value of the data model ns_rwset field specifies a list of chaincode specific read-write set (one for each chaincode)

FieldTypeLabelDescription
data_modelTxReadWriteSet.DataModel
ns_rwsetNsReadWriteSetrepeated

TxReadWriteSet.DataModel

NameNumberDescription
KV0

Top

ledger/rwset/kvrwset/kv_rwset.proto

HashedRWSet

HashedRWSet encapsulates hashed representation of a private read-write set for KV or Document data model

FieldTypeLabelDescription
hashed_readsKVReadHashrepeated
hashed_writesKVWriteHashrepeated
metadata_writesKVMetadataWriteHashrepeated

KVMetadataEntry

KVMetadataEntry captures a 'name'ed entry in the metadata of a key/key-hash.

FieldTypeLabelDescription
namestring
valuebytes

KVMetadataWrite

KVMetadataWrite captures all the entries in the metadata associated with a key

FieldTypeLabelDescription
keystring
entriesKVMetadataEntryrepeated

KVMetadataWriteHash

KVMetadataWriteHash captures all the upserts to the metadata associated with a key hash

FieldTypeLabelDescription
key_hashbytes
entriesKVMetadataEntryrepeated

KVRWSet

KVRWSet encapsulates the read-write set for a chaincode that operates upon a KV or Document data model This structure is used for both the public data and the private data

FieldTypeLabelDescription
readsKVReadrepeated
range_queries_infoRangeQueryInforepeated
writesKVWriterepeated
metadata_writesKVMetadataWriterepeated

KVRead

KVRead captures a read operation performed during transaction simulation A 'nil' version indicates a non-existing key read by the transaction

FieldTypeLabelDescription
keystring
versionVersion

KVReadHash

KVReadHash is similar to the KVRead in spirit. However, it captures the hash of the key instead of the key itself version is kept as is for now. However, if the version also needs to be privacy-protected, it would need to be the hash of the version and hence of 'bytes' type

FieldTypeLabelDescription
key_hashbytes
versionVersion

KVWrite

KVWrite captures a write (update/delete) operation performed during transaction simulation

FieldTypeLabelDescription
keystring
is_deletebool
valuebytes

KVWriteHash

KVWriteHash is similar to the KVWrite. It captures a write (update/delete) operation performed during transaction simulation

FieldTypeLabelDescription
key_hashbytes
is_deletebool
value_hashbytes

QueryReads

QueryReads encapsulates the KVReads for the items read by a transaction as a result of a query execution

FieldTypeLabelDescription
kv_readsKVReadrepeated

QueryReadsMerkleSummary

QueryReadsMerkleSummary encapsulates the Merkle-tree hashes for the QueryReads This allows to reduce the size of RWSet in the presence of query results by storing certain hashes instead of actual results. maxDegree field refers to the maximum number of children in the tree at any level maxLevel field contains the lowest level which has lesser nodes than maxDegree (starting from leaf level)

FieldTypeLabelDescription
max_degreeuint32
max_leveluint32
max_level_hashesbytesrepeated

RangeQueryInfo

RangeQueryInfo encapsulates the details of a range query performed by a transaction during simulation. This helps protect transactions from phantom reads by varifying during validation whether any new items got committed within the given range between transaction simuation and validation (in addition to regular checks for updates/deletes of the existing items). readInfo field contains either the KVReads (for the items read by the range query) or a merkle-tree hash if the KVReads exceeds a pre-configured numbers

FieldTypeLabelDescription
start_keystring
end_keystring
itr_exhaustedbool
raw_readsQueryReads
reads_merkle_hashesQueryReadsMerkleSummary

Version

Version encapsulates the version of a Key A version of a committed key is maintained as the height of the transaction that committed the key. The height is represenetd as a tuple <blockNum, txNum> where the txNum is the position of the transaction (starting with 0) within block

FieldTypeLabelDescription
block_numuint64
tx_numuint64

Top

ledger/queryresult/kv_query_result.proto

KV

KV -- QueryResult for range/execute query. Holds a key and corresponding value.

FieldTypeLabelDescription
namespacestring
keystring
valuebytes

KeyModification

KeyModification -- QueryResult for history query. Holds a transaction ID, value, timestamp, and delete marker which resulted from a history query.

FieldTypeLabelDescription
tx_idstring
valuebytes
timestampgoogle.protobuf.Timestamp
is_deletebool

Top

discovery/protocol.proto

AuthInfo

AuthInfo aggregates authentication information that the server uses to authenticate the client

FieldTypeLabelDescription
client_identitybytesThis is the identity of the client that is used to verify the signature on the SignedRequest's payload. It is a msp.SerializedIdentity in bytes form
client_tls_cert_hashbytesThis is the hash of the client's TLS cert. When the network is running with TLS, clients that don't include a certificate will be denied access to the service. Since the Request is encapsulated with a SignedRequest (which is signed), this binds the TLS session to the enrollement identity of the client and therefore both authenticates the client to the server, and also prevents the server from relaying the request message to another server.

ChaincodeCall

ChaincodeCall defines a call to a chaincode. It may have collections that are related to the chaincode

FieldTypeLabelDescription
namestring
collection_namesstringrepeated

ChaincodeInterest

ChaincodeInterest defines an interest about an endorsement for a specific single chaincode invocation. Multiple chaincodes indicate chaincode to chaincode invocations.

FieldTypeLabelDescription
chaincodesChaincodeCallrepeated

ChaincodeQuery

ChaincodeQuery requests ChaincodeQueryResults for a given list of chaincode invocations. Each invocation is a separate one, and the endorsement policy is evaluated independantly for each given interest.

FieldTypeLabelDescription
interestsChaincodeInterestrepeated

ChaincodeQueryResult

ChaincodeQueryResult contains EndorsementDescriptors for chaincodes

FieldTypeLabelDescription
contentEndorsementDescriptorrepeated

ConfigQuery

ConfigQuery requests a ConfigResult

ConfigResult

FieldTypeLabelDescription
mspsConfigResult.MspsEntryrepeatedmsps is a map from MSP_ID to FabricMSPConfig
orderersConfigResult.OrderersEntryrepeatedorderers is a map from MSP_ID to endpoint lists of orderers

ConfigResult.MspsEntry

FieldTypeLabelDescription
keystring
valuemsp.FabricMSPConfig

ConfigResult.OrderersEntry

FieldTypeLabelDescription
keystring
valueEndpoints

EndorsementDescriptor

EndorsementDescriptor contains information about which peers can be used to request endorsement from, such that the endorsement policy would be fulfilled. Here is how to compute a set of peers to ask an endorsement from, given an EndorsementDescriptor: Let e: G --> P be the endorsers_by_groups field that maps a group to a set of peers. Note that applying e on a group g yields a set of peers.

  1. Select a layout l: G --> N out of the layouts given. l is the quantities_by_group field of a Layout, and it maps a group to an integer.
  2. R = {} (an empty set of peers)
  3. For each group g in the layout l, compute n = l(g) 3.1) Denote P_g as a set of n random peers {p0, p1, ... p_n} selected from e(g) 3.2) R = R U P_g (add P_g to R)
  4. The set of peers R is the peers the client needs to request endorsements from
FieldTypeLabelDescription
chaincodestring
endorsers_by_groupsEndorsementDescriptor.EndorsersByGroupsEntryrepeatedSpecifies the endorsers, separated to groups.
layoutsLayoutrepeatedSpecifies options of fulfulling the endorsement policy. Each option lists the group names, and the amount of signatures needed from each group.

EndorsementDescriptor.EndorsersByGroupsEntry

FieldTypeLabelDescription
keystring
valuePeers

Endpoint

Endpoint is a combination of a host and a port

FieldTypeLabelDescription
hoststring
portuint32

Endpoints

Endpoints is a list of Endpoint(s)

FieldTypeLabelDescription
endpointEndpointrepeated

Error

Error denotes that something went wrong and contains the error message

FieldTypeLabelDescription
contentstring

Layout

Layout contains a mapping from a group name to number of peers that are needed for fulfilling an endorsement policy

FieldTypeLabelDescription
quantities_by_groupLayout.QuantitiesByGroupEntryrepeatedSpecifies how many non repeated signatures of each group are needed for endorsement

Layout.QuantitiesByGroupEntry

FieldTypeLabelDescription
keystring
valueuint32

LocalPeerQuery

LocalPeerQuery queries for peers in a non channel context

Peer

Peer contains information about the peer such as its channel specific state, and membership information.

FieldTypeLabelDescription
state_infogossip.EnvelopeThis is an Envelope of a GossipMessage with a gossip.StateInfo message
membership_infogossip.EnvelopeThis is an Envelope of a GossipMessage with a gossip.AliveMessage message
identitybytesThis is the msp.SerializedIdentity of the peer, represented in bytes.

PeerMembershipQuery

PeerMembershipQuery requests PeerMembershipResult. The filter field may be optionally populated in order for the peer membership to be filtered according to chaincodes that are installed on peers and collection access control policies.

FieldTypeLabelDescription
filterChaincodeInterest

PeerMembershipResult

PeerMembershipResult contains peers mapped by their organizations (MSP_ID)

FieldTypeLabelDescription
peers_by_orgPeerMembershipResult.PeersByOrgEntryrepeated

PeerMembershipResult.PeersByOrgEntry

FieldTypeLabelDescription
keystring
valuePeers

Peers

Peers contains a list of Peer(s)

FieldTypeLabelDescription
peersPeerrepeated

Query

Query asks for information in the context of a specific channel

FieldTypeLabelDescription
channelstring
config_queryConfigQueryConfigQuery is used to query for the configuration of the channel, such as FabricMSPConfig, and rorderer endpoints. The client has to query a peer it trusts as it doesn't have means to self-verify the authenticity of the returned result. The result is returned in the form of ConfigResult.
peer_queryPeerMembershipQueryPeerMembershipQuery queries for peers in a channel context, and returns PeerMembershipResult
cc_queryChaincodeQueryChaincodeQuery queries for chaincodes by their name and version. An empty version means any version can by returned.
local_peersLocalPeerQueryLocalPeerQuery queries for peers in a non channel context, and returns PeerMembershipResult

QueryResult

QueryResult contains a result for a given Query. The corresponding Query can be inferred by the index of the QueryResult from its enclosing Response message. QueryResults are ordered in the same order as the Queries are ordered in their enclosing Request.

FieldTypeLabelDescription
errorErrorError indicates failure or refusal to process the query
config_resultConfigResultConfigResult contains the configuration of the channel, such as FabricMSPConfig and orderer endpoints
cc_query_resChaincodeQueryResultChaincodeQueryResult contains information about chaincodes, and their corresponding endorsers
membersPeerMembershipResultPeerMembershipResult contains information about peers, such as their identity, endpoints, and channel related state.

Request

Request contains authentication info about the client that sent the request and the queries it wishes to query the service

FieldTypeLabelDescription
authenticationAuthInfoauthentication contains information that the service uses to check the client's eligibility for the queries.
queriesQueryrepeatedqueries

Response

FieldTypeLabelDescription
resultsQueryResultrepeatedThe results are returned in the same order of the queries

SignedRequest

SignedRequest contains a serialized Request in the payload field and a signature. The identity that is used to verify the signature can be extracted from the authentication field of type AuthInfo in the Request itself after deserializing it.

FieldTypeLabelDescription
payloadbytes
signaturebytes

Discovery

Discovery defines a service that serves information about the fabric network like which peers, orderers, chaincodes, etc.

Method NameRequest TypeResponse TypeDescription
DiscoverSignedRequestResponseDiscover receives a signed request, and returns a response.

Top

orderer/configuration.proto

BatchSize

FieldTypeLabelDescription
max_message_countuint32Simply specified as number of messages for now, in the future we may want to allow this to be specified by size in bytes
absolute_max_bytesuint32The byte count of the serialized messages in a batch cannot exceed this value.
preferred_max_bytesuint32The byte count of the serialized messages in a batch should not exceed this value.

BatchTimeout

FieldTypeLabelDescription
timeoutstringAny duration string parseable by ParseDuration(): https://golang.org/pkg/time/#ParseDuration

ChannelRestrictions

ChannelRestrictions is the mssage which conveys restrictions on channel creation for an orderer

FieldTypeLabelDescription
max_countuint64The max count of channels to allow to be created, a value of 0 indicates no limit

ConsensusType

FieldTypeLabelDescription
typestringThe consensus type: "solo", "kafka" or "etcdraft".
metadatabytesOpaque metadata, dependent on the consensus type.
stateConsensusType.StateThe state signals the ordering service to go into maintenance mode, typically for consensus-type migration.

KafkaBrokers

Carries a list of bootstrap brokers, i.e. this is not the exclusive set of brokers an ordering service

FieldTypeLabelDescription
brokersstringrepeatedEach broker here should be identified using the (IP

ConsensusType.State

State defines the orderer mode of operation, typically for consensus-type migration. NORMAL is during normal operation, when consensus-type migration is not, and can not, take place. MAINTENANCE is when the consensus-type can be changed.

NameNumberDescription
STATE_NORMAL0
STATE_MAINTENANCE1

Top

orderer/kafka.proto

KafkaMessage

KafkaMessage is a wrapper type for the messages that the Kafka-based orderer deals with.

FieldTypeLabelDescription
regularKafkaMessageRegular
time_to_cutKafkaMessageTimeToCut
connectKafkaMessageConnect

KafkaMessageConnect

KafkaMessageConnect is posted by an orderer upon booting up. It is used to prevent the panic that would be caused if we were to consume an empty partition. It is ignored by all orderers when processing the partition.

FieldTypeLabelDescription
payloadbytes

KafkaMessageRegular

KafkaMessageRegular wraps a marshalled envelope.

FieldTypeLabelDescription
payloadbytes
config_sequint64
classKafkaMessageRegular.Class
original_offsetint64

KafkaMessageTimeToCut

KafkaMessageTimeToCut is used to signal to the orderers that it is time to cut block <block_number>.

FieldTypeLabelDescription
block_numberuint64

KafkaMetadata

KafkaMetadata is encoded into the ORDERER block to keep track of Kafka-related metadata associated with this block.

FieldTypeLabelDescription
last_offset_persistedint64LastOffsetPersisted is the encoded value for the Metadata message which is encoded in the ORDERER block metadata index for the case of the Kafka-based orderer.
last_original_offset_processedint64LastOriginalOffsetProcessed is used to keep track of the newest offset processed if a message is re-validated and re-ordered. This value is used to deduplicate re-submitted messages from multiple orderer so that we don't bother re-processing it again.
last_resubmitted_config_offsetint64LastResubmittedConfigOffset is used to capture the newest offset of CONFIG kafka message, which is revalidated and resubmitted. By comparing this with LastOriginalOffsetProcessed, we could detemine whether there are still CONFIG messages that have been resubmitted but NOT processed yet. It's used as condition to block ingress messages, so we could reduce the overhead of repeatedly resubmitting messages as config seq keeps advancing.

KafkaMessageRegular.Class

NameNumberDescription
UNKNOWN0
NORMAL1
CONFIG2

Top

orderer/ab.proto

BroadcastResponse

FieldTypeLabelDescription
statuscommon.StatusStatus code, which may be used to programatically respond to success/failure
infostringInfo string which may contain additional information about the status returned

DeliverResponse

FieldTypeLabelDescription
statuscommon.Status
blockcommon.Block

SeekInfo

SeekInfo specifies the range of requested blocks to return If the start position is not found, an error is immediately returned Otherwise, blocks are returned until a missing block is encountered, then behavior is dictated by the SeekBehavior specified.

FieldTypeLabelDescription
startSeekPositionThe position to start the deliver from
stopSeekPositionThe position to stop the deliver
behaviorSeekInfo.SeekBehaviorThe behavior when a missing block is encountered
error_responseSeekInfo.SeekErrorResponseHow to respond to errors reported to the deliver service

SeekNewest

SeekOldest

SeekPosition

FieldTypeLabelDescription
newestSeekNewest
oldestSeekOldest
specifiedSeekSpecified

SeekSpecified

FieldTypeLabelDescription
numberuint64

SeekInfo.SeekBehavior

If BLOCK_UNTIL_READY is specified, the reply will block until the requested blocks are available, if FAIL_IF_NOT_READY is specified, the reply will return an error indicating that the block is not found. To request that all blocks be returned indefinitely as they are created, behavior should be set to BLOCK_UNTIL_READY and the stop should be set to specified with a number of MAX_UINT64

NameNumberDescription
BLOCK_UNTIL_READY0
FAIL_IF_NOT_READY1

SeekInfo.SeekErrorResponse

SeekErrorTolerance indicates to the server how block provider errors should be tolerated. By default, if the deliver service detects a problem in the underlying block source (typically, in the orderer, a consenter error), it will begin to reject deliver requests. This is to prevent a client from waiting for blocks from an orderer which is stuck in an errored state. This is almost always the desired behavior and clients should stick with the default STRICT checking behavior. However, in some scenarios, particularly when attempting to recover from a crash or other corruption, it's desirable to force an orderer to respond with blocks on a best effort basis, even if the backing consensus implementation is in an errored state. In this case, set the SeekErrorResponse to BEST_EFFORT to ignore the consenter errors.

NameNumberDescription
STRICT0
BEST_EFFORT1

AtomicBroadcast

Method NameRequest TypeResponse TypeDescription
Broadcast.common.Envelope streamBroadcastResponse streambroadcast receives a reply of Acknowledgement for each common.Envelope in order, indicating success or type of failure
Deliver.common.Envelope streamDeliverResponse streamdeliver first requires an Envelope of type DELIVER_SEEK_INFO with Payload data as a mashaled SeekInfo message, then a stream of block replies is received.

Top

orderer/cluster.proto

ConsensusRequest

ConsensusRequest is a consensus specific message sent to a cluster member.

FieldTypeLabelDescription
channelstring
payloadbytes
metadatabytes

StepRequest

StepRequest wraps a message that is sent to a cluster member.

FieldTypeLabelDescription
consensus_requestConsensusRequestconsensus_request is a consensus specific message.
submit_requestSubmitRequestsubmit_request is a relay of a transaction.

StepResponse

StepResponse is a message received from a cluster member.

FieldTypeLabelDescription
submit_resSubmitResponse

SubmitRequest

SubmitRequest wraps a transaction to be sent for ordering.

FieldTypeLabelDescription
channelstring
last_validation_sequint64last_validation_seq denotes the last configuration sequence at which the sender validated this message.
payloadcommon.Envelopecontent is the fabric transaction that is forwarded to the cluster member.

SubmitResponse

SubmitResponse returns a success or failure status to the sender.

FieldTypeLabelDescription
channelstring
statuscommon.StatusStatus code, which may be used to programatically respond to success/failure.
infostringInfo string which may contain additional information about the returned status.

Cluster

Cluster defines communication between cluster members.

Method NameRequest TypeResponse TypeDescription
StepStepRequest streamStepResponse streamStep passes an implementation-specific message to another cluster member.

Top

orderer/etcdraft/configuration.proto

ConfigMetadata

ConfigMetadata is serialized and set as the value of ConsensusType.Metadata in a channel configuration when the ConsensusType.Type is set "etcdraft".

FieldTypeLabelDescription
consentersConsenterrepeated
optionsOptions

Consenter

Consenter represents a consenting node (i.e. replica).

FieldTypeLabelDescription
hoststring
portuint32
client_tls_certbytes
server_tls_certbytes

Options

Options to be specified for all the etcd/raft nodes. These can be modified on a per-channel basis.

FieldTypeLabelDescription
tick_intervalstringtime duration format, e.g. 500ms
election_tickuint32
heartbeat_tickuint32
max_inflight_blocksuint32
snapshot_interval_sizeuint32Take snapshot when cumulative data exceeds certain size in bytes.

Top

orderer/etcdraft/metadata.proto

BlockMetadata

BlockMetadata stores data used by the Raft OSNs when coordinating with each other, to be serialized into block meta dta field and used after failres and restarts.

FieldTypeLabelDescription
consenter_idsuint64repeatedMaintains a mapping between the cluster's OSNs and their Raft IDs.
next_consenter_iduint64Carries the Raft ID value that will be assigned to the next OSN that will join this cluster.
raft_indexuint64Index of etcd/raft entry for current block.

ClusterMetadata

ClusterMetadata encapsulates metadata that is exchanged among cluster nodes

FieldTypeLabelDescription
active_nodesuint64repeatedIndicates active nodes in cluster that are reacheable by Raft leader

Top

gossip/message.proto

Acknowledgement

FieldTypeLabelDescription
errorstring

AliveMessage

AliveMessage is sent to inform remote peers of a peer's existence and activity

FieldTypeLabelDescription
membershipMember
timestampPeerTime
identitybytes

Chaincode

Chaincode represents a Chaincode that is installed on a peer

FieldTypeLabelDescription
namestring
versionstring
metadatabytes

ConnEstablish

ConnEstablish is the message used for the gossip handshake Whenever a peer connects to another peer, it handshakes with it by sending this message that proves its identity

FieldTypeLabelDescription
pki_idbytes
identitybytes
tls_cert_hashbytes

DataDigest

DataDigest is the message sent from the receiver peer to the initator peer and contains the data items it has

FieldTypeLabelDescription
nonceuint64
digestsbytesrepeatedMaybe change this to bitmap later on
msg_typePullMsgType

DataMessage

DataMessage is the message that contains a block

FieldTypeLabelDescription
payloadPayload

DataRequest

DataRequest is a message used for a peer to request certain data blocks from a remote peer

FieldTypeLabelDescription
nonceuint64
digestsbytesrepeated
msg_typePullMsgType

DataUpdate

DataUpdate is the final message in the pull phase sent from the receiver to the initiator

FieldTypeLabelDescription
nonceuint64
dataEnveloperepeated
msg_typePullMsgType

Empty

Empty is used for pinging and in tests

Envelope

Envelope contains a marshalled GossipMessage and a signature over it. It may also contain a SecretEnvelope which is a marshalled Secret

FieldTypeLabelDescription
payloadbytes
signaturebytes
secret_envelopeSecretEnvelope

GossipHello

GossipHello is the message that is used for the peer to initiate a pull round with another peer

FieldTypeLabelDescription
nonceuint64
metadatabytes
msg_typePullMsgType

GossipMessage

GossipMessage defines the message sent in a gossip network

FieldTypeLabelDescription
nonceuint64used mainly for testing, but will might be used in the future for ensuring message delivery by acking
channelbytesThe channel of the message. Some GossipMessages may set this to nil, because they are cross-channels but some may not
tagGossipMessage.Tagdetermines to which peers it is allowed to forward the message
alive_msgAliveMessageMembership
mem_reqMembershipRequest
mem_resMembershipResponse
data_msgDataMessageContains a ledger block
helloGossipHelloUsed for push&pull
data_digDataDigest
data_reqDataRequest
data_updateDataUpdate
emptyEmptyEmpty message, used for pinging
connConnEstablishConnEstablish, used for establishing a connection
state_infoStateInfoUsed for relaying information about state
state_snapshotStateInfoSnapshotUsed for sending sets of StateInfo messages
state_info_pull_reqStateInfoPullRequestUsed for asking for StateInfoSnapshots
state_requestRemoteStateRequestUsed to ask from a remote peer a set of blocks
state_responseRemoteStateResponseUsed to send a set of blocks to a remote peer
leadership_msgLeadershipMessageUsed to indicate intent of peer to become leader
peer_identityPeerIdentityUsed to learn of a peer's certificate
ackAcknowledgement
privateReqRemotePvtDataRequestUsed to request private data
privateResRemotePvtDataResponseUsed to respond to private data requests
private_dataPrivateDataMessageEncapsulates private data used to distribute private rwset after the endorsement

LeadershipMessage

Leadership Message is sent during leader election to inform remote peers about intent of peer to proclaim itself as leader

FieldTypeLabelDescription
pki_idbytes
timestampPeerTime
is_declarationbool

Member

Member holds membership-related information about a peer

FieldTypeLabelDescription
endpointstring
metadatabytes
pki_idbytes

MembershipRequest

MembershipRequest is used to ask membership information from a remote peer

FieldTypeLabelDescription
self_informationEnvelope
knownbytesrepeated

MembershipResponse

MembershipResponse is used for replying to MembershipRequests

FieldTypeLabelDescription
aliveEnveloperepeated
deadEnveloperepeated

Payload

Payload contains a block

FieldTypeLabelDescription
seq_numuint64
databytes
private_databytesrepeated

PeerIdentity

PeerIdentity defines the identity of the peer Used to make other peers learn of the identity of a certain peer

FieldTypeLabelDescription
pki_idbytes
certbytes
metadatabytes

PeerTime

PeerTime defines the logical time of a peer's life

FieldTypeLabelDescription
inc_numuint64
seq_numuint64

PrivateDataMessage

PrivateDataMessage message which includes private data information to distributed once transaction has been endorsed

FieldTypeLabelDescription
payloadPrivatePayload

PrivatePayload

PrivatePayload payload to encapsulate private data with collection name to enable routing based on collection partitioning

FieldTypeLabelDescription
collection_namestring
namespacestring
tx_idstring
private_rwsetbytes
private_sim_heightuint64
collection_configscommon.CollectionConfigPackage

Properties

FieldTypeLabelDescription
ledger_heightuint64
left_channelbool
chaincodesChaincoderepeated

PvtDataDigest

PvtDataDigest defines a digest of private data

FieldTypeLabelDescription
tx_idstring
namespacestring
collectionstring
block_sequint64
seq_in_blockuint64

PvtDataElement

FieldTypeLabelDescription
digestPvtDataDigest
payloadbytesrepeatedthe payload is a marshaled kvrwset.KVRWSet

PvtDataPayload

PvtPayload augments private rwset data and tx index inside the block

FieldTypeLabelDescription
tx_seq_in_blockuint64
payloadbytesEncodes marhslaed bytes of rwset.TxPvtReadWriteSet defined in rwset.proto

RemotePvtDataRequest

RemotePrivateDataRequest message used to request missing private rwset

FieldTypeLabelDescription
digestsPvtDataDigestrepeated

RemotePvtDataResponse

RemotePrivateData message to response on private data replication request

FieldTypeLabelDescription
elementsPvtDataElementrepeated

RemoteStateRequest

RemoteStateRequest is used to ask a set of blocks from a remote peer

FieldTypeLabelDescription
start_seq_numuint64
end_seq_numuint64

RemoteStateResponse

RemoteStateResponse is used to send a set of blocks to a remote peer

FieldTypeLabelDescription
payloadsPayloadrepeated

Secret

Secret is an entity that might be omitted from an Envelope when the remote peer that is receiving the Envelope shouldn't know the secret's content.

FieldTypeLabelDescription
internalEndpointstring

SecretEnvelope

SecretEnvelope is a marshalled Secret and a signature over it. The signature should be validated by the peer that signed the Envelope the SecretEnvelope came with

FieldTypeLabelDescription
payloadbytes
signaturebytes

StateInfo

StateInfo is used for a peer to relay its state information to other peers

FieldTypeLabelDescription
timestampPeerTime
pki_idbytes
channel_MACbyteschannel_MAC is an authentication code that proves that the peer that sent this message knows the name of the channel.
propertiesProperties

StateInfoPullRequest

StateInfoPullRequest is used to fetch a StateInfoSnapshot from a remote peer

FieldTypeLabelDescription
channel_MACbyteschannel_MAC is an authentication code that proves that the peer that sent this message knows the name of the channel.

StateInfoSnapshot

StateInfoSnapshot is an aggregation of StateInfo messages

FieldTypeLabelDescription
elementsEnveloperepeated

GossipMessage.Tag

NameNumberDescription
UNDEFINED0
EMPTY1
ORG_ONLY2
CHAN_ONLY3
CHAN_AND_ORG4
CHAN_OR_ORG5

PullMsgType

NameNumberDescription
UNDEFINED0
BLOCK_MSG1
IDENTITY_MSG2

Gossip

Gossip

Method NameRequest TypeResponse TypeDescription
GossipStreamEnvelope streamEnvelope streamGossipStream is the gRPC stream used for sending and receiving messages
PingEmptyEmptyPing is used to probe a remote peer's aliveness

Top

transientstore/transientstore.proto

TxPvtReadWriteSetWithConfigInfo

TxPvtReadWriteSetWithConfigInfo encapsulates the transaction's private read-write set and additional information about the configurations such as the latest collection config when the transaction is simulated

FieldTypeLabelDescription
endorsed_atuint64
pvt_rwsetrwset.TxPvtReadWriteSet
collection_configsTxPvtReadWriteSetWithConfigInfo.CollectionConfigsEntryrepeated

TxPvtReadWriteSetWithConfigInfo.CollectionConfigsEntry

FieldTypeLabelDescription
keystring
valuecommon.CollectionConfigPackage

Top

common/configuration.proto

BlockDataHashingStructure

BlockDataHashingStructure is encoded into the configuration transaction as a configuration item of type Chain with a Key of "BlockDataHashingStructure" and a Value of HashingAlgorithm as marshaled protobuf bytes

FieldTypeLabelDescription
widthuint32width specifies the width of the Merkle tree to use when computing the BlockDataHash in order to replicate flat hashing, set this width to MAX_UINT32

Capabilities

Capabilities message defines the capabilities a particular binary must implement for that binary to be able to safely participate in the channel. The capabilities message is defined at the /Channel level, the /Channel/Application level, and the /Channel/Orderer level.

The /Channel level capabilties define capabilities which both the orderer and peer binaries must satisfy. These capabilties might be things like a new MSP type, or a new policy type.

The /Channel/Orderer level capabilties define capabilities which must be supported by the orderer, but which have no bearing on the behavior of the peer. For instance if the orderer changes the logic for how it constructs new channels, only all orderers must agree on the new logic. The peers do not need to be aware of this change as they only interact with the channel after it has been constructed.

Finally, the /Channel/Application level capabilities define capabilities which the peer binary must satisfy, but which have no bearing on the orderer. For instance, if the peer adds a new UTXO transaction type, or changes the chaincode lifecycle requirements, all peers must agree on the new logic. However, orderers never inspect transactions this deeply, and therefore have no need to be aware of the change.

The capabilities strings defined in these messages typically correspond to release binary versions (e.g. "V1.1"), and are used primarilly as a mechanism for a fully upgraded network to switch from one set of logic to a new one.

Although for V1.1, the orderers must be upgraded to V1.1 prior to the rest of the network, going forward, because of the split between the /Channel, /Channel/Orderer and /Channel/Application capabilities. It should be possible for the orderer and application networks to upgrade themselves independently (with the exception of any new capabilities defined at the /Channel level).

FieldTypeLabelDescription
capabilitiesCapabilities.CapabilitiesEntryrepeated

Capabilities.CapabilitiesEntry

FieldTypeLabelDescription
keystring
valueCapability

Capability

Capability is an empty message for the time being. It is defined as a protobuf message rather than a constant, so that we may extend capabilities with other fields if the need arises in the future. For the time being, a capability being in the capabilities map requires that that capability be supported.

Consortium

Consortium represents the consortium context in which the channel was created

FieldTypeLabelDescription
namestring

HashingAlgorithm

HashingAlgorithm is encoded into the configuration transaction as a configuration item of type Chain with a Key of "HashingAlgorithm" and a Value of HashingAlgorithm as marshaled protobuf bytes

FieldTypeLabelDescription
namestringCurrently supported algorithms are: SHAKE256

OrdererAddresses

OrdererAddresses is encoded into the configuration transaction as a configuration item of type Chain with a Key of "OrdererAddresses" and a Value of OrdererAddresses as marshaled protobuf bytes

FieldTypeLabelDescription
addressesstringrepeated

Top

common/ledger.proto

BlockchainInfo

Contains information about the blockchain ledger such as height, current block hash, and previous block hash.

FieldTypeLabelDescription
heightuint64
currentBlockHashbytes
previousBlockHashbytes

Top

common/policies.proto

ImplicitMetaPolicy

ImplicitMetaPolicy is a policy type which depends on the hierarchical nature of the configuration It is implicit because the rule is generate implicitly based on the number of sub policies It is meta because it depends only on the result of other policies When evaluated, this policy iterates over all immediate child sub-groups, retrieves the policy of name sub_policy, evaluates the collection and applies the rule. For example, with 4 sub-groups, and a policy name of "foo", ImplicitMetaPolicy retrieves each sub-group, retrieves policy "foo" for each subgroup, evaluates it, and, in the case of ANY 1 satisfied is sufficient, ALL would require 4 signatures, and MAJORITY would require 3 signatures.

FieldTypeLabelDescription
sub_policystring
ruleImplicitMetaPolicy.Rule

Policy

Policy expresses a policy which the orderer can evaluate, because there has been some desire expressed to support multiple policy engines, this is typed as a oneof for now

FieldTypeLabelDescription
typeint32For outside implementors, consider the first 1000 types reserved, otherwise one of PolicyType
valuebytes

SignaturePolicy

SignaturePolicy is a recursive message structure which defines a featherweight DSL for describing policies which are more complicated than 'exactly this signature'. The NOutOf operator is sufficent to express AND as well as OR, as well as of course N out of the following M policies SignedBy implies that the signature is from a valid certificate which is signed by the trusted authority specified in the bytes. This will be the certificate itself for a self-signed certificate and will be the CA for more traditional certificates

FieldTypeLabelDescription
signed_byint32
n_out_ofSignaturePolicy.NOutOf

SignaturePolicy.NOutOf

FieldTypeLabelDescription
nint32
rulesSignaturePolicyrepeated

SignaturePolicyEnvelope

SignaturePolicyEnvelope wraps a SignaturePolicy and includes a version for future enhancements

FieldTypeLabelDescription
versionint32
ruleSignaturePolicy
identitiesMSPPrincipalrepeated

ImplicitMetaPolicy.Rule

NameNumberDescription
ANY0Requires any of the sub-policies be satisfied, if no sub-policies exist, always returns true
ALL1Requires all of the sub-policies be satisfied
MAJORITY2Requires a strict majority (greater than half) of the sub-policies be satisfied

Policy.PolicyType

NameNumberDescription
UNKNOWN0Reserved to check for proper initialization
SIGNATURE1
MSP2
IMPLICIT_META3

Top

common/configtx.proto

Config

Config represents the config for a particular channel

FieldTypeLabelDescription
sequenceuint64
channel_groupConfigGroupchannel_group is a bad name for this, it should be changed to root when API breakage is allowed

ConfigEnvelope

ConfigEnvelope is designed to contain all configuration for a chain with no dependency on previous configuration transactions.

It is generated with the following scheme:

  1. Retrieve the existing configuration
  2. Note the config properties (ConfigValue, ConfigPolicy, ConfigGroup) to be modified
  3. Add any intermediate ConfigGroups to the ConfigUpdate.read_set (sparsely)
  4. Add any additional desired dependencies to ConfigUpdate.read_set (sparsely)
  5. Modify the config properties, incrementing each version by 1, set them in the ConfigUpdate.write_set Note: any element not modified but specified should already be in the read_set, so may be specified sparsely
  6. Create ConfigUpdate message and marshal it into ConfigUpdateEnvelope.update and encode the required signatures a) Each signature is of type ConfigSignature b) The ConfigSignature signature is over the concatenation of signature_header and the ConfigUpdate bytes (which includes a ChainHeader)
  7. Submit new Config for ordering in Envelope signed by submitter a) The Envelope Payload has data set to the marshaled ConfigEnvelope b) The Envelope Payload has a header of type Header.Type.CONFIG_UPDATE

The configuration manager will verify:

  1. All items in the read_set exist at the read versions
  2. All items in the write_set at a different version than, or not in, the read_set have been appropriately signed according to their mod_policy
  3. The new configuration satisfies the ConfigSchema
FieldTypeLabelDescription
configConfigA marshaled Config structure
last_updateEnvelopeThe last CONFIG_UPDATE message which generated this current configuration

ConfigGroup

ConfigGroup is the hierarchical data structure for holding config

FieldTypeLabelDescription
versionuint64
groupsConfigGroup.GroupsEntryrepeated
valuesConfigGroup.ValuesEntryrepeated
policiesConfigGroup.PoliciesEntryrepeated
mod_policystring

ConfigGroup.GroupsEntry

FieldTypeLabelDescription
keystring
valueConfigGroup

ConfigGroup.PoliciesEntry

FieldTypeLabelDescription
keystring
valueConfigPolicy

ConfigGroup.ValuesEntry

FieldTypeLabelDescription
keystring
valueConfigValue

ConfigGroupSchema

FieldTypeLabelDescription
groupsConfigGroupSchema.GroupsEntryrepeated
valuesConfigGroupSchema.ValuesEntryrepeated
policiesConfigGroupSchema.PoliciesEntryrepeated

ConfigGroupSchema.GroupsEntry

FieldTypeLabelDescription
keystring
valueConfigGroupSchema

ConfigGroupSchema.PoliciesEntry

FieldTypeLabelDescription
keystring
valueConfigPolicySchema

ConfigGroupSchema.ValuesEntry

FieldTypeLabelDescription
keystring
valueConfigValueSchema

ConfigPolicy

FieldTypeLabelDescription
versionuint64
policyPolicy
mod_policystring

ConfigPolicySchema

ConfigSignature

FieldTypeLabelDescription
signature_headerbytesA marshaled SignatureHeader
signaturebytesSignature over the concatenation signatureHeader bytes and config bytes

ConfigUpdate

ConfigUpdate is used to submit a subset of config and to have the orderer apply to Config it is always submitted inside a ConfigUpdateEnvelope which allows the addition of signatures resulting in a new total configuration. The update is applied as follows:

  1. The versions from all of the elements in the read_set is verified against the versions in the existing config. If there is a mismatch in the read versions, then the config update fails and is rejected.
  2. Any elements in the write_set with the same version as the read_set are ignored.
  3. The corresponding mod_policy for every remaining element in the write_set is collected.
  4. Each policy is checked against the signatures from the ConfigUpdateEnvelope, any failing to verify are rejected
  5. The write_set is applied to the Config and the ConfigGroupSchema verifies that the updates were legal
FieldTypeLabelDescription
channel_idstringWhich channel this config update is for
read_setConfigGroupReadSet explicitly lists the portion of the config which was read, this should be sparse with only Version set
write_setConfigGroupWriteSet lists the portion of the config which was written, this should included updated Versions
isolated_dataConfigUpdate.IsolatedDataEntryrepeatedData which is not to be reflected in the resulting Config, but is still needed for some other purpose. For instance, rscc_seed_data

ConfigUpdate.IsolatedDataEntry

FieldTypeLabelDescription
keystring
valuebytes

ConfigUpdateEnvelope

FieldTypeLabelDescription
config_updatebytesA marshaled ConfigUpdate structure
signaturesConfigSignaturerepeatedSignatures over the config_update

ConfigValue

ConfigValue represents an individual piece of config data

FieldTypeLabelDescription
versionuint64
valuebytes
mod_policystring

ConfigValueSchema

Top

common/common.proto

Block

This is finalized block structure to be shared among the orderer and peer Note that the BlockHeader chains to the previous BlockHeader, and the BlockData hash is embedded in the BlockHeader. This makes it natural and obvious that the Data is included in the hash, but the Metadata is not.

FieldTypeLabelDescription
headerBlockHeader
dataBlockData
metadataBlockMetadata

BlockData

FieldTypeLabelDescription
databytesrepeated

BlockHeader

BlockHeader is the element of the block which forms the block chain The block header is hashed using the configured chain hashing algorithm over the ASN.1 encoding of the BlockHeader

FieldTypeLabelDescription
numberuint64The position in the blockchain
previous_hashbytesThe hash of the previous block header
data_hashbytesThe hash of the BlockData, by MerkleTree

BlockMetadata

FieldTypeLabelDescription
metadatabytesrepeated

ChannelHeader

Header is a generic replay prevention and identity message to include in a signed payload

FieldTypeLabelDescription
typeint32Header types 0-10000 are reserved and defined by HeaderType
versionint32Version indicates message protocol version
timestampgoogle.protobuf.TimestampTimestamp is the local time when the message was created by the sender
channel_idstringIdentifier of the channel this message is bound for
tx_idstringAn unique identifier that is used end-to-end. - set by higher layers such as end user or SDK - passed to the endorser (which will check for uniqueness) - as the header is passed along unchanged, it will be be retrieved by the committer (uniqueness check here as well) - to be stored in the ledger
epochuint64The epoch in which this header was generated, where epoch is defined based on block height Epoch in which the response has been generated. This field identifies a logical window of time. A proposal response is accepted by a peer only if two conditions hold: 1. the epoch specified in the message is the current epoch 2. this message has been only seen once during this epoch (i.e. it hasn't been replayed)
extensionbytesExtension that may be attached based on the header type
tls_cert_hashbytesIf mutual TLS is employed, this represents the hash of the client's TLS certificate

Envelope

Envelope wraps a Payload with a signature so that the message may be authenticated

FieldTypeLabelDescription
payloadbytesA marshaled Payload
signaturebytesA signature by the creator specified in the Payload header

Header

FieldTypeLabelDescription
channel_headerbytes
signature_headerbytes

LastConfig

LastConfig is the encoded value for the Metadata message which is encoded in the LAST_CONFIGURATION block metadata index

FieldTypeLabelDescription
indexuint64

Metadata

Metadata is a common structure to be used to encode block metadata

FieldTypeLabelDescription
valuebytes
signaturesMetadataSignaturerepeated

MetadataSignature

FieldTypeLabelDescription
signature_headerbytesAn encoded SignatureHeader
signaturebytesThe signature over the concatenation of the Metadata value bytes, signatureHeader, and block header

OrdererBlockMetadata

OrdererBlockMetadata defines metadata that is set by the ordering service.

FieldTypeLabelDescription
last_configLastConfig
consenter_metadatabytes

Payload

Payload is the message contents (and header to allow for signing)

FieldTypeLabelDescription
headerHeaderHeader is included to provide identity and prevent replay
databytesData, the encoding of which is defined by the type in the header

SignatureHeader

FieldTypeLabelDescription
creatorbytesCreator of the message, a marshaled msp.SerializedIdentity
noncebytesArbitrary number that may only be used once. Can be used to detect replay attacks.

BlockMetadataIndex

This enum enlists indexes of the block metadata array

NameNumberDescription
SIGNATURES0Block metadata array position for block signatures
LAST_CONFIG1Block metadata array position to store last configuration block sequence number
TRANSACTIONS_FILTER2Block metadata array position to store serialized bit array filter of invalid transactions
ORDERER3Block metadata array position to store operational metadata for orderers e.g. For Kafka, this is where we store the last offset written to the local ledger
COMMIT_HASH4Block metadata array position to store the hash of TRANSACTIONS_FILTER, State Updates, and the COMMIT_HASH of the previous block

HeaderType

NameNumberDescription
MESSAGE0Used for messages which are signed but opaque
CONFIG1Used for messages which express the channel config
CONFIG_UPDATE2Used for transactions which update the channel config
ENDORSER_TRANSACTION3Used by the SDK to submit endorser based transactions
ORDERER_TRANSACTION4Used internally by the orderer for management
DELIVER_SEEK_INFO5Used as the type for Envelope messages submitted to instruct the Deliver API to seek
CHAINCODE_PACKAGE6Used for packaging chaincode artifacts for install
PEER_ADMIN_OPERATION8Used for invoking an administrative operation on a peer

Status

These status codes are intended to resemble selected HTTP status codes

NameNumberDescription
UNKNOWN0
SUCCESS200
BAD_REQUEST400
FORBIDDEN403
NOT_FOUND404
REQUEST_ENTITY_TOO_LARGE413
INTERNAL_SERVER_ERROR500
NOT_IMPLEMENTED501
SERVICE_UNAVAILABLE503

Top

common/collection.proto

CollectionConfig

CollectionConfig defines the configuration of a collection object; it currently contains a single, static type. Dynamic collections are deferred.

FieldTypeLabelDescription
static_collection_configStaticCollectionConfig

CollectionConfigPackage

CollectionConfigPackage represents an array of CollectionConfig messages; the extra struct is required because repeated oneof is forbidden by the protobuf syntax

FieldTypeLabelDescription
configCollectionConfigrepeated

CollectionCriteria

CollectionCriteria defines an element of a private data that corresponds to a certain transaction and collection

FieldTypeLabelDescription
channelstring
tx_idstring
collectionstring
namespacestring

CollectionPolicyConfig

Collection policy configuration. Initially, the configuration can only contain a SignaturePolicy. In the future, the SignaturePolicy may be a more general Policy. Instead of containing the actual policy, the configuration may in the future contain a string reference to a policy.

FieldTypeLabelDescription
signature_policySignaturePolicyEnvelopeInitially, only a signature policy is supported.

Later, the SignaturePolicy will be replaced by a Policy. Policy policy = 1; A reference to a Policy is planned to be added later. string reference = 2; |

StaticCollectionConfig

StaticCollectionConfig constitutes the configuration parameters of a static collection object. Static collections are collections that are known at chaincode instantiation time, and that cannot be changed. Dynamic collections are deferred.

FieldTypeLabelDescription
namestringthe name of the collection inside the denoted chaincode
member_orgs_policyCollectionPolicyConfiga reference to a policy residing / managed in the config block to define which orgs have access to this collection’s private data
required_peer_countint32The minimum number of peers private data will be sent to upon endorsement. The endorsement would fail if dissemination to at least this number of peers is not achieved.
maximum_peer_countint32The maximum number of peers that private data will be sent to upon endorsement. This number has to be bigger than required_peer_count.
block_to_liveuint64The number of blocks after which the collection data expires. For instance if the value is set to 10, a key last modified by block number 100 will be purged at block number 111. A zero value is treated same as MaxUint64
member_only_readboolThe member only read access denotes whether only collection member clients can read the private data (if set to true), or even non members can read the data (if set to false, for example if you want to implement more granular access logic in the chaincode)
member_only_writeboolThe member only write access denotes whether only collection member clients can write the private data (if set to true), or even non members can write the data (if set to false, for example if you want to implement more granular access logic in the chaincode)

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── ci
├── common
│   ├── collection.proto
│   ├── common.proto
│   ├── configtx.proto
│   ├── configuration.proto
│   ├── ledger.proto
│   └── policies.proto
├── discovery
│   └── protocol.proto
├── gossip
│   └── message.proto
├── ledger
│   ├── queryresult
│   │   └── kv_query_result.proto
│   └── rwset
│       ├── kvrwset
│       │   └── kv_rwset.proto
│       └── rwset.proto
├── msp
│   ├── identities.proto
│   ├── msp_config.proto
│   └── msp_principal.proto
├── orderer
│   ├── ab.proto
│   ├── cluster.proto
│   ├── configuration.proto
│   ├── etcdraft
│   │   ├── configuration.proto
│   │   └── metadata.proto
│   └── kafka.proto
├── peer
│   ├── chaincode_event.proto
│   ├── chaincode.proto
│   ├── chaincode_shim.proto
│   ├── configuration.proto
│   ├── events.proto
│   ├── lifecycle
│   │   ├── chaincode_definition.proto
│   │   ├── db.proto
│   │   └── lifecycle.proto
│   ├── peer.proto
│   ├── policy.proto
│   ├── proposal.proto
│   ├── proposal_response.proto
│   ├── query.proto
│   ├── resources.proto
│   ├── signed_cc_dep_spec.proto
│   └── transaction.proto
└── transientstore
    └── transientstore.proto

14 directories, 37 files

Protobuf sources

src:./peer/transaction.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/peer";
option java_package = "org.hyperledger.fabric.protos.peer";
option java_outer_classname = "TransactionPackage";

package protos;

import "peer/proposal_response.proto";
import "common/common.proto";

// This message is necessary to facilitate the verification of the signature
// (in the signature field) over the bytes of the transaction (in the
// transactionBytes field).
message SignedTransaction {
    // The bytes of the Transaction. NDD
    bytes transaction_bytes = 1;

    // Signature of the transactionBytes The public key of the signature is in
    // the header field of TransactionAction There might be multiple
    // TransactionAction, so multiple headers, but there should be same
    // transactor identity (cert) in all headers
    bytes signature = 2;
}

// ProcessedTransaction wraps an Envelope that includes a transaction along with an indication
// of whether the transaction was validated or invalidated by committing peer.
// The use case is that GetTransactionByID API needs to retrieve the transaction Envelope
// from block storage, and return it to a client, and indicate whether the transaction
// was validated or invalidated by committing peer. So that the originally submitted
// transaction Envelope is not modified, the ProcessedTransaction wrapper is returned.
message ProcessedTransaction {
    // An Envelope which includes a processed transaction
    common.Envelope transactionEnvelope = 1;

    // An indication of whether the transaction was validated or invalidated by committing peer
    int32 validationCode = 2;
}

// The transaction to be sent to the ordering service. A transaction contains
// one or more TransactionAction. Each TransactionAction binds a proposal to
// potentially multiple actions. The transaction is atomic meaning that either
// all actions in the transaction will be committed or none will.  Note that
// while a Transaction might include more than one Header, the Header.creator
// field must be the same in each.
// A single client is free to issue a number of independent Proposal, each with
// their header (Header) and request payload (ChaincodeProposalPayload).  Each
// proposal is independently endorsed generating an action
// (ProposalResponsePayload) with one signature per Endorser. Any number of
// independent proposals (and their action) might be included in a transaction
// to ensure that they are treated atomically.
message Transaction {

    // The payload is an array of TransactionAction. An array is necessary to
    // accommodate multiple actions per transaction
    repeated TransactionAction actions = 1;
}

// TransactionAction binds a proposal to its action.  The type field in the
// header dictates the type of action to be applied to the ledger.
message TransactionAction {

    // The header of the proposal action, which is the proposal header
    bytes header = 1;

    // The payload of the action as defined by the type in the header For
    // chaincode, it's the bytes of ChaincodeActionPayload
    bytes payload = 2;
}

//---------- Chaincode Transaction ------------

// ChaincodeActionPayload is the message to be used for the TransactionAction's
// payload when the Header's type is set to CHAINCODE.  It carries the
// chaincodeProposalPayload and an endorsed action to apply to the ledger.
message ChaincodeActionPayload {
    // This field contains the bytes of the ChaincodeProposalPayload message from
    // the original invocation (essentially the arguments) after the application
    // of the visibility function. The main visibility modes are "full" (the
    // entire ChaincodeProposalPayload message is included here), "hash" (only
    // the hash of the ChaincodeProposalPayload message is included) or
    // "nothing".  This field will be used to check the consistency of
    // ProposalResponsePayload.proposalHash.  For the CHAINCODE type,
    // ProposalResponsePayload.proposalHash is supposed to be H(ProposalHeader ||
    // f(ChaincodeProposalPayload)) where f is the visibility function.
    bytes chaincode_proposal_payload = 1;

    // The list of actions to apply to the ledger
    ChaincodeEndorsedAction action = 2;
}

// ChaincodeEndorsedAction carries information about the endorsement of a
// specific proposal
message ChaincodeEndorsedAction {
    // This is the bytes of the ProposalResponsePayload message signed by the
    // endorsers.  Recall that for the CHAINCODE type, the
    // ProposalResponsePayload's extenstion field carries a ChaincodeAction
    bytes proposal_response_payload = 1;

    // The endorsement of the proposal, basically the endorser's signature over
    // proposalResponsePayload
    repeated Endorsement endorsements = 2;
}

enum TxValidationCode {
    VALID = 0;
    NIL_ENVELOPE = 1;
    BAD_PAYLOAD = 2;
    BAD_COMMON_HEADER = 3;
    BAD_CREATOR_SIGNATURE = 4;
    INVALID_ENDORSER_TRANSACTION = 5;
    INVALID_CONFIG_TRANSACTION = 6;
    UNSUPPORTED_TX_PAYLOAD = 7;
    BAD_PROPOSAL_TXID = 8;
    DUPLICATE_TXID = 9;
    ENDORSEMENT_POLICY_FAILURE = 10;
    MVCC_READ_CONFLICT = 11;
    PHANTOM_READ_CONFLICT = 12;
    UNKNOWN_TX_TYPE = 13;
    TARGET_CHAIN_NOT_FOUND = 14;
    MARSHAL_TX_ERROR = 15;
    NIL_TXACTION = 16;
    EXPIRED_CHAINCODE = 17;
    CHAINCODE_VERSION_CONFLICT = 18;
    BAD_HEADER_EXTENSION = 19;
    BAD_CHANNEL_HEADER = 20;
    BAD_RESPONSE_PAYLOAD = 21;
    BAD_RWSET = 22;
    ILLEGAL_WRITESET = 23;
    INVALID_WRITESET = 24;
    INVALID_CHAINCODE = 25;
    NOT_VALIDATED = 254;
    INVALID_OTHER_REASON = 255;
}

// Reserved entries in the key-level metadata map
enum MetaDataKeys {
    VALIDATION_PARAMETER = 0;
    VALIDATION_PARAMETER_V2 = 1;
}

src:./peer/configuration.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

// AnchorPeers simply represents list of anchor peers which is used in ConfigurationItem
message AnchorPeers {
    repeated AnchorPeer anchor_peers = 1;
}

// AnchorPeer message structure which provides information about anchor peer, it includes host name,
// port number and peer certificate.
message AnchorPeer {
    string host = 1; // DNS host name of the anchor peer
    int32 port  = 2; // The port number
}

// APIResource represents an API resource in the peer whose ACL
// is determined by the policy_ref field
message APIResource {
    string policy_ref = 1; // The policy name to use for this API
}

// ACLs provides mappings for resources in a channel. APIResource encapsulates
// reference to a policy used to determine ACL for the resource
message ACLs {
    map<string, APIResource> acls = 1;
}

src:./peer/signed_cc_dep_spec.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "peer/proposal_response.proto";

// SignedChaincodeDeploymentSpec carries the CDS along with endorsements
message SignedChaincodeDeploymentSpec {
    // This is the bytes of the ChaincodeDeploymentSpec
    bytes chaincode_deployment_spec = 1;

    // This is the instantiation policy which is identical in structure
    // to endorsement policy.  This policy is checked by the VSCC at commit
    // time on the instantiation (all peers will get the same policy as it
    // will be part of the LSCC instantation record and will be part of the
    // hash as well)
    bytes instantiation_policy = 2;

    // The endorsements of the above deployment spec, the owner's signature over
    // chaincode_deployment_spec and Endorsement.endorser.
    repeated Endorsement owner_endorsements = 3;
}


src:./peer/chaincode.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "common/policies.proto";

//ChaincodeID contains the path as specified by the deploy transaction
//that created it as well as the hashCode that is generated by the
//system for the path. From the user level (ie, CLI, REST API and so on)
//deploy transaction is expected to provide the path and other requests
//are expected to provide the hashCode. The other value will be ignored.
//Internally, the structure could contain both values. For instance, the
//hashCode will be set when first generated using the path
message ChaincodeID {
    //deploy transaction will use the path
    string path = 1;

    //all other requests will use the name (really a hashcode) generated by
    //the deploy transaction
    string name = 2;

    //user friendly version name for the chaincode
    string version = 3;
}

// Carries the chaincode function and its arguments.
// UnmarshalJSON in transaction.go converts the string-based REST/JSON input to
// the []byte-based current ChaincodeInput structure.
message ChaincodeInput {
    repeated bytes args  = 1;
    map<string, bytes> decorations = 2;

    // is_init is used for the application to signal that an invocation is to be routed
    // to the legacy 'Init' function for compatibility with chaincodes which handled
    // Init in the old way.  New applications should manage their initialized state
    // themselves.
    bool is_init = 3;
}

// Carries the chaincode specification. This is the actual metadata required for
// defining a chaincode.
message ChaincodeSpec {

    enum Type {
        UNDEFINED = 0;
        GOLANG = 1;
        NODE = 2;
        CAR = 3;
        JAVA = 4;
    }

    Type type = 1;
    ChaincodeID chaincode_id = 2;
    ChaincodeInput input = 3;
    int32 timeout = 4;
}

// Specify the deployment of a chaincode.
// TODO: Define `codePackage`.
message ChaincodeDeploymentSpec {
    // Prevent removed tag re-use
    reserved 2, 4;
    reserved "effective_date", "exec_env";

    ChaincodeSpec chaincode_spec = 1;
    bytes code_package = 3;

}

// Carries the chaincode function and its arguments.
message ChaincodeInvocationSpec {
    // Prevent removed tag re-use
    reserved 2;
    reserved "id_generation_alg";

    ChaincodeSpec chaincode_spec = 1;
}

// LifecycleEvent is used as the payload of the chaincode event emitted by LSCC
message LifecycleEvent {
    string chaincode_name = 1;
}

// CDSData is data stored in the LSCC on instantiation of a CC
// for CDSPackage.  This needs to be serialized for ChaincodeData
// hence the protobuf format
message CDSData {
    bytes hash = 1; // hash of ChaincodeDeploymentSpec.code_package
    bytes metadatahash = 2; // hash of ChaincodeID.name + ChaincodeID.version
}

// ChaincodeData defines the datastructure for chaincodes to be serialized by proto
// Type provides an additional check by directing to use a specific package after instantiation
// Data is Type specific (see CDSPackage and SignedCDSPackage)
message ChaincodeData {

    // Name of the chaincode
    string name = 1;

    // Version of the chaincode
    string version = 2;

    // Escc for the chaincode instance
    string escc = 3;

    // Vscc for the chaincode instance
    string vscc = 4;

    // Policy endorsement policy for the chaincode instance
    common.SignaturePolicyEnvelope policy = 5;

    // Data data specific to the package
    bytes data = 6;

    // Id of the chaincode that's the unique fingerprint for the CC This is not
    // currently used anywhere but serves as a good eyecatcher
    bytes id = 7;

    // InstantiationPolicy for the chaincode
    common.SignaturePolicyEnvelope instantiation_policy = 8;
}

src:./peer/proposal_response.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/peer";
option java_package = "org.hyperledger.fabric.protos.peer";
option java_outer_classname = "ProposalResponsePackage";

package protos;

import "google/protobuf/timestamp.proto";

// A ProposalResponse is returned from an endorser to the proposal submitter.
// The idea is that this message contains the endorser's response to the
// request of a client to perform an action over a chaincode (or more
// generically on the ledger); the response might be success/error (conveyed in
// the Response field) together with a description of the action and a
// signature over it by that endorser.  If a sufficient number of distinct
// endorsers agree on the same action and produce signature to that effect, a
// transaction can be generated and sent for ordering.
message ProposalResponse {
    // Version indicates message protocol version
    int32 version = 1;

    // Timestamp is the time that the message
    // was created as  defined by the sender
    google.protobuf.Timestamp timestamp = 2;

    // A response message indicating whether the
    // endorsement of the action was successful
    Response response = 4;

    // The payload of response. It is the bytes of ProposalResponsePayload
    bytes payload = 5;

    // The endorsement of the proposal, basically
    // the endorser's signature over the payload
    Endorsement endorsement = 6;
}

// A response with a representation similar to an HTTP response that can
// be used within another message.
message Response {
    // A status code that should follow the HTTP status codes.
    int32 status = 1;

    // A message associated with the response code.
    string message = 2;

    // A payload that can be used to include metadata with this response.
    bytes payload = 3;
}

// ProposalResponsePayload is the payload of a proposal response.  This message
// is the "bridge" between the client's request and the endorser's action in
// response to that request. Concretely, for chaincodes, it contains a hashed
// representation of the proposal (proposalHash) and a representation of the
// chaincode state changes and events inside the extension field.
message ProposalResponsePayload {
    // Hash of the proposal that triggered this response. The hash is used to
    // link a response with its proposal, both for bookeeping purposes on an
    // asynchronous system and for security reasons (accountability,
    // non-repudiation). The hash usually covers the entire Proposal message
    // (byte-by-byte).
    bytes proposal_hash = 1;

    // Extension should be unmarshaled to a type-specific message. The type of
    // the extension in any proposal response depends on the type of the proposal
    // that the client selected when the proposal was initially sent out.  In
    // particular, this information is stored in the type field of a Header.  For
    // chaincode, it's a ChaincodeAction message
    bytes extension = 2;
}

// An endorsement is a signature of an endorser over a proposal response.  By
// producing an endorsement message, an endorser implicitly "approves" that
// proposal response and the actions contained therein. When enough
// endorsements have been collected, a transaction can be generated out of a
// set of proposal responses.  Note that this message only contains an identity
// and a signature but no signed payload. This is intentional because
// endorsements are supposed to be collected in a transaction, and they are all
// expected to endorse a single proposal response/action (many endorsements
// over a single proposal response)
message Endorsement {
    // Identity of the endorser (e.g. its certificate)
    bytes endorser = 1;

    // Signature of the payload included in ProposalResponse concatenated with
    // the endorser's certificate; ie, sign(ProposalResponse.payload + endorser)
    bytes signature = 2;
}

src:./peer/query.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

// ChaincodeQueryResponse returns information about each chaincode that pertains
// to a query in lscc.go, such as GetChaincodes (returns all chaincodes
// instantiated on a channel), and GetInstalledChaincodes (returns all chaincodes
// installed on a peer)
message ChaincodeQueryResponse {
    repeated ChaincodeInfo chaincodes = 1;
}

// ChaincodeInfo contains general information about an installed/instantiated
// chaincode
message ChaincodeInfo {
    string name = 1;
    string version = 2;
    // the path as specified by the install/instantiate transaction
    string path = 3;
    // the chaincode function upon instantiation and its arguments. This will be
    // blank if the query is returning information about installed chaincodes.
    string input = 4;
    // the name of the ESCC for this chaincode. This will be
    // blank if the query is returning information about installed chaincodes.
    string escc = 5;
    // the name of the VSCC for this chaincode. This will be
    // blank if the query is returning information about installed chaincodes.
    string vscc = 6;
    // the chaincode unique id.
    // computed as: H(
    //                H(name || version) ||
    //                H(CodePackage)
    //              )
    bytes id = 7;
}

// ChannelQueryResponse returns information about each channel that pertains
// to a query in lscc.go, such as GetChannels (returns all channels for a
// given peer)
message ChannelQueryResponse {
    repeated ChannelInfo channels = 1;
}

// ChannelInfo contains general information about channels
message ChannelInfo {
    string channel_id = 1;
}

src:./peer/resources.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "common/configtx.proto";

// ChaincodeIdentifier identifies a piece of chaincode.  For a peer to accept invocations of
// this chaincode, the hash of the installed code must match, as must the version string
// included with the install command.
message ChaincodeIdentifier {
    bytes hash = 1;     // The hash of the chaincode bytes
    string version = 2; // A user friendly human readable name corresponding to the ID
}

// ChaincodeValidation instructs the peer how transactions for this chaincode should be
// validated.  The only validation mechanism which ships with fabric today is the standard
// 'vscc' validation mechanism.  This built in validation method utilizes an endorsement policy
// which checks that a sufficient number of signatures have been included.  The 'arguement'
// field encodes any parameters required by the validation implementation.
message ChaincodeValidation {
    string name = 1;    // Specifies which code to run to validate transactions, defaults to 'vscc'
    bytes argument = 2; // When 'vscc' a marshaled VSCCArgs
}

// VSCCArgs is passed (marshaled) as a parameter to the VSCC imlementation via the
// argument field of the ChaincodeValidation message.
message VSCCArgs {
    string endorsement_policy_ref = 1;  // A named reference to an endorsement policy,
                                        // for instance /Channel/Application/Writers
}

// ChaincodeEndorsement instructs the peer how transactions should be endorsed.  The only
// endorsement mechanism which ships with the fabric today is the standard 'escc' mechanism.
// This code simply simulates the proposal to generate a RW set, then signs the result
// using the peer's local signing identity.
message ChaincodeEndorsement {
    string name = 1; // Specifies what code to run for endorsements, defaults 'escc'
    // Eventually we may wish add an arg here, just like the ChaincodeValidation message, but
    // omitting now until there is a need for it.
}

// ConfigTree encapsulates channel and resources configuration of a channel.
// Both configurations are represented as common.Config
message ConfigTree {
    common.Config channel_config = 1;
    common.Config resources_config = 2;
}

src:./peer/events.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option java_outer_classname = "EventsPackage";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "common/common.proto";
import "ledger/rwset/rwset.proto";
import "peer/chaincode_event.proto";
import "peer/transaction.proto";

// FilteredBlock is a minimal set of information about a block
message FilteredBlock {
    string channel_id = 1;
    uint64 number = 2; // The position in the blockchain
    repeated FilteredTransaction filtered_transactions = 4;
}

// FilteredTransaction is a minimal set of information about a transaction
// within a block
message FilteredTransaction {
    string txid = 1;
    common.HeaderType type = 2;
    TxValidationCode tx_validation_code = 3;
    oneof Data {
        FilteredTransactionActions transaction_actions = 4;
    }
}

// FilteredTransactionActions is a wrapper for array of TransactionAction
// message from regular block
message FilteredTransactionActions {
    repeated FilteredChaincodeAction chaincode_actions = 1;
}

// FilteredChaincodeAction is a minimal set of information about an action
// within a transaction
message FilteredChaincodeAction {
    ChaincodeEvent chaincode_event = 1;
}

// BlockAndPrivateData contains Block and a map from tx_seq_in_block to rwset.TxPvtReadWriteSet
message BlockAndPrivateData {
    common.Block block = 1;
    // map from tx_seq_in_block to rwset.TxPvtReadWriteSet
    map<uint64, rwset.TxPvtReadWriteSet> private_data_map = 2;
}

// DeliverResponse
message DeliverResponse {
    oneof Type {
        common.Status status = 1;
        common.Block block = 2;
        FilteredBlock filtered_block = 3;
        BlockAndPrivateData block_and_private_data = 4;
    }
}

service Deliver {
    // Deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with
    // Payload data as a marshaled orderer.SeekInfo message,
    // then a stream of block replies is received
    rpc Deliver (stream common.Envelope) returns (stream DeliverResponse) {
    }
    // DeliverFiltered first requires an Envelope of type ab.DELIVER_SEEK_INFO with
    // Payload data as a marshaled orderer.SeekInfo message,
    // then a stream of **filtered** block replies is received
    rpc DeliverFiltered (stream common.Envelope) returns (stream DeliverResponse) {
    }
    // DeliverWithPrivateData first requires an Envelope of type ab.DELIVER_SEEK_INFO with
    // Payload data as a marshaled orderer.SeekInfo message,
    // then a stream of block and private data replies is received
    rpc DeliverWithPrivateData (stream common.Envelope) returns (stream DeliverResponse) {
    }
}

src:./peer/proposal.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/peer";
option java_package = "org.hyperledger.fabric.protos.peer";
option java_outer_classname = "ProposalPackage";

package protos;

import "peer/chaincode.proto";
import "peer/proposal_response.proto";

/*
The flow to get a generic transaction approved goes as follows:

1. client sends proposal to endorser
====================================

The proposal is basically a request to do something that will result on some
action with impact on the ledger; a proposal contains a header (with some
metadata describing it, such as the type, the identity of the invoker, the
time, the ID of the chain, a cryptographic nonce..) and an opaque payload that
depends on the type specified in the header. A proposal contains the following
messages:

SignedProposal
|\_ Signature                                    (signature on the Proposal message by the creator specified in the header)
 \_ Proposal
    |\_ Header                                   (the header for this proposal)
     \_ Payload                                  (the payload for this proposal)

2. endorser sends proposal response back to client
==================================================

The proposal response contains an endorser's response to a client's proposal. A
proposal response contains a success/error code, a response payload and a
signature (also referred to as endorsement) over the response payload. The
response payload contains a hash of the proposal (to securely link this
response to the corresponding proposal) and an opaque extension field that
depends on the type specified in the header of the corresponding proposal. A
proposal response contains the following messages:

ProposalResponse
|\_ Endorsement                                  (the endorser's signature over the whole response payload)
 \_ ProposalResponsePayload                      (the payload of the proposal response)

3. client assembles endorsements into a transaction
===================================================

A transaction message assembles one or more proposals and corresponding
responses into a message to be sent to orderers. After ordering, (batches of)
transactions are delivered to committing peers for validation and final
delivery into the ledger. A transaction contains one or more actions. Each of
them contains a header (same as that of the proposal that requested it) and an
opaque payload that depends on the type specified in the header.

SignedTransaction
|\_ Signature                                    (signature on the Transaction message by the creator specified in the header)
 \_ Transaction
     \_ TransactionAction (1...n)
        |\_ Header (1)                           (the header of the proposal that requested this action)
         \_ Payload (1)                          (the payload for this action)
*/

// This structure is necessary to sign the proposal which contains the header
// and the payload. Without this structure, we would have to concatenate the
// header and the payload to verify the signature, which could be expensive
// with large payload
//
// When an endorser receives a SignedProposal message, it should verify the
// signature over the proposal bytes. This verification requires the following
// steps:
// 1. Verification of the validity of the certificate that was used to produce
//    the signature.  The certificate will be available once proposalBytes has
//    been unmarshalled to a Proposal message, and Proposal.header has been
//    unmarshalled to a Header message. While this unmarshalling-before-verifying
//    might not be ideal, it is unavoidable because i) the signature needs to also
//    protect the signing certificate; ii) it is desirable that Header is created
//    once by the client and never changed (for the sake of accountability and
//    non-repudiation). Note also that it is actually impossible to conclusively
//    verify the validity of the certificate included in a Proposal, because the
//    proposal needs to first be endorsed and ordered with respect to certificate
//    expiration transactions. Still, it is useful to pre-filter expired
//    certificates at this stage.
// 2. Verification that the certificate is trusted (signed by a trusted CA) and
//    that it is allowed to transact with us (with respect to some ACLs);
// 3. Verification that the signature on proposalBytes is valid;
// 4. Detect replay attacks;
message SignedProposal {

    // The bytes of Proposal
    bytes proposal_bytes = 1;

  // Signaure over proposalBytes; this signature is to be verified against
  // the creator identity contained in the header of the Proposal message
  // marshaled as proposalBytes
    bytes signature = 2;
}

// A Proposal is sent to an endorser for endorsement.  The proposal contains:
// 1. A header which should be unmarshaled to a Header message.  Note that
//    Header is both the header of a Proposal and of a Transaction, in that i)
//    both headers should be unmarshaled to this message; and ii) it is used to
//    compute cryptographic hashes and signatures.  The header has fields common
//    to all proposals/transactions.  In addition it has a type field for
//    additional customization. An example of this is the ChaincodeHeaderExtension
//    message used to extend the Header for type CHAINCODE.
// 2. A payload whose type depends on the header's type field.
// 3. An extension whose type depends on the header's type field.
//
// Let us see an example. For type CHAINCODE (see the Header message),
// we have the following:
// 1. The header is a Header message whose extensions field is a
//    ChaincodeHeaderExtension message.
// 2. The payload is a ChaincodeProposalPayload message.
// 3. The extension is a ChaincodeAction that might be used to ask the
//    endorsers to endorse a specific ChaincodeAction, thus emulating the
//    submitting peer model.
message Proposal {

    // The header of the proposal. It is the bytes of the Header
    bytes header = 1;

    // The payload of the proposal as defined by the type in the proposal
    // header.
    bytes payload = 2;

    // Optional extensions to the proposal. Its content depends on the Header's
    // type field.  For the type CHAINCODE, it might be the bytes of a
    // ChaincodeAction message.
    bytes extension = 3;
}

//-------- the Chaincode Proposal -----------

/*
The flow to get a CHAINCODE transaction approved goes as follows:

1. client sends proposal to endorser
====================================

The proposal is basically a request to do something on a chaincode, that will
result on some action - some change in the state of a chaincode and/or some
data to be committed to the ledger; a proposal in general contains a header
(with some metadata describing it, such as the type, the identity of the
invoker, the time, the ID of the chain, a cryptographic nonce..) and a payload
(the chaincode ID, invocation arguments..). Optionally, it may contain actions
that the endorser may be asked to endorse, to emulate a submitting peer. A
chaincode proposal contains the following messages:

SignedProposal
|\_ Signature                                    (signature on the Proposal message by the creator specified in the header)
 \_ Proposal
    |\_ Header                                   (the header for this proposal)
    |\_ ChaincodeProposalPayload                 (the payload for this proposal)
     \_ ChaincodeAction                          (the actions for this proposal - optional for a proposal)

2. endorser sends proposal response back to client
==================================================

The proposal response contains an endorser's response to a client's proposal. A
proposal response contains a success/error code, a response payload and a
signature (also referred to as endorsement) over the response payload. The
response payload contains a hash of the proposal (to securely link this
response to the corresponding proposal), a description of the action resulting
from the proposal and the endorser's signature over its payload. Formally, a
chaincode proposal response contains the following messages:

ProposalResponse
|\_ Endorsement                                  (the endorser's signature over the whole response payload)
 \_ ProposalResponsePayload
     \_ ChaincodeAction                          (the actions for this proposal)

3. client assembles endorsements into a transaction
===================================================

A transaction message assembles one or more proposals and corresponding
responses into a message to be sent to orderers. After ordering, (batches of)
transactions are delivered to committing peers for validation and final
delivery into the ledger. A transaction contains one or more actions. Each of
them contains a header (same as that of the proposal that requested it), a
proposal payload (same as that of the proposal that requested it), a
description of the resulting action and signatures from each of the endorsers
that endorsed the action.

SignedTransaction
|\_ Signature                                    (signature on the Transaction message by the creator specified in the header)
 \_ Transaction
     \_ TransactionAction (1...n)
        |\_ Header (1)                           (the header of the proposal that requested this action)
         \_ ChaincodeActionPayload (1)
            |\_ ChaincodeProposalPayload (1)     (payload of the proposal that requested this action)
             \_ ChaincodeEndorsedAction (1)
                |\_ Endorsement (1...n)          (endorsers' signatures over the whole response payload)
                 \_ ProposalResponsePayload
                     \_ ChaincodeAction          (the actions for this proposal)
*/

// ChaincodeHeaderExtension is the Header's extentions message to be used when
// the Header's type is CHAINCODE.  This extensions is used to specify which
// chaincode to invoke and what should appear on the ledger.
message ChaincodeHeaderExtension {

    reserved 1;
    reserved "payload_visbility";

    // The ID of the chaincode to target.
    ChaincodeID chaincode_id = 2;
}

// ChaincodeProposalPayload is the Proposal's payload message to be used when
// the Header's type is CHAINCODE.  It contains the arguments for this
// invocation.
message ChaincodeProposalPayload {

    // Input contains the arguments for this invocation. If this invocation
    // deploys a new chaincode, ESCC/VSCC are part of this field.
    // This is usually a marshaled ChaincodeInvocationSpec
    bytes input  = 1;

    // TransientMap contains data (e.g. cryptographic material) that might be used
    // to implement some form of application-level confidentiality. The contents
    // of this field are supposed to always be omitted from the transaction and
    // excluded from the ledger.
    map<string, bytes> TransientMap = 2;
}

// ChaincodeAction contains the actions the events generated by the execution
// of the chaincode.
message ChaincodeAction {
    reserved 5;
    reserved "token_operations";

    // This field contains the read set and the write set produced by the
    // chaincode executing this invocation.
    bytes results = 1;

    // This field contains the events generated by the chaincode executing this
    // invocation.
    bytes events = 2;

    // This field contains the result of executing this invocation.
    Response response = 3;

    // This field contains the ChaincodeID of executing this invocation. Endorser
    // will set it with the ChaincodeID called by endorser while simulating proposal.
    // Committer will validate the version matching with latest chaincode version.
    // Adding ChaincodeID to keep version opens up the possibility of multiple
    // ChaincodeAction per transaction.
    ChaincodeID chaincode_id = 4;
}

src:./peer/policy.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/peer";
option java_package = "org.hyperledger.fabric.protos.peer";

package protos;

import "common/policies.proto";

// ApplicationPolicy captures the diffenrent policy types that
// are set and evaluted at the application level.
message ApplicationPolicy {
    oneof Type {
        // SignaturePolicy type is used if the policy is specified as
        // a combination (using threshold gates) of signatures from MSP
        // principals
        common.SignaturePolicyEnvelope signature_policy = 1;

        // ChannelConfigPolicyReference is used when the policy is
        // specified as a string that references a policy defined in
        // the configuration of the channel
        string channel_config_policy_reference = 2;
    }
}

src:./peer/lifecycle/chaincode_definition.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer.lifecycle";
option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle";

package lifecycle;

// These protos are used for encoding chaincode definitions into the statedb
// in general, it should not be necessary for clients to utilize them.

// ChaincodeEndorsementInfo is (most) everything the peer needs to know in order
// to execute a chaincode
message ChaincodeEndorsementInfo {
    string version = 1;
    bool init_required = 2;
    string endorsement_plugin = 3;
}

// ValidationInfo is (most) everything the peer needs to know in order
// to validate a transaction
message ChaincodeValidationInfo {
    string validation_plugin = 1;
    bytes validation_parameter = 2;
}

// The notable omission in this file is the collection configuration info.
// It should be moved to this package, but... defering for now.

src:./peer/lifecycle/lifecycle.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer.lifecycle";
option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle";

package lifecycle;

import "common/collection.proto";

// InstallChaincodeArgs is the message used as the argument to
// '_lifecycle.InstallChaincode'.
message InstallChaincodeArgs {
    bytes chaincode_install_package = 1; // This should be a marshaled lifecycle.ChaincodePackage
}

// InstallChaincodeArgs is the message returned by
// '_lifecycle.InstallChaincode'.
message InstallChaincodeResult {
    string package_id = 1;
    string label = 2;
}

// QueryInstalledChaincodeArgs is the message used as arguments
// '_lifecycle.QueryInstalledChaincode'
message QueryInstalledChaincodeArgs {
    string package_id = 1;
}

// QueryInstalledChaincodeResult is the message returned by
// '_lifecycle.QueryInstalledChaincode'
message QueryInstalledChaincodeResult {
    string package_id = 1;
    string label = 2;
    map<string, References> references = 3;

    message References {
        repeated Chaincode chaincodes = 1;
    }

    message Chaincode {
        string name = 1;
        string version = 2;
    }
}

// GetInstalledChaincodePackageArgs is the message used as the argument to
// '_lifecycle.GetInstalledChaincodePackage'.
message GetInstalledChaincodePackageArgs {
    string package_id = 1;
}

// GetInstalledChaincodePackageResult is the message returned by
// '_lifecycle.GetInstalledChaincodePackage'.
message GetInstalledChaincodePackageResult {
    bytes chaincode_install_package = 1;
}

// QueryInstalledChaincodesArgs currently is an empty argument to
// '_lifecycle.QueryInstalledChaincodes'.   In the future, it may be
// extended to have parameters.
message QueryInstalledChaincodesArgs {
}

// QueryInstalledChaincodesResult is the message returned by
// '_lifecycle.QueryInstalledChaincodes'.  It returns a list of installed
// chaincodes, including a map of channel name to chaincode name and version
// pairs of chaincode definitions that reference this chaincode package.
message QueryInstalledChaincodesResult {
    message InstalledChaincode {
        string package_id = 1;
        string label = 2;
        map<string, References> references = 3;
    }

    message References {
        repeated Chaincode chaincodes = 1;
    }

    message Chaincode {
        string name = 1;
        string version = 2;
    }

    repeated InstalledChaincode installed_chaincodes = 1;
}

// ApproveChaincodeDefinitionForMyOrgArgs is the message used as arguments to
// `_lifecycle.ApproveChaincodeDefinitionForMyOrg`.
message ApproveChaincodeDefinitionForMyOrgArgs {
    int64 sequence = 1;
    string name = 2;
    string version = 3;
    string endorsement_plugin = 4;
    string validation_plugin = 5;
    bytes validation_parameter = 6;
    common.CollectionConfigPackage collections = 7;
    bool init_required = 8;
    ChaincodeSource source = 9;
}

message ChaincodeSource {
    message Unavailable {}

    message Local {
        string package_id = 1;
    }

    oneof Type {
        Unavailable unavailable = 1;
        Local local_package = 2;
    }
}

// ApproveChaincodeDefinitionForMyOrgResult is the message returned by
// `_lifecycle.ApproveChaincodeDefinitionForMyOrg`. Currently it returns
// nothing, but may be extended in the future.
message ApproveChaincodeDefinitionForMyOrgResult {
}

// CommitChaincodeDefinitionArgs is the message used as arguments to
// `_lifecycle.CommitChaincodeDefinition`.
message CommitChaincodeDefinitionArgs {
    int64 sequence = 1;
    string name = 2;
    string version = 3;
    string endorsement_plugin = 4;
    string validation_plugin = 5;
    bytes validation_parameter = 6;
    common.CollectionConfigPackage collections = 7;
    bool init_required = 8;
}

// CommitChaincodeDefinitionResult is the message returned by
// `_lifecycle.CommitChaincodeDefinition`. Currently it returns
// nothing, but may be extended in the future.
message CommitChaincodeDefinitionResult {
}

// CheckCommitReadinessArgs is the message used as arguments to
// `_lifecycle.CheckCommitReadiness`.
message CheckCommitReadinessArgs {
    int64 sequence = 1;
    string name = 2;
    string version = 3;
    string endorsement_plugin = 4;
    string validation_plugin = 5;
    bytes validation_parameter = 6;
    common.CollectionConfigPackage collections = 7;
    bool init_required = 8;
}

// CheckCommitReadinessResult is the message returned by
// `_lifecycle.CheckCommitReadiness`. It returns a map of
// orgs to their approval (true/false) for the definition 
// supplied as args.
message CheckCommitReadinessResult{
    map<string, bool> approvals = 1;
}

// QueryChaincodeDefinitionArgs is the message used as arguments to
// `_lifecycle.QueryChaincodeDefinition`.
message QueryChaincodeDefinitionArgs {
    string name = 1;
}

// QueryChaincodeDefinitionResult is the message returned by
// `_lifecycle.QueryChaincodeDefinition`.
message QueryChaincodeDefinitionResult {
    int64 sequence = 1;
    string version = 2;
    string endorsement_plugin = 3;
    string validation_plugin = 4;
    bytes validation_parameter = 5;
    common.CollectionConfigPackage collections = 6;
    bool init_required = 7;
    map<string,bool> approvals = 8;
}

// QueryChaincodeDefinitionsArgs is the message used as arguments to
// `_lifecycle.QueryChaincodeDefinitions`.
message QueryChaincodeDefinitionsArgs { }

// QueryChaincodeDefinitionsResult is the message returned by
// `_lifecycle.QueryChaincodeDefinitions`.
message QueryChaincodeDefinitionsResult {
    message ChaincodeDefinition {
        string name = 1;
        int64 sequence = 2;
        string version = 3;
        string endorsement_plugin = 4;
        string validation_plugin = 5;
        bytes validation_parameter = 6;
        common.CollectionConfigPackage collections = 7;
        bool init_required = 8;
    }
    repeated ChaincodeDefinition chaincode_definitions = 1;
}

src:./peer/lifecycle/db.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer.lifecycle";
option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle";

package lifecycle;

// These protos are used for encoding data into the statedb
// in general, it should not be necessary for clients to utilize them.

// StateMetadata describes the keys in a namespace.  It is necessary because
// in collections, range scans are not possible during transactions which
// write.  Therefore we must track the keys in our namespace ourselves.
message StateMetadata {
    string datatype = 1;
    repeated string fields = 2;
}

// StateData encodes a particular field of a datatype
message StateData {
    oneof Type {
        int64 Int64 = 1;
        bytes Bytes = 2;
        string String = 3;
    }
}

src:./peer/chaincode_event.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option java_outer_classname = "ChaincodeEventPackage";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

//ChaincodeEvent is used for events and registrations that are specific to chaincode
//string type - "chaincode"
message ChaincodeEvent {
    string chaincode_id = 1;
    string tx_id = 2;
    string event_name = 3;
    bytes payload = 4;
}

src:./peer/chaincode_shim.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "peer/chaincode_event.proto";
import "peer/proposal.proto";
import "google/protobuf/timestamp.proto";

message ChaincodeMessage {
    enum Type {
        UNDEFINED = 0;
        REGISTER = 1;
        REGISTERED = 2;
        INIT = 3;
        READY = 4;
        TRANSACTION = 5;
        COMPLETED = 6;
        ERROR = 7;
        GET_STATE = 8;
        PUT_STATE = 9;
        DEL_STATE = 10;
        INVOKE_CHAINCODE = 11;
        RESPONSE = 13;
        GET_STATE_BY_RANGE = 14;
        GET_QUERY_RESULT = 15;
        QUERY_STATE_NEXT = 16;
        QUERY_STATE_CLOSE = 17;
        KEEPALIVE = 18;
        GET_HISTORY_FOR_KEY = 19;
        GET_STATE_METADATA = 20;
        PUT_STATE_METADATA = 21;
        GET_PRIVATE_DATA_HASH = 22;
    }

    Type type = 1;
    google.protobuf.Timestamp timestamp = 2;
    bytes payload = 3;
    string txid = 4;

    SignedProposal proposal = 5;

    //event emitted by chaincode. Used only with Init or Invoke.
    // This event is then stored (currently)
    //with Block.NonHashData.TransactionResult
    ChaincodeEvent chaincode_event = 6;

    //channel id
    string channel_id = 7;
}

// TODO: We need to finalize the design on chaincode container
// compatibility upon upgrade, see FAB-5777.

// GetState is the payload of a ChaincodeMessage. It contains a key which
// is to be fetched from the ledger. If the collection is specified, the key
// would be fetched from the collection (i.e., private state)
message GetState {
    string key = 1;
    string collection = 2;
}

message GetStateMetadata {
    string key = 1;
    string collection = 2;
}

// PutState is the payload of a ChaincodeMessage. It contains a key and value
// which needs to be written to the transaction's write set. If the collection is
// specified, the key and value would be written to the transaction's private
// write set.
message PutState {
    string key = 1;
    bytes value = 2;
    string collection = 3;
}

message PutStateMetadata {
    string key = 1;
    string collection = 3;
    StateMetadata metadata = 4;
}

// DelState is the payload of a ChaincodeMessage. It contains a key which
// needs to be recorded in the transaction's write set as a delete operation.
// If the collection is specified, the key needs to be recorded in the
// transaction's private write set as a delete operation.
message DelState {
    string key = 1;
    string collection = 2;
}

// GetStateByRange is the payload of a ChaincodeMessage. It contains a start key and
// a end key required to execute range query. If the collection is specified,
// the range query needs to be executed on the private data. The metadata hold
// the byte representation of QueryMetadata.
message GetStateByRange {
    string startKey = 1;
    string endKey = 2;
    string collection = 3;
    bytes metadata = 4;
}

// GetQueryResult is the payload of a ChaincodeMessage. It contains a query
// string in the form that is supported by the underlying state database.
// If the collection is specified, the query needs to be executed on the
// private data.  The metadata hold the byte representation of QueryMetadata.
message GetQueryResult {
    string query = 1;
    string collection = 2;
    bytes metadata = 3;
}

// QueryMetadata is the metadata of a GetStateByRange and GetQueryResult.
// It contains a pageSize which denotes the number of records to be fetched
// and a bookmark.
message QueryMetadata {
    int32 pageSize = 1;
    string bookmark = 2;
}

// GetHistoryForKey is the payload of a ChaincodeMessage. It contains a key
// for which the historical values need to be retrieved.
message GetHistoryForKey {
    string key = 1;
}

message QueryStateNext {
    string id = 1;
}

message QueryStateClose {
    string id = 1;
}

// QueryResultBytes hold the byte representation of a record returned by the peer.
message QueryResultBytes {
    bytes resultBytes = 1;
}

// QueryResponse is returned by the peer as a result of a GetStateByRange,
// GetQueryResult, and GetHistoryForKey. It holds a bunch of records in
// results field, a flag to denote whether more results need to be fetched from
// the peer in has_more field, transaction id in id field, and a QueryResponseMetadata
// in metadata field.
message QueryResponse {
    repeated QueryResultBytes results = 1;
    bool has_more = 2;
    string id = 3;
    bytes metadata = 4;
}

// QueryResponseMetadata is the metadata of a QueryResponse. It contains a count
// which denotes the number of records fetched from the ledger and a bookmark.
message QueryResponseMetadata {
    int32 fetched_records_count = 1;
    string bookmark = 2;
}

message StateMetadata {
    string metakey = 1;
    bytes value = 2;
}

message StateMetadataResult {
    repeated StateMetadata entries = 1;
}

// Interface that provides support to chaincode execution. ChaincodeContext
// provides the context necessary for the server to respond appropriately.
service ChaincodeSupport {
    rpc Register(stream ChaincodeMessage) returns (stream ChaincodeMessage);
}

src:./peer/peer.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option java_package = "org.hyperledger.fabric.protos.peer";
option go_package = "github.com/hyperledger/fabric-protos-go/peer";

package protos;

import "peer/proposal.proto";
import "peer/proposal_response.proto";

service Endorser {
    rpc ProcessProposal(SignedProposal) returns (ProposalResponse);
}

src:./msp/msp_config.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/msp";
option java_package = "org.hyperledger.fabric.protos.msp";
option java_outer_classname = "MspConfigPackage";

package msp;

// MSPConfig collects all the configuration information for
// an MSP. The Config field should be unmarshalled in a way
// that depends on the Type
message MSPConfig {
    // Type holds the type of the MSP; the default one would
    // be of type FABRIC implementing an X.509 based provider
    int32 type = 1;

    // Config is MSP dependent configuration info
    bytes config = 2;
}

// FabricMSPConfig collects all the configuration information for
// a Fabric MSP.
// Here we assume a default certificate validation policy, where
// any certificate signed by any of the listed rootCA certs would
// be considered as valid under this MSP.
// This MSP may or may not come with a signing identity. If it does,
// it can also issue signing identities. If it does not, it can only
// be used to validate and verify certificates.
message FabricMSPConfig {
    // Name holds the identifier of the MSP; MSP identifier
    // is chosen by the application that governs this MSP.
    // For example, and assuming the default implementation of MSP,
    // that is X.509-based and considers a single Issuer,
    // this can refer to the Subject OU field or the Issuer OU field.
    string name = 1;

    // List of root certificates trusted by this MSP
    // they are used upon certificate validation (see
    // comment for IntermediateCerts below)
    repeated bytes root_certs = 2;

    // List of intermediate certificates trusted by this MSP;
    // they are used upon certificate validation as follows:
    // validation attempts to build a path from the certificate
    // to be validated (which is at one end of the path) and
    // one of the certs in the RootCerts field (which is at
    // the other end of the path). If the path is longer than
    // 2, certificates in the middle are searched within the
    // IntermediateCerts pool
    repeated bytes intermediate_certs = 3;

    // Identity denoting the administrator of this MSP
    repeated bytes admins = 4;

    // Identity revocation list
    repeated bytes revocation_list = 5;

    // SigningIdentity holds information on the signing identity
    // this peer is to use, and which is to be imported by the
    // MSP defined before
    SigningIdentityInfo signing_identity = 6;

    // OrganizationalUnitIdentifiers holds one or more
    // fabric organizational unit identifiers that belong to
    // this MSP configuration
    repeated FabricOUIdentifier organizational_unit_identifiers = 7;

    // FabricCryptoConfig contains the configuration parameters
    // for the cryptographic algorithms used by this MSP
    FabricCryptoConfig crypto_config = 8;

    // List of TLS root certificates trusted by this MSP.
    // They are returned by GetTLSRootCerts.
    repeated bytes tls_root_certs = 9;

    // List of TLS intermediate certificates trusted by this MSP;
    // They are returned by GetTLSIntermediateCerts.
    repeated bytes tls_intermediate_certs = 10;

    // fabric_node_ous contains the configuration to distinguish clients from peers from orderers
    // based on the OUs.
    FabricNodeOUs fabric_node_ous = 11;
}

// FabricCryptoConfig contains configuration parameters
// for the cryptographic algorithms used by the MSP
// this configuration refers to
message FabricCryptoConfig {

    // SignatureHashFamily is a string representing the hash family to be used
    // during sign and verify operations.
    // Allowed values are "SHA2" and "SHA3".
    string signature_hash_family = 1;

    // IdentityIdentifierHashFunction is a string representing the hash function
    // to be used during the computation of the identity identifier of an MSP identity.
    // Allowed values are "SHA256", "SHA384" and "SHA3_256", "SHA3_384".
    string identity_identifier_hash_function = 2;

}

// IdemixMSPConfig collects all the configuration information for
// an Idemix MSP.
message IdemixMSPConfig {
    // Name holds the identifier of the MSP
    string name = 1;

    // ipk represents the (serialized) issuer public key
    bytes ipk = 2;

    // signer may contain crypto material to configure a default signer
    IdemixMSPSignerConfig signer = 3;

    // revocation_pk is the public key used for revocation of credentials
    bytes revocation_pk = 4;

    // epoch represents the current epoch (time interval) used for revocation
    int64 epoch = 5;
}

// IdemixMSPSIgnerConfig contains the crypto material to set up an idemix signing identity
message IdemixMSPSignerConfig {
    // cred represents the serialized idemix credential of the default signer
    bytes cred = 1;

    // sk is the secret key of the default signer, corresponding to credential Cred
    bytes sk = 2;

    // organizational_unit_identifier defines the organizational unit the default signer is in
    string organizational_unit_identifier = 3;

    // role defines whether the default signer is admin, peer, member or client
    int32 role = 4;

    // enrollment_id contains the enrollment id of this signer
    string enrollment_id = 5;

    // credential_revocation_information contains a serialized CredentialRevocationInformation
    bytes credential_revocation_information = 6;
}

// SigningIdentityInfo represents the configuration information
// related to the signing identity the peer is to use for generating
// endorsements
message SigningIdentityInfo {
    // PublicSigner carries the public information of the signing
    // identity. For an X.509 provider this would be represented by
    // an X.509 certificate
    bytes public_signer = 1;

    // PrivateSigner denotes a reference to the private key of the
    // peer's signing identity
    KeyInfo private_signer = 2;
}

// KeyInfo represents a (secret) key that is either already stored
// in the bccsp/keystore or key material to be imported to the
// bccsp key-store. In later versions it may contain also a
// keystore identifier
message KeyInfo {
    // Identifier of the key inside the default keystore; this for
    // the case of Software BCCSP as well as the HSM BCCSP would be
    // the SKI of the key
    string key_identifier = 1;

    // KeyMaterial (optional) for the key to be imported; this is
    // properly encoded key bytes, prefixed by the type of the key
    bytes key_material = 2;
}

// FabricOUIdentifier represents an organizational unit and
// its related chain of trust identifier.
message FabricOUIdentifier {

    // Certificate represents the second certificate in a certification chain.
    // (Notice that the first certificate in a certification chain is supposed
    // to be the certificate of an identity).
    // It must correspond to the certificate of root or intermediate CA
    // recognized by the MSP this message belongs to.
    // Starting from this certificate, a certification chain is computed
    // and bound to the OrganizationUnitIdentifier specified
    bytes certificate = 1;

    // OrganizationUnitIdentifier defines the organizational unit under the
    // MSP identified with MSPIdentifier
    string organizational_unit_identifier = 2;
}

// FabricNodeOUs contains configuration to tell apart clients from peers from orderers
// based on OUs. If NodeOUs recognition is enabled then an msp identity
// that does not contain any of the specified OU will be considered invalid.
message FabricNodeOUs {
    // If true then an msp identity that does not contain any of the specified OU will be considered invalid.
    bool   enable = 1;

    // OU Identifier of the clients
    FabricOUIdentifier client_ou_identifier = 2;

    // OU Identifier of the peers
    FabricOUIdentifier peer_ou_identifier = 3;

    // OU Identifier of the admins
    FabricOUIdentifier admin_ou_identifier = 4;

    // OU Identifier of the orderers
    FabricOUIdentifier orderer_ou_identifier = 5;
}

src:./msp/msp_principal.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/msp";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

// msp_principal.proto contains proto messages defining the generalized
// MSP notion of identity called an MSPPrincipal.  It is used as part of
// the chain configuration, in particular as the identity parameters to
// the configuration.proto file.  This does not represent the MSP
// configuration for a chain, but is understood by MSPs

// MSPPrincipal aims to represent an MSP-centric set of identities.
// In particular, this structure allows for definition of
//  - a group of identities that are member of the same MSP
//  - a group of identities that are member of the same organization unit
//    in the same MSP
//  - a group of identities that are administering a specific MSP
//  - a specific identity
// Expressing these groups is done given two fields of the fields below
//  - Classification, that defines the type of classification of identities
//    in an MSP this principal would be defined on; Classification can take
//    three values:
//     (i)  ByMSPRole: that represents a classification of identities within
//          MSP based on one of the two pre-defined MSP rules, "member" and "admin"
//     (ii) ByOrganizationUnit: that represents a classification of identities
//          within MSP based on the organization unit an identity belongs to
//     (iii)ByIdentity that denotes that MSPPrincipal is mapped to a single
//          identity/certificate; this would mean that the Principal bytes
//          message
message MSPPrincipal {
    enum Classification {
        ROLE = 0;  // Represents the one of the dedicated MSP roles, the
        // one of a member of MSP network, and the one of an
        // administrator of an MSP network
        ORGANIZATION_UNIT = 1; // Denotes a finer grained (affiliation-based)
        // groupping of entities, per MSP affiliation
        // E.g., this can well be represented by an MSP's
        // Organization unit
        IDENTITY  = 2;    // Denotes a principal that consists of a single
        // identity
        ANONYMITY = 3; // Denotes a principal that can be used to enforce
        // an identity to be anonymous or nominal.
        COMBINED = 4; // Denotes a combined principal
    }

    // Classification describes the way that one should process
    // Principal. An Classification value of "ByOrganizationUnit" reflects
    // that "Principal" contains the name of an organization this MSP
    // handles. A Classification value "ByIdentity" means that
    // "Principal" contains a specific identity. Default value
    // denotes that Principal contains one of the groups by
    // default supported by all MSPs ("admin" or "member").
    Classification principal_classification = 1;

    // Principal completes the policy principal definition. For the default
    // principal types, Principal can be either "Admin" or "Member".
    // For the ByOrganizationUnit/ByIdentity values of Classification,
    // PolicyPrincipal acquires its value from an organization unit or
    // identity, respectively.
    // For the Combined Classification type, the Principal is a marshalled
    // CombinedPrincipal.
    bytes principal = 2;
}


// OrganizationUnit governs the organization of the Principal
// field of a policy principal when a specific organization unity members
// are to be defined within a policy principal.
message OrganizationUnit {

    // MSPIdentifier represents the identifier of the MSP this organization unit
    // refers to
    string msp_identifier = 1;

    // OrganizationUnitIdentifier defines the organizational unit under the
    // MSP identified with MSPIdentifier
    string organizational_unit_identifier = 2;

    // CertifiersIdentifier is the hash of certificates chain of trust
    // related to this organizational unit
    bytes certifiers_identifier = 3;
}

// MSPRole governs the organization of the Principal
// field of an MSPPrincipal when it aims to define one of the
// two dedicated roles within an MSP: Admin and Members.
message MSPRole {
    // MSPIdentifier represents the identifier of the MSP this principal
    // refers to
    string msp_identifier = 1;

    enum MSPRoleType {
        MEMBER = 0; // Represents an MSP Member
        ADMIN  = 1; // Represents an MSP Admin
        CLIENT = 2; // Represents an MSP Client
        PEER = 3; // Represents an MSP Peer
        ORDERER = 4; // Represents an MSP Orderer
    }

    // MSPRoleType defines which of the available, pre-defined MSP-roles
    // an identiy should posess inside the MSP with identifier MSPidentifier
    MSPRoleType role = 2;
}

// MSPIdentityAnonymity can be used to enforce an identity to be anonymous or nominal.
message MSPIdentityAnonymity {
    enum MSPIdentityAnonymityType {
        NOMINAL = 0; // Represents a nominal MSP Identity
        ANONYMOUS = 1; // Represents an anonymous MSP Identity
    }

    MSPIdentityAnonymityType anonymity_type = 1;
}

// CombinedPrincipal governs the organization of the Principal
// field of a policy principal when principal_classification has
// indicated that a combined form of principals is required
message CombinedPrincipal {
    // Principals refer to combined principals
    repeated MSPPrincipal principals = 1;
}

// TODO: Bring msp.SerializedIdentity from fabric/msp/identities.proto here. Reason below.
// SerializedIdentity represents an serialized version of an identity;
// this consists of an MSP-identifier this identity would correspond to
// and the bytes of the actual identity. A serialized form of
// SerializedIdentity would govern "Principal" field of a PolicyPrincipal
// of classification "ByIdentity".

src:./msp/identities.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/msp";
option java_package = "org.hyperledger.fabric.protos.msp";

package msp;

// This struct represents an Identity
// (with its MSP identifier) to be used
// to serialize it and deserialize it
message SerializedIdentity {
    // The identifier of the associated membership service provider
    string mspid = 1;

    // the Identity, serialized according to the rules of its MPS
    bytes id_bytes = 2;
}

// This struct represents an Idemix Identity
// to be used to serialize it and deserialize it.
// The IdemixMSP will first serialize an idemix identity to bytes using
// this proto, and then uses these bytes as id_bytes in SerializedIdentity
message SerializedIdemixIdentity {
    // nym_x is the X-component of the pseudonym elliptic curve point.
    // It is a []byte representation of an amcl.BIG
    // The pseudonym can be seen as a public key of the identity, it is used to verify signatures.
    bytes nym_x = 1;

    // nym_y is the Y-component of the pseudonym elliptic curve point.
    // It is a []byte representation of an amcl.BIG
    // The pseudonym can be seen as a public key of the identity, it is used to verify signatures.
    bytes nym_y = 2;

    // ou contains the organizational unit of the idemix identity
    bytes ou = 3;

    // role contains the role of this identity (e.g., ADMIN or MEMBER)
    bytes role = 4;

    // proof contains the cryptographic evidence that this identity is valid
    bytes proof = 5;
}

src:./ledger/rwset/rwset.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/ledger/rwset";
option java_package = "org.hyperledger.fabric.protos.ledger.rwset";

package rwset;

// TxReadWriteSet encapsulates a read-write set for a transaction
// DataModel specifies the enum value of the data model
// ns_rwset field specifies a list of chaincode specific read-write set (one for each chaincode)
message TxReadWriteSet {
    enum DataModel {
        KV = 0;
    }
    DataModel data_model = 1;
    repeated NsReadWriteSet ns_rwset = 2;
}

// NsReadWriteSet encapsulates the read-write set for a chaincode
message NsReadWriteSet {
   string namespace = 1;
   bytes rwset = 2; // Data model specific serialized proto message (e.g., kvrwset.KVRWSet for KV and Document data models)
   repeated CollectionHashedReadWriteSet collection_hashed_rwset = 3;
}

// CollectionHashedReadWriteSet encapsulate the hashed representation for the private read-write set for a collection
message CollectionHashedReadWriteSet {
    string collection_name = 1;
    bytes hashed_rwset = 2; // Data model specific serialized proto message (e.g., kvrwset.HashedRWSet for KV and Document data models)
    bytes pvt_rwset_hash = 3; // Hash of entire private read-write set for a specific collection. This helps in authenticating the private read-write set efficiently
}

// TxPvtReadWriteSet encapsulate the private read-write set for a transaction
message TxPvtReadWriteSet {
    TxReadWriteSet.DataModel data_model = 1;
    repeated NsPvtReadWriteSet ns_pvt_rwset = 2;
}

// NsPvtReadWriteSet encapsulates the private read-write set for a chaincode
message NsPvtReadWriteSet {
   string namespace = 1;
   repeated CollectionPvtReadWriteSet collection_pvt_rwset = 2;
}

// CollectionPvtReadWriteSet encapsulates the private read-write set for a collection
message CollectionPvtReadWriteSet {
    string collection_name = 1;
    bytes rwset = 2; // Data model specific serialized proto message (e.g., kvrwset.KVRWSet for KV and Document data models)
}

src:./ledger/rwset/kvrwset/kv_rwset.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset";
option java_package = "org.hyperledger.fabric.protos.ledger.rwset.kvrwset";

package kvrwset;

// KVRWSet encapsulates the read-write set for a chaincode that operates upon a KV or Document data model
// This structure is used for both the public data and the private data
message KVRWSet {
    repeated KVRead reads = 1;
    repeated RangeQueryInfo range_queries_info = 2;
    repeated KVWrite writes = 3;
    repeated KVMetadataWrite metadata_writes = 4;
}

// HashedRWSet encapsulates hashed representation of a private read-write set for KV or Document data model
message HashedRWSet {
    repeated KVReadHash hashed_reads = 1;
    repeated KVWriteHash hashed_writes = 2;
    repeated KVMetadataWriteHash metadata_writes = 3;
}

// KVRead captures a read operation performed during transaction simulation
// A 'nil' version indicates a non-existing key read by the transaction
message KVRead {
    string key = 1;
    Version version = 2;
}

// KVWrite captures a write (update/delete) operation performed during transaction simulation
message KVWrite {
    string key = 1;
    bool is_delete = 2;
    bytes value = 3;
}

// KVMetadataWrite captures all the entries in the metadata associated with a key
message KVMetadataWrite {
    string key = 1;
    repeated KVMetadataEntry entries = 2;
}

// KVReadHash is similar to the KVRead in spirit. However, it captures the hash of the key instead of the key itself
// version is kept as is for now. However, if the version also needs to be privacy-protected, it would need to be the
// hash of the version and hence of 'bytes' type
message KVReadHash {
    bytes key_hash = 1;
    Version version = 2;
}

// KVWriteHash is similar to the KVWrite. It captures a write (update/delete) operation performed during transaction simulation
message KVWriteHash {
    bytes key_hash = 1;
    bool is_delete = 2;
    bytes value_hash = 3;
}

// KVMetadataWriteHash captures all the upserts to the metadata associated with a key hash
message KVMetadataWriteHash {
    bytes key_hash = 1;
    repeated KVMetadataEntry entries = 2;
}

// KVMetadataEntry captures a 'name'ed entry in the metadata of a key/key-hash.
message KVMetadataEntry {
    string name = 1;
    bytes value = 2;
}

// Version encapsulates the version of a Key
// A version of a committed key is maintained as the height of the transaction that committed the key.
// The height is represenetd as a tuple <blockNum, txNum> where the txNum is the position of the transaction
// (starting with 0) within block
message Version {
    uint64 block_num = 1;
    uint64 tx_num = 2;
}

// RangeQueryInfo encapsulates the details of a range query performed by a transaction during simulation.
// This helps protect transactions from phantom reads by varifying during validation whether any new items
// got committed within the given range between transaction simuation and validation
// (in addition to regular checks for updates/deletes of the existing items).
// readInfo field contains either the KVReads (for the items read by the range query) or a merkle-tree hash
// if the KVReads exceeds a pre-configured numbers
message RangeQueryInfo {
    string start_key = 1;
    string end_key = 2;
    bool itr_exhausted = 3;
    oneof reads_info {
        QueryReads raw_reads = 4;
        QueryReadsMerkleSummary reads_merkle_hashes = 5;
    }
}

// QueryReads encapsulates the KVReads for the items read by a transaction as a result of a query execution
message QueryReads {
    repeated KVRead kv_reads = 1;
}

// QueryReadsMerkleSummary encapsulates the Merkle-tree hashes for the QueryReads
// This allows to reduce the size of RWSet in the presence of query results
// by storing certain hashes instead of actual results.
// maxDegree field refers to the maximum number of children in the tree at any level
// maxLevel field contains the lowest level which has lesser nodes than maxDegree (starting from leaf level)
message QueryReadsMerkleSummary {
    uint32 max_degree = 1;
    uint32 max_level = 2;
    repeated bytes max_level_hashes = 3;
}

src:./ledger/queryresult/kv_query_result.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package queryresult;

option go_package = "github.com/hyperledger/fabric-protos-go/ledger/queryresult";
option java_package = "org.hyperledger.fabric.protos.ledger.queryresult";

import "google/protobuf/timestamp.proto";


// KV -- QueryResult for range/execute query. Holds a key and corresponding value.
message KV {
    string namespace = 1;
    string key = 2;
    bytes value = 3;
}

// KeyModification -- QueryResult for history query. Holds a transaction ID, value,
// timestamp, and delete marker which resulted from a history query.
message KeyModification {
    string tx_id = 1;
    bytes value = 2;
    google.protobuf.Timestamp timestamp = 3;
    bool is_delete = 4;
}

src:./discovery/protocol.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/discovery";
option java_package = "org.hyperledger.fabric.protos.discovery";

package discovery;

import "gossip/message.proto";
import "msp/msp_config.proto";

// Discovery defines a service that serves information about the fabric network
// like which peers, orderers, chaincodes, etc.
service Discovery {
    // Discover receives a signed request, and returns a response.
    rpc Discover (SignedRequest) returns (Response);
}

// SignedRequest contains a serialized Request in the payload field
// and a signature.
// The identity that is used to verify the signature
// can be extracted from the authentication field of type AuthInfo
// in the Request itself after deserializing it.
message SignedRequest {
    bytes payload   = 1;
    bytes signature = 2;
}

// Request contains authentication info about the client that sent the request
// and the queries it wishes to query the service
message Request {
    // authentication contains information that the service uses to check
    // the client's eligibility for the queries.
    AuthInfo authentication = 1;
    // queries
    repeated Query queries = 2;
}

message Response {
    // The results are returned in the same order of the queries
    repeated QueryResult results = 1;
}

// AuthInfo aggregates authentication information that the server uses
// to authenticate the client
message AuthInfo {
    // This is the identity of the client that is used to verify the signature
    // on the SignedRequest's payload.
    // It is a msp.SerializedIdentity in bytes form
    bytes client_identity = 1;

    // This is the hash of the client's TLS cert.
    // When the network is running with TLS, clients that don't include a certificate
    // will be denied access to the service.
    // Since the Request is encapsulated with a SignedRequest (which is signed),
    // this binds the TLS session to the enrollement identity of the client and
    // therefore both authenticates the client to the server,
    // and also prevents the server from relaying the request message to another server.
    bytes client_tls_cert_hash = 2;
}

// Query asks for information in the context of a specific channel
message Query {
    string channel = 1;
    oneof query {
        // ConfigQuery is used to query for the configuration of the channel,
        // such as FabricMSPConfig, and rorderer endpoints.
        // The client has to query a peer it trusts as it doesn't have means to self-verify
        // the authenticity of the returned result.
        // The result is returned in the form of ConfigResult.
        ConfigQuery config_query = 2;

        // PeerMembershipQuery queries for peers in a channel context,
        // and returns PeerMembershipResult
        PeerMembershipQuery peer_query = 3;

        // ChaincodeQuery queries for chaincodes by their name and version.
        // An empty version means any version can by returned.
        ChaincodeQuery cc_query = 4;

        // LocalPeerQuery queries for peers in a non channel context,
        // and returns PeerMembershipResult
        LocalPeerQuery local_peers = 5;
    }
}

// QueryResult contains a result for a given Query.
// The corresponding Query can be inferred by the index of the QueryResult from
// its enclosing Response message.
// QueryResults are ordered in the same order as the Queries are ordered in their enclosing Request.
message QueryResult {
    oneof result {
        // Error indicates failure or refusal to process the query
        Error error = 1;

        // ConfigResult contains the configuration of the channel,
        // such as FabricMSPConfig and orderer endpoints
        ConfigResult config_result = 2;

        // ChaincodeQueryResult contains information about chaincodes,
        // and their corresponding endorsers
        ChaincodeQueryResult cc_query_res = 3;

        // PeerMembershipResult contains information about peers,
        // such as their identity, endpoints, and channel related state.
        PeerMembershipResult members = 4;
    }
}

// ConfigQuery requests a ConfigResult
message ConfigQuery {

}

message ConfigResult {
    // msps is a map from MSP_ID to FabricMSPConfig
    map<string, msp.FabricMSPConfig> msps = 1;
    // orderers is a map from MSP_ID to endpoint lists of orderers
    map<string, Endpoints> orderers = 2;
}

// PeerMembershipQuery requests PeerMembershipResult.
// The filter field may be optionally populated in order
// for the peer membership to be filtered according to
// chaincodes that are installed on peers and collection
// access control policies.
message PeerMembershipQuery {
    ChaincodeInterest filter = 1;
}

// PeerMembershipResult contains peers mapped by their organizations (MSP_ID)
message PeerMembershipResult {
    map<string, Peers> peers_by_org = 1;
}

// ChaincodeQuery requests ChaincodeQueryResults for a given
// list of chaincode invocations.
// Each invocation is a separate one, and the endorsement policy
// is evaluated independantly for each given interest.
message ChaincodeQuery {
    repeated ChaincodeInterest interests = 1;
}

// ChaincodeInterest defines an interest about an endorsement
// for a specific single chaincode invocation.
// Multiple chaincodes indicate chaincode to chaincode invocations.
message ChaincodeInterest {
    repeated ChaincodeCall chaincodes = 1;
}

// ChaincodeCall defines a call to a chaincode.
// It may have collections that are related to the chaincode
message ChaincodeCall {
    string name = 1;
    repeated string collection_names = 2;
}

// ChaincodeQueryResult contains EndorsementDescriptors for
// chaincodes
message ChaincodeQueryResult {
    repeated EndorsementDescriptor content = 1;
}

// LocalPeerQuery queries for peers in a non channel context
message LocalPeerQuery {
}

// EndorsementDescriptor contains information about which peers can be used
// to request endorsement from, such that the endorsement policy would be fulfilled.
// Here is how to compute a set of peers to ask an endorsement from, given an EndorsementDescriptor:
// Let e: G --> P be the endorsers_by_groups field that maps a group to a set of peers.
// Note that applying e on a group g yields a set of peers.
// 1) Select a layout l: G --> N out of the layouts given.
//    l is the quantities_by_group field of a Layout, and it maps a group to an integer.
// 2) R = {}  (an empty set of peers)
// 3) For each group g in the layout l, compute n = l(g)
//    3.1) Denote P_g as a set of n random peers {p0, p1, ... p_n} selected from e(g)
//    3.2) R = R U P_g  (add P_g to R)
// 4) The set of peers R is the peers the client needs to request endorsements from
message EndorsementDescriptor {
    string chaincode = 1;
    // Specifies the endorsers, separated to groups.
    map<string, Peers> endorsers_by_groups = 2;

    // Specifies options of fulfulling the endorsement policy.
    // Each option lists the group names, and the amount of signatures needed
    // from each group.
    repeated Layout layouts = 3;
}

// Layout contains a mapping from a group name to number of peers
// that are needed for fulfilling an endorsement policy
message Layout {
    // Specifies how many non repeated signatures of each group
    // are needed for endorsement
    map<string, uint32> quantities_by_group = 1;
}

// Peers contains a list of Peer(s)
message Peers {
    repeated Peer peers = 1;
}

// Peer contains information about the peer such as its channel specific
// state, and membership information.
message Peer {
    // This is an Envelope of a GossipMessage with a gossip.StateInfo message
    gossip.Envelope state_info = 1;
    // This is an Envelope of a GossipMessage with a gossip.AliveMessage message
    gossip.Envelope membership_info = 2;

    // This is the msp.SerializedIdentity of the peer, represented in bytes.
    bytes identity = 3;
}

// Error denotes that something went wrong and contains the error message
message Error {
    string content = 1;
}

// Endpoints is a list of Endpoint(s)
message Endpoints {
    repeated Endpoint endpoint = 1;
}

// Endpoint is a combination of a host and a port
message Endpoint {
    string host = 1;
    uint32 port = 2;
}

src:./orderer/configuration.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer";
option java_package = "org.hyperledger.fabric.protos.orderer";

package orderer;

// The orderer config is specified by the following convention:
//   For a configuration item with key "Key"
//   the encoded value is a a proto message of type "Key"
//   For example, for the configuration item of name "ConsensusType"
//   the encoded value is the proto message "ConsensusType"

message ConsensusType {
    // The consensus type: "solo", "kafka" or "etcdraft".
    string type = 1;
    // Opaque metadata, dependent on the consensus type.
    bytes metadata = 2;

    // State defines the orderer mode of operation, typically for consensus-type migration.
    // NORMAL is during normal operation, when consensus-type migration is not, and can not, take place.
    // MAINTENANCE is when the consensus-type can be changed.
    enum State {
        STATE_NORMAL = 0;
        STATE_MAINTENANCE = 1;
    }
    // The state signals the ordering service to go into maintenance mode, typically for consensus-type migration.
    State state = 3;
}

message BatchSize {
    // Simply specified as number of messages for now, in the future
    // we may want to allow this to be specified by size in bytes
    uint32 max_message_count = 1;
    // The byte count of the serialized messages in a batch cannot
    // exceed this value.
    uint32 absolute_max_bytes = 2;
    // The byte count of the serialized messages in a batch should not
    // exceed this value.
    uint32 preferred_max_bytes = 3;
}

message BatchTimeout {
    // Any duration string parseable by ParseDuration():
    // https://golang.org/pkg/time/#ParseDuration
    string timeout = 1;
}

// Carries a list of bootstrap brokers, i.e. this is not the exclusive set of
// brokers an ordering service
message KafkaBrokers {
    // Each broker here should be identified using the (IP|host):port notation,
    // e.g. 127.0.0.1:7050, or localhost:7050 are valid entries
    repeated string brokers = 1;
}

// ChannelRestrictions is the mssage which conveys restrictions on channel creation for an orderer
message ChannelRestrictions {
    uint64 max_count = 1; // The max count of channels to allow to be created, a value of 0 indicates no limit
}

src:./orderer/kafka.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer";
option java_package = "org.hyperledger.fabric.protos.orderer";

package orderer;

// KafkaMessage is a wrapper type for the messages
// that the Kafka-based orderer deals with.
message KafkaMessage {
    oneof Type {
        KafkaMessageRegular regular = 1;
        KafkaMessageTimeToCut time_to_cut = 2;
        KafkaMessageConnect connect = 3;
    }
}

// KafkaMessageRegular wraps a marshalled envelope.
message KafkaMessageRegular {
    enum Class {
        UNKNOWN = 0;
        NORMAL = 1;
        CONFIG = 2;
    }
    bytes payload = 1;
    uint64 config_seq = 2;
    Class class = 3;
    int64 original_offset = 4;
}

// KafkaMessageTimeToCut is used to signal to the orderers
// that it is time to cut block <block_number>.
message KafkaMessageTimeToCut {
    uint64 block_number = 1;
}

// KafkaMessageConnect is posted by an orderer upon booting up.
// It is used to prevent the panic that would be caused if we
// were to consume an empty partition. It is ignored by all
// orderers when processing the partition.
message KafkaMessageConnect {
    bytes payload = 1;
}

// KafkaMetadata is encoded into the ORDERER block to keep track of
// Kafka-related metadata associated with this block.
message KafkaMetadata {
    // LastOffsetPersisted is the encoded value for the Metadata message
    // which is encoded in the ORDERER block metadata index for the case
    // of the Kafka-based orderer.
    int64 last_offset_persisted = 1;

    // LastOriginalOffsetProcessed is used to keep track of the newest
    // offset processed if a message is re-validated and re-ordered.
    // This value is used to deduplicate re-submitted messages from
    // multiple orderer so that we don't bother re-processing it again.
    int64 last_original_offset_processed = 2;

    // LastResubmittedConfigOffset is used to capture the newest offset of
    // CONFIG kafka message, which is revalidated and resubmitted. By comparing
    // this with LastOriginalOffsetProcessed, we could detemine whether there
    // are still CONFIG messages that have been resubmitted but NOT processed
    // yet. It's used as condition to block ingress messages, so we could reduce
    // the overhead of repeatedly resubmitting messages as config seq keeps
    // advancing.
    int64 last_resubmitted_config_offset = 3;
}

src:./orderer/ab.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer";
option java_package = "org.hyperledger.fabric.protos.orderer";

package orderer;

import "common/common.proto";

message BroadcastResponse {
    // Status code, which may be used to programatically respond to success/failure
    common.Status status = 1;
    // Info string which may contain additional information about the status returned
    string info = 2;
}

message SeekNewest { }

message SeekOldest { }

message SeekSpecified {
    uint64 number = 1;
}

message SeekPosition {
    oneof Type {
        SeekNewest newest = 1;
        SeekOldest oldest = 2;
        SeekSpecified specified = 3;
    }
}

// SeekInfo specifies the range of requested blocks to return
// If the start position is not found, an error is immediately returned
// Otherwise, blocks are returned until a missing block is encountered, then behavior is dictated
// by the SeekBehavior specified.
message SeekInfo {
   // If BLOCK_UNTIL_READY is specified, the reply will block until the requested blocks are available,
   // if FAIL_IF_NOT_READY is specified, the reply will return an error indicating that the block is not
   // found.  To request that all blocks be returned indefinitely as they are created, behavior should be
   // set to BLOCK_UNTIL_READY and the stop should be set to specified with a number of MAX_UINT64
    enum SeekBehavior {
        BLOCK_UNTIL_READY = 0;
        FAIL_IF_NOT_READY = 1;
    }

    // SeekErrorTolerance indicates to the server how block provider errors should be tolerated.  By default,
    // if the deliver service detects a problem in the underlying block source (typically, in the orderer,
    // a consenter error), it will begin to reject deliver requests.  This is to prevent a client from waiting
    // for blocks from an orderer which is stuck in an errored state.  This is almost always the desired behavior
    // and clients should stick with the default STRICT checking behavior.  However, in some scenarios, particularly
    // when attempting to recover from a crash or other corruption, it's desirable to force an orderer to respond
    // with blocks on a best effort basis, even if the backing consensus implementation is in an errored state.
    // In this case, set the SeekErrorResponse to BEST_EFFORT to ignore the consenter errors.
    enum SeekErrorResponse {
        STRICT = 0;
        BEST_EFFORT = 1;
    }
    SeekPosition start = 1;               // The position to start the deliver from
    SeekPosition stop = 2;                // The position to stop the deliver
    SeekBehavior behavior = 3;            // The behavior when a missing block is encountered
    SeekErrorResponse error_response = 4; // How to respond to errors reported to the deliver service
}

message DeliverResponse {
    oneof Type {
        common.Status status = 1;
        common.Block block = 2;
    }
}

service AtomicBroadcast {
    // broadcast receives a reply of Acknowledgement for each common.Envelope in order, indicating success or type of failure
    rpc Broadcast(stream common.Envelope) returns (stream BroadcastResponse);

    // deliver first requires an Envelope of type DELIVER_SEEK_INFO with Payload data as a mashaled SeekInfo message, then a stream of block replies is received.
    rpc Deliver(stream common.Envelope) returns (stream DeliverResponse);
}

src:./orderer/cluster.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer";
option java_package = "org.hyperledger.fabric.protos.orderer";

package orderer;

import "common/common.proto";

// Cluster defines communication between cluster members.
service Cluster {
    // Step passes an implementation-specific message to another cluster member.
    rpc Step(stream StepRequest) returns (stream StepResponse);
}

// StepRequest wraps a message that is sent to a cluster member.
message StepRequest {
    oneof payload {
        // consensus_request is a consensus specific message.
        ConsensusRequest consensus_request = 1;
        // submit_request is a relay of a transaction.
        SubmitRequest submit_request = 2;
    }
}

// StepResponse is a message received from a cluster member.
message StepResponse {
    oneof payload {
        SubmitResponse submit_res = 1;
    }
}

// ConsensusRequest is a consensus specific message sent to a cluster member.
message ConsensusRequest {
    string channel = 1;
    bytes payload = 2;
    bytes metadata = 3;
}

// SubmitRequest wraps a transaction to be sent for ordering.
message SubmitRequest {
    string channel = 1;
    // last_validation_seq denotes the last
    // configuration sequence at which the
    // sender validated this message.
    uint64 last_validation_seq = 2;
    // content is the fabric transaction
    // that is forwarded to the cluster member.
    common.Envelope payload = 3;
}

// SubmitResponse returns a success
// or failure status to the sender.
message SubmitResponse {
    string channel = 1;
    // Status code, which may be used to programatically respond to success/failure.
    common.Status status = 2;
    // Info string which may contain additional information about the returned status.
    string info = 3;
}

src:./orderer/etcdraft/configuration.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer/etcdraft";
option java_package = "org.hyperledger.fabric.protos.orderer.etcdraft";

package etcdraft;

// ConfigMetadata is serialized and set as the value of ConsensusType.Metadata in
// a channel configuration when the ConsensusType.Type is set "etcdraft".
message ConfigMetadata {
    repeated Consenter consenters = 1;
    Options options = 2;
}

// Consenter represents a consenting node (i.e. replica).
message Consenter {
    string host = 1;
    uint32 port = 2;
    bytes client_tls_cert = 3;
    bytes server_tls_cert = 4;
}

// Options to be specified for all the etcd/raft nodes. These can be modified on a
// per-channel basis.
message Options {
    string tick_interval = 1; // time duration format, e.g. 500ms
    uint32 election_tick = 2;
    uint32 heartbeat_tick = 3;
    uint32 max_inflight_blocks = 4;
    // Take snapshot when cumulative data exceeds certain size in bytes.
    uint32 snapshot_interval_size = 5;
}

src:./orderer/etcdraft/metadata.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/orderer/etcdraft";
option java_package = "org.hyperledger.fabric.protos.orderer.etcdraft";

package etcdraft;

// BlockMetadata stores data used by the Raft OSNs when
// coordinating with each other, to be serialized into
// block meta dta field and used after failres and restarts.
message BlockMetadata {
    // Maintains a mapping between the cluster's OSNs
    // and their Raft IDs.
    repeated uint64 consenter_ids = 1;
    // Carries the Raft ID value that will be assigned
    // to the next OSN that will join this cluster.
    uint64 next_consenter_id = 2;
    // Index of etcd/raft entry for current block.
    uint64 raft_index = 3;
}

// ClusterMetadata encapsulates metadata that is exchanged among cluster nodes
message ClusterMetadata {
    // Indicates active nodes in cluster that are reacheable by Raft leader
    repeated uint64 active_nodes = 1;
}

src:./gossip/message.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/gossip";
option java_package = "org.hyperledger.fabric.protos.gossip";

package gossip;

import "common/collection.proto";

// Gossip
service Gossip {

    // GossipStream is the gRPC stream used for sending and receiving messages
    rpc GossipStream (stream Envelope) returns (stream Envelope);

    // Ping is used to probe a remote peer's aliveness
    rpc Ping (Empty) returns (Empty);
}


// Envelope contains a marshalled
// GossipMessage and a signature over it.
// It may also contain a SecretEnvelope
// which is a marshalled Secret
message Envelope {
    bytes payload   = 1;
    bytes signature = 2;
    SecretEnvelope secret_envelope = 3;
}

// SecretEnvelope is a marshalled Secret
// and a signature over it.
// The signature should be validated by the peer
// that signed the Envelope the SecretEnvelope
// came with
message SecretEnvelope {
    bytes payload   = 1;
    bytes signature = 2;
}

// Secret is an entity that might be omitted
// from an Envelope when the remote peer that is receiving
// the Envelope shouldn't know the secret's content.
message Secret {
    oneof content {
        string internalEndpoint = 1;
    }
}

// GossipMessage defines the message sent in a gossip network
message GossipMessage {

    // used mainly for testing, but will might be used in the future
    // for ensuring message delivery by acking
    uint64 nonce  = 1;

    // The channel of the message.
    // Some GossipMessages may set this to nil, because
    // they are cross-channels but some may not
    bytes channel = 2;


    enum Tag {
        UNDEFINED    = 0;
        EMPTY        = 1;
        ORG_ONLY     = 2;
        CHAN_ONLY    = 3;
        CHAN_AND_ORG = 4;
        CHAN_OR_ORG  = 5;
    }

    // determines to which peers it is allowed
    // to forward the message
    Tag tag = 3;

    oneof content {
        // Membership
        AliveMessage alive_msg = 5;
        MembershipRequest mem_req = 6;
        MembershipResponse mem_res = 7;

        // Contains a ledger block
        DataMessage data_msg = 8;

        // Used for push&pull
        GossipHello hello = 9;
        DataDigest  data_dig = 10;
        DataRequest data_req = 11;
        DataUpdate  data_update = 12;

        // Empty message, used for pinging
        Empty empty = 13;

        // ConnEstablish, used for establishing a connection
        ConnEstablish conn = 14;

        // Used for relaying information
        // about state
        StateInfo state_info = 15;

        // Used for sending sets of StateInfo messages
        StateInfoSnapshot state_snapshot = 16;

        // Used for asking for StateInfoSnapshots
        StateInfoPullRequest state_info_pull_req = 17;

        //  Used to ask from a remote peer a set of blocks
        RemoteStateRequest state_request = 18;

        // Used to send a set of blocks to a remote peer
        RemoteStateResponse state_response = 19;

        // Used to indicate intent of peer to become leader
        LeadershipMessage leadership_msg = 20;

        // Used to learn of a peer's certificate
        PeerIdentity peer_identity = 21;

        Acknowledgement ack = 22;

        // Used to request private data
        RemotePvtDataRequest privateReq = 23;

        // Used to respond to private data requests
        RemotePvtDataResponse privateRes = 24;

        // Encapsulates private data used to distribute
        // private rwset after the endorsement
        PrivateDataMessage private_data = 25;
    }
}

// StateInfo is used for a peer to relay its state information
// to other peers
message StateInfo {
    PeerTime timestamp = 2;
    bytes pki_id       = 3;

    // channel_MAC is an authentication code that proves
    // that the peer that sent this message knows
    // the name of the channel.
    bytes channel_MAC  = 4;

    Properties properties = 5;
}

message Properties {
    uint64 ledger_height = 1;
    bool left_channel = 2;
    repeated Chaincode chaincodes = 3;
}

// StateInfoSnapshot is an aggregation of StateInfo messages
message StateInfoSnapshot {
    repeated Envelope elements = 1;
}

// StateInfoPullRequest is used to fetch a StateInfoSnapshot
// from a remote peer
message StateInfoPullRequest {
    // channel_MAC is an authentication code that proves
    // that the peer that sent this message knows
    // the name of the channel.
    bytes channel_MAC  = 1;
}

// ConnEstablish is the message used for the gossip handshake
// Whenever a peer connects to another peer, it handshakes
// with it by sending this message that proves its identity
message ConnEstablish {
    bytes pki_id          = 1;
    bytes identity        = 2;
    bytes tls_cert_hash   = 3;
}

// PeerIdentity defines the identity of the peer
// Used to make other peers learn of the identity
// of a certain peer
message PeerIdentity {
    bytes pki_id    = 1;
    bytes cert      = 2;
    bytes metadata  = 3;
}

// Messages related to pull mechanism

enum PullMsgType {
    UNDEFINED     = 0;
    BLOCK_MSG     = 1;
    IDENTITY_MSG  = 2;
}

// DataRequest is a message used for a peer to request
// certain data blocks from a remote peer
message DataRequest {
    uint64 nonce             = 1;
    repeated bytes digests  = 2;
    PullMsgType msg_type     = 3;
}

// GossipHello is the message that is used for the peer to initiate
// a pull round with another peer
message GossipHello {
    uint64 nonce         = 1;
    bytes metadata       = 2;
    PullMsgType msg_type = 3;
}

// DataUpdate is the final message in the pull phase
// sent from the receiver to the initiator
message DataUpdate {
    uint64 nonce                = 1;
    repeated Envelope data      = 2;
    PullMsgType msg_type        = 3;
}

// DataDigest is the message sent from the receiver peer
// to the initator peer and contains the data items it has
message DataDigest {
    uint64 nonce             = 1;
    repeated bytes digests  = 2; // Maybe change this to bitmap later on
    PullMsgType msg_type     = 3;
}


// Ledger block messages

// DataMessage is the message that contains a block
message DataMessage {
    Payload payload = 1;
}

// PrivateDataMessage message which includes private
// data information to distributed once transaction
// has been endorsed
message PrivateDataMessage {
    PrivatePayload payload = 1;
}

// Payload contains a block
message Payload {
    uint64 seq_num              = 1;
    bytes data                  = 2;
    repeated bytes private_data = 3;
}

// PrivatePayload payload to encapsulate private
// data with collection name to enable routing
// based on collection partitioning
message PrivatePayload {
    string collection_name      = 1;
    string namespace            = 2;
    string tx_id                = 3;
    bytes private_rwset         = 4;
    uint64 private_sim_height  = 5;
    common.CollectionConfigPackage collection_configs = 6;
}

// Membership messages

// AliveMessage is sent to inform remote peers
// of a peer's existence and activity
message AliveMessage {
    Member membership  = 1;
    PeerTime timestamp = 2;
    bytes identity     = 4;
}

// Leadership Message is sent during leader election to inform
// remote peers about intent of peer to proclaim itself as leader
message LeadershipMessage {
    bytes pki_id        = 1;
    PeerTime timestamp = 2;
    bool is_declaration = 3;
}

// PeerTime defines the logical time of a peer's life
message PeerTime {
    uint64 inc_num = 1;
    uint64 seq_num = 2;
}

// MembershipRequest is used to ask membership information
// from a remote peer
message MembershipRequest {
    Envelope self_information = 1;
    repeated bytes known         = 2;
}

// MembershipResponse is used for replying to MembershipRequests
message MembershipResponse {
    repeated Envelope alive = 1;
    repeated Envelope dead  = 2;
}

// Member holds membership-related information
// about a peer
message Member {
    string endpoint = 1;
    bytes  metadata = 2;
    bytes  pki_id    = 3;
}

// Empty is used for pinging and in tests
message Empty {}


// State transfer

// RemoteStateRequest is used to ask a set of blocks
// from a remote peer
message RemoteStateRequest {
    uint64 start_seq_num = 1;
    uint64 end_seq_num = 2;
}

// RemoteStateResponse is used to send a set of blocks
// to a remote peer
message RemoteStateResponse {
    repeated Payload payloads = 1;
}

// RemotePrivateDataRequest message used to request
// missing private rwset
message RemotePvtDataRequest {
    repeated PvtDataDigest digests = 1;
}

// PvtDataDigest defines a digest of private data
message PvtDataDigest {
    string tx_id = 1;
    string namespace = 2;
    string collection = 3;
    uint64 block_seq = 4;
    uint64 seq_in_block = 5;
}

// RemotePrivateData message to response on private
// data replication request
message RemotePvtDataResponse {
    repeated PvtDataElement elements = 1;
}

message PvtDataElement {
    PvtDataDigest digest = 1;
    // the payload is a marshaled kvrwset.KVRWSet
    repeated bytes payload = 2;
}

// PvtPayload augments private rwset data and tx index
// inside the block
message PvtDataPayload {
    uint64 tx_seq_in_block = 1;
    // Encodes marhslaed bytes of rwset.TxPvtReadWriteSet
    // defined in rwset.proto
    bytes payload = 2;
}

message Acknowledgement {
    string error = 1;
}

// Chaincode represents a Chaincode that is installed
// on a peer
message Chaincode {
    string name = 1;
    string version = 2;
    bytes metadata = 3;
}

src:./transientstore/transientstore.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package transientstore;

option go_package = "github.com/hyperledger/fabric-protos-go/transientstore";
option java_package = "org.hyperledger.fabric.protos.transientstore";

import "ledger/rwset/rwset.proto";
import "common/collection.proto";

// TxPvtReadWriteSetWithConfigInfo encapsulates the transaction's private
// read-write set and additional information about the configurations such as
// the latest collection config when the transaction is simulated
message TxPvtReadWriteSetWithConfigInfo {
    uint64 endorsed_at = 1;
    rwset.TxPvtReadWriteSet pvt_rwset = 2;
    map<string, common.CollectionConfigPackage> collection_configs = 3;
}

src:./common/configuration.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

// HashingAlgorithm is encoded into the configuration transaction as  a configuration item of type Chain
// with a Key of "HashingAlgorithm" and a Value of  HashingAlgorithm as marshaled protobuf bytes
message HashingAlgorithm {
    // Currently supported algorithms are: SHAKE256
    string name = 1;
}

// BlockDataHashingStructure is encoded into the configuration transaction as a configuration item of
// type Chain with a Key of "BlockDataHashingStructure" and a Value of HashingAlgorithm as marshaled protobuf bytes
message BlockDataHashingStructure {
    // width specifies the width of the Merkle tree to use when computing the BlockDataHash
    // in order to replicate flat hashing, set this width to MAX_UINT32
    uint32 width  = 1;
}

// OrdererAddresses is encoded into the configuration transaction as a configuration item of type Chain
// with a Key of "OrdererAddresses" and a Value of OrdererAddresses as marshaled protobuf bytes
message OrdererAddresses {
    repeated string addresses = 1;
}

// Consortium represents the consortium context in which the channel was created
message Consortium {
    string name = 1;
}


// Capabilities message defines the capabilities a particular binary must implement
// for that binary to be able to safely participate in the channel.  The capabilities
// message is defined at the /Channel level, the /Channel/Application level, and the
// /Channel/Orderer level.
//
// The /Channel level capabilties define capabilities which both the orderer and peer
// binaries must satisfy.  These capabilties might be things like a new MSP type,
// or a new policy type.
//
// The /Channel/Orderer level capabilties define capabilities which must be supported
// by the orderer, but which have no bearing on the behavior of the peer.  For instance
// if the orderer changes the logic for how it constructs new channels, only all orderers
// must agree on the new logic.  The peers do not need to be aware of this change as
// they only interact with the channel after it has been constructed.
//
// Finally, the /Channel/Application level capabilities define capabilities which the peer
// binary must satisfy, but which have no bearing on the orderer.  For instance, if the
// peer adds a new UTXO transaction type, or changes the chaincode lifecycle requirements,
// all peers must agree on the new logic.  However, orderers never inspect transactions
// this deeply, and therefore have no need to be aware of the change.
//
// The capabilities strings defined in these messages typically correspond to release
// binary versions (e.g. "V1.1"), and are used primarilly as a mechanism for a fully
// upgraded network to switch from one set of logic to a new one.
//
// Although for V1.1, the orderers must be upgraded to V1.1 prior to the rest of the
// network, going forward, because of the split between the /Channel, /Channel/Orderer
// and /Channel/Application capabilities.  It should be possible for the orderer and
// application networks to upgrade themselves independently (with the exception of any
// new capabilities defined at the /Channel level).
message Capabilities {
    map<string, Capability> capabilities = 1;
}

// Capability is an empty message for the time being.  It is defined as a protobuf
// message rather than a constant, so that we may extend capabilities with other fields
// if the need arises in the future.  For the time being, a capability being in the
// capabilities map requires that that capability be supported.
message Capability { }

src:./common/ledger.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

// Contains information about the blockchain ledger such as height, current
// block hash, and previous block hash.
message BlockchainInfo {
    uint64 height = 1;
    bytes currentBlockHash = 2;
    bytes previousBlockHash = 3;
}

src:./common/policies.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

import "msp/msp_principal.proto";

// Policy expresses a policy which the orderer can evaluate, because there has been some desire expressed to support
// multiple policy engines, this is typed as a oneof for now
message Policy {
    enum PolicyType {
        UNKNOWN = 0; // Reserved to check for proper initialization
        SIGNATURE = 1;
        MSP = 2;
        IMPLICIT_META = 3;
    }
    int32 type = 1; // For outside implementors, consider the first 1000 types reserved, otherwise one of PolicyType
    bytes value = 2;
}

// SignaturePolicyEnvelope wraps a SignaturePolicy and includes a version for future enhancements
message SignaturePolicyEnvelope {
    int32 version = 1;
    SignaturePolicy rule = 2;
    repeated MSPPrincipal identities = 3;
}

// SignaturePolicy is a recursive message structure which defines a featherweight DSL for describing
// policies which are more complicated than 'exactly this signature'.  The NOutOf operator is sufficent
// to express AND as well as OR, as well as of course N out of the following M policies
// SignedBy implies that the signature is from a valid certificate which is signed by the trusted
// authority specified in the bytes.  This will be the certificate itself for a self-signed certificate
// and will be the CA for more traditional certificates
message SignaturePolicy {
    message NOutOf {
        int32 n = 1;
        repeated SignaturePolicy rules = 2;
    }
    oneof Type {
        int32 signed_by = 1;
        NOutOf n_out_of = 2;
    }
}

// ImplicitMetaPolicy is a policy type which depends on the hierarchical nature of the configuration
// It is implicit because the rule is generate implicitly based on the number of sub policies
// It is meta because it depends only on the result of other policies
// When evaluated, this policy iterates over all immediate child sub-groups, retrieves the policy
// of name sub_policy, evaluates the collection and applies the rule.
// For example, with 4 sub-groups, and a policy name of "foo", ImplicitMetaPolicy retrieves
// each sub-group, retrieves policy "foo" for each subgroup, evaluates it, and, in the case of ANY
// 1 satisfied is sufficient, ALL would require 4 signatures, and MAJORITY would require 3 signatures.
message ImplicitMetaPolicy {
    enum Rule {
        ANY = 0;      // Requires any of the sub-policies be satisfied, if no sub-policies exist, always returns true
        ALL = 1;      // Requires all of the sub-policies be satisfied
        MAJORITY = 2; // Requires a strict majority (greater than half) of the sub-policies be satisfied
    }
    string sub_policy = 1;
    Rule rule = 2;
}

src:./common/configtx.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

import "common/common.proto";
import "common/policies.proto";

// ConfigEnvelope is designed to contain _all_ configuration for a chain with no dependency
// on previous configuration transactions.
//
// It is generated with the following scheme:
//   1. Retrieve the existing configuration
//   2. Note the config properties (ConfigValue, ConfigPolicy, ConfigGroup) to be modified
//   3. Add any intermediate ConfigGroups to the ConfigUpdate.read_set (sparsely)
//   4. Add any additional desired dependencies to ConfigUpdate.read_set (sparsely)
//   5. Modify the config properties, incrementing each version by 1, set them in the ConfigUpdate.write_set
//      Note: any element not modified but specified should already be in the read_set, so may be specified sparsely
//   6. Create ConfigUpdate message and marshal it into ConfigUpdateEnvelope.update and encode the required signatures
//     a) Each signature is of type ConfigSignature
//     b) The ConfigSignature signature is over the concatenation of signature_header and the ConfigUpdate bytes (which includes a ChainHeader)
//   5. Submit new Config for ordering in Envelope signed by submitter
//     a) The Envelope Payload has data set to the marshaled ConfigEnvelope
//     b) The Envelope Payload has a header of type Header.Type.CONFIG_UPDATE
//
// The configuration manager will verify:
//   1. All items in the read_set exist at the read versions
//   2. All items in the write_set at a different version than, or not in, the read_set have been appropriately signed according to their mod_policy
//   3. The new configuration satisfies the ConfigSchema
message ConfigEnvelope {
    Config config = 1;        // A marshaled Config structure
    Envelope last_update = 2; // The last CONFIG_UPDATE message which generated this current configuration
                              // Note that CONFIG_UPDATE has a Payload.Data of a Marshaled ConfigUpdate
}

message ConfigGroupSchema {
    map<string, ConfigGroupSchema> groups = 1;
    map<string, ConfigValueSchema> values = 2;
    map<string, ConfigPolicySchema> policies = 3;
}

message ConfigValueSchema {}

message ConfigPolicySchema {}

// Config represents the config for a particular channel
message Config {
    // Prevent removed tag re-use
    reserved 3;
    reserved "type";

    uint64 sequence = 1;
    ConfigGroup channel_group = 2; // channel_group is a bad name for this, it should be changed to root when API breakage is allowed
}

message ConfigUpdateEnvelope {
    bytes config_update = 1;                 // A marshaled ConfigUpdate structure
    repeated ConfigSignature signatures = 2; // Signatures over the config_update
}

// ConfigUpdate is used to submit a subset of config and to have the orderer apply to Config
// it is always submitted inside a ConfigUpdateEnvelope which allows the addition of signatures
// resulting in a new total configuration.  The update is applied as follows:
// 1. The versions from all of the elements in the read_set is verified against the versions in the existing config.
//    If there is a mismatch in the read versions, then the config update fails and is rejected.
// 2. Any elements in the write_set with the same version as the read_set are ignored.
// 3. The corresponding mod_policy for every remaining element in the write_set is collected.
// 4. Each policy is checked against the signatures from the ConfigUpdateEnvelope, any failing to verify are rejected
// 5. The write_set is applied to the Config and the ConfigGroupSchema verifies that the updates were legal
message ConfigUpdate {
    // Prevent removed tag re-use
    reserved 4;
    reserved "type";

    string channel_id = 1;                // Which channel this config update is for
    ConfigGroup read_set = 2;             // ReadSet explicitly lists the portion of the config which was read, this should be sparse with only Version set
    ConfigGroup write_set = 3;            // WriteSet lists the portion of the config which was written, this should included updated Versions
    map<string, bytes> isolated_data = 5; // Data which is not to be reflected in the resulting Config, but is still needed for some other purpose.  For instance, rscc_seed_data
}

// ConfigGroup is the hierarchical data structure for holding config
message ConfigGroup {
    uint64 version = 1;
    map<string,ConfigGroup> groups = 2;
    map<string,ConfigValue> values = 3;
    map<string,ConfigPolicy> policies = 4;
    string mod_policy = 5;
}

// ConfigValue represents an individual piece of config data
message ConfigValue {
    uint64 version = 1;
    bytes value = 2;
    string mod_policy = 3;
}

message ConfigPolicy {
    uint64 version = 1;
    Policy policy = 2;
    string mod_policy = 3;
}

message ConfigSignature {
    bytes signature_header = 1; // A marshaled SignatureHeader
    bytes signature = 2;        // Signature over the concatenation signatureHeader bytes and config bytes
}

src:./common/common.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

import "google/protobuf/timestamp.proto";

// These status codes are intended to resemble selected HTTP status codes
enum Status {
    UNKNOWN = 0;
    SUCCESS = 200;
    BAD_REQUEST = 400;
    FORBIDDEN = 403;
    NOT_FOUND = 404;
    REQUEST_ENTITY_TOO_LARGE = 413;
    INTERNAL_SERVER_ERROR = 500;
    NOT_IMPLEMENTED = 501;
    SERVICE_UNAVAILABLE = 503;
}

enum HeaderType {
    reserved 7, 9;
    reserved "PEER_RESOURCE_UPDATE", "TOKEN_TRANSACTION";

    MESSAGE = 0;                     // Used for messages which are signed but opaque
    CONFIG = 1;                      // Used for messages which express the channel config
    CONFIG_UPDATE = 2;               // Used for transactions which update the channel config
    ENDORSER_TRANSACTION = 3;        // Used by the SDK to submit endorser based transactions
    ORDERER_TRANSACTION = 4;         // Used internally by the orderer for management
    DELIVER_SEEK_INFO = 5;           // Used as the type for Envelope messages submitted to instruct the Deliver API to seek
    CHAINCODE_PACKAGE = 6;           // Used for packaging chaincode artifacts for install
    PEER_ADMIN_OPERATION = 8;        // Used for invoking an administrative operation on a peer
}

// This enum enlists indexes of the block metadata array
enum BlockMetadataIndex {
    SIGNATURES = 0;                  // Block metadata array position for block signatures
    LAST_CONFIG = 1;                 // Block metadata array position to store last configuration block sequence number
    TRANSACTIONS_FILTER = 2;         // Block metadata array position to store serialized bit array filter of invalid transactions
    ORDERER = 3 [deprecated=true];   /* Block metadata array position to store operational metadata for orderers
                                        e.g. For Kafka, this is where we store the last offset written to the local ledger */
    COMMIT_HASH = 4;                 /* Block metadata array position to store the hash of TRANSACTIONS_FILTER, State Updates,
                                        and the COMMIT_HASH of the previous block */
}

// LastConfig is the encoded value for the Metadata message which is encoded in the LAST_CONFIGURATION block metadata index
message LastConfig {
    uint64 index  = 1;
}

// Metadata is a common structure to be used to encode block metadata
message Metadata {
    bytes value = 1;
    repeated MetadataSignature signatures = 2;
}

message MetadataSignature {
    bytes signature_header = 1; // An encoded SignatureHeader
    bytes signature = 2;       // The signature over the concatenation of the Metadata value bytes, signatureHeader, and block header
}

message Header {
    bytes channel_header = 1;
    bytes signature_header = 2;
}

// Header is a generic replay prevention and identity message to include in a signed payload
message ChannelHeader {
    int32 type = 1; // Header types 0-10000 are reserved and defined by HeaderType

    // Version indicates message protocol version
    int32 version = 2;

    // Timestamp is the local time when the message was created
    // by the sender
    google.protobuf.Timestamp timestamp = 3;

    // Identifier of the channel this message is bound for
    string channel_id = 4;

    // An unique identifier that is used end-to-end.
    //  -  set by higher layers such as end user or SDK
    //  -  passed to the endorser (which will check for uniqueness)
    //  -  as the header is passed along unchanged, it will be
    //     be retrieved by the committer (uniqueness check here as well)
    //  -  to be stored in the ledger
    string tx_id = 5;

    // The epoch in which this header was generated, where epoch is defined based on block height
    // Epoch in which the response has been generated. This field identifies a
    // logical window of time. A proposal response is accepted by a peer only if
    // two conditions hold:
    // 1. the epoch specified in the message is the current epoch
    // 2. this message has been only seen once during this epoch (i.e. it hasn't
    //    been replayed)
    uint64 epoch = 6;

    // Extension that may be attached based on the header type
    bytes extension = 7;

    // If mutual TLS is employed, this represents
    // the hash of the client's TLS certificate
    bytes tls_cert_hash = 8;
}

message SignatureHeader {
    // Creator of the message, a marshaled msp.SerializedIdentity
    bytes creator = 1;

    // Arbitrary number that may only be used once. Can be used to detect replay attacks.
    bytes nonce = 2;
}

// Payload is the message contents (and header to allow for signing)
message Payload {

    // Header is included to provide identity and prevent replay
    Header header = 1;

    // Data, the encoding of which is defined by the type in the header
    bytes data = 2;
}

// Envelope wraps a Payload with a signature so that the message may be authenticated
message Envelope {
    // A marshaled Payload
    bytes payload = 1;

    // A signature by the creator specified in the Payload header
    bytes signature = 2;
}

// This is finalized block structure to be shared among the orderer and peer
// Note that the BlockHeader chains to the previous BlockHeader, and the BlockData hash is embedded
// in the BlockHeader.  This makes it natural and obvious that the Data is included in the hash, but
// the Metadata is not.
message Block {
    BlockHeader header = 1;
    BlockData data = 2;
    BlockMetadata metadata = 3;
}

// BlockHeader is the element of the block which forms the block chain
// The block header is hashed using the configured chain hashing algorithm
// over the ASN.1 encoding of the BlockHeader
message BlockHeader {
    uint64 number = 1; // The position in the blockchain
    bytes previous_hash = 2; // The hash of the previous block header
    bytes data_hash = 3; // The hash of the BlockData, by MerkleTree
}

message BlockData {
    repeated bytes data = 1;
}

message BlockMetadata {
    repeated bytes metadata = 1;
}

// OrdererBlockMetadata defines metadata that is set by the ordering service.
message OrdererBlockMetadata {
    LastConfig last_config = 1;
    bytes consenter_metadata = 2;
}

src:./common/collection.proto


// Copyright the Hyperledger Fabric contributors. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

option go_package = "github.com/hyperledger/fabric-protos-go/common";
option java_package = "org.hyperledger.fabric.protos.common";

package common;

import "common/policies.proto";

// CollectionConfigPackage represents an array of CollectionConfig
// messages; the extra struct is required because repeated oneof is
// forbidden by the protobuf syntax
message CollectionConfigPackage {
    repeated CollectionConfig config = 1;
}

// CollectionConfig defines the configuration of a collection object;
// it currently contains a single, static type.
// Dynamic collections are deferred.
message CollectionConfig {
    oneof payload {
        StaticCollectionConfig static_collection_config = 1;
    }
}


// StaticCollectionConfig constitutes the configuration parameters of a
// static collection object. Static collections are collections that are
// known at chaincode instantiation time, and that cannot be changed.
// Dynamic collections are deferred.
message StaticCollectionConfig {
    // the name of the collection inside the denoted chaincode
    string name = 1;
    // a reference to a policy residing / managed in the config block
    // to define which orgs have access to this collection’s private data
    CollectionPolicyConfig member_orgs_policy = 2;
    // The minimum number of peers private data will be sent to upon
    // endorsement. The endorsement would fail if dissemination to at least
    // this number of peers is not achieved.
    int32 required_peer_count = 3;
    // The maximum number of peers that private data will be sent to
    // upon endorsement. This number has to be bigger than required_peer_count.
    int32 maximum_peer_count = 4;
    // The number of blocks after which the collection data expires.
    // For instance if the value is set to 10, a key last modified by block number 100
    // will be purged at block number 111. A zero value is treated same as MaxUint64
    uint64 block_to_live = 5;
    // The member only read access denotes whether only collection member clients
    // can read the private data (if set to true), or even non members can
    // read the data (if set to false, for example if you want to implement more granular
    // access logic in the chaincode)
    bool member_only_read = 6;
    // The member only write access denotes whether only collection member clients
    // can write the private data (if set to true), or even non members can
    // write the data (if set to false, for example if you want to implement more granular
    // access logic in the chaincode)
    bool member_only_write = 7;
}


// Collection policy configuration. Initially, the configuration can only
// contain a SignaturePolicy. In the future, the SignaturePolicy may be a
// more general Policy. Instead of containing the actual policy, the
// configuration may in the future contain a string reference to a policy.
message CollectionPolicyConfig {
    oneof payload {
        // Initially, only a signature policy is supported.
        SignaturePolicyEnvelope signature_policy = 1;
        // Later, the SignaturePolicy will be replaced by a Policy.
        //        Policy policy = 1;
        // A reference to a Policy is planned to be added later.
//        string reference = 2;
    }
}


// CollectionCriteria defines an element of a private data that corresponds
// to a certain transaction and collection
message CollectionCriteria {
    string channel = 1;
    string tx_id = 2;
    string collection = 3;
    string namespace = 4;
}

Hyperledger Sawtooth

hyperledger/sawtooth-core

TOC

學習資源

The Linux Foundation 開在 edX 的免費 Hyperledger Sawtooth 開發課程。

Hyperledger Sawtooth for Application Developers

生成 Google Protocol Buffers 文件

pseudomuto/protoc-gen-doc: Documentation generator plugin for Google Protocol Buffers

git clone https://github.com/hyperledger/sawtooth-core.git /tmp/src/sawtooth
bash tc.sh --gen-proto-doc /tmp/src/sawtooth/protos /tmp/output.md

Generated Date:2019-09-11T16:57:31+08:00

Protocol Documentation

Table of Contents

Top

transaction.proto

Transaction

FieldTypeLabelDescription
headerbytesThe serialized version of the TransactionHeader
header_signaturestringThe signature derived from signing the header
payloadbytesThe payload is the encoded family specific information of the transaction. Example cbor({'Verb': verb, 'Name': name,'Value': value})

TransactionHeader

FieldTypeLabelDescription
batcher_public_keystringPublic key for the client who added this transaction to a batch
dependenciesstringrepeatedA list of transaction signatures that describe the transactions that must be processed before this transaction can be valid
family_namestringThe family name correlates to the transaction processor's family name that this transaction can be processed on, for example 'intkey'
family_versionstringThe family version correlates to the transaction processor's family version that this transaction can be processed on, for example "1.0"
inputsstringrepeatedA list of addresses that are given to the context manager and control what addresses the transaction processor is allowed to read from.
noncestringA random string that provides uniqueness for transactions with otherwise identical fields.
outputsstringrepeatedA list of addresses that are given to the context manager and control what addresses the transaction processor is allowed to write to.
payload_sha512stringThe sha512 hash of the encoded payload
signer_public_keystringPublic key for the client that signed the TransactionHeader

TransactionList

A simple list of transactions that needs to be serialized before it can be transmitted to a batcher.

FieldTypeLabelDescription
transactionsTransactionrepeated

Top

client_status.proto

ClientStatusGetRequest

A request to get miscellaneous information about the validator

ClientStatusGetResponse

FieldTypeLabelDescription
statusClientStatusGetResponse.Status
peersClientStatusGetResponse.Peerrepeated
endpointstringThe validator's public network endpoint

ClientStatusGetResponse.Peer

Information about the validator's peers

FieldTypeLabelDescription
endpointstringThe peer's public network endpoint

ClientStatusGetResponse.Status

The status of the response message, not the validator's status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

Top

validator.proto

Message

The message passed between the validator and client, containing the header fields and content.

FieldTypeLabelDescription
message_typeMessage.MessageTypeThe type of message, used to determine how to 'route' the message to the appropriate handler as well as how to deserialize the content.
correlation_idstringThe identifier used to correlate response messages to their related request messages. correlation_id should be set to a random string for messages which are not responses to previously sent messages. For response messages, correlation_id should be set to the same string as contained in the request message.
contentbytesThe content of the message, defined by message_type. In many cases, this data has been serialized with Protocol Buffers or CBOR.

MessageList

A list of messages to be transmitted together.

FieldTypeLabelDescription
messagesMessagerepeated

Message.MessageType

NameNumberDescription
DEFAULT0
TP_REGISTER_REQUEST1Registration request from the transaction processor to the validator
TP_REGISTER_RESPONSE2Registration response from the validator to the transaction processor
TP_UNREGISTER_REQUEST3Tell the validator that the transaction processor won't take any more transactions
TP_UNREGISTER_RESPONSE4Response from the validator to the tp that it won't send any more transactions
TP_PROCESS_REQUEST5Process Request from the validator/executor to the transaction processor
TP_PROCESS_RESPONSE6Process response from the transaction processor to the validator/executor
TP_STATE_GET_REQUEST7State get request from the transaction processor to validator/context_manager
TP_STATE_GET_RESPONSE8State get response from the validator/context_manager to the transaction processor
TP_STATE_SET_REQUEST9State set request from the transaction processor to the validator/context_manager
TP_STATE_SET_RESPONSE10State set response from the validator/context_manager to the transaction processor
TP_STATE_DELETE_REQUEST11State delete request from the transaction processor to the validator/context_manager
TP_STATE_DELETE_RESPONSE12State delete response from the validator/context_manager to the transaction processor
TP_RECEIPT_ADD_DATA_REQUEST13Message to append data to a transaction receipt
TP_RECEIPT_ADD_DATA_RESPONSE14Response from validator to tell transaction processor that data has been appended
TP_EVENT_ADD_REQUEST15Message to add event
TP_EVENT_ADD_RESPONSE16Response from validator to tell transaction processor that event has been created
CLIENT_BATCH_SUBMIT_REQUEST100Submission of a batchlist from the web api or another client to the validator
CLIENT_BATCH_SUBMIT_RESPONSE101Response from the validator to the web api/client that the submission was accepted
CLIENT_BLOCK_LIST_REQUEST102A request to list blocks from the web api/client to the validator
CLIENT_BLOCK_LIST_RESPONSE103
CLIENT_BLOCK_GET_BY_ID_REQUEST104
CLIENT_BLOCK_GET_RESPONSE105
CLIENT_BATCH_LIST_REQUEST106
CLIENT_BATCH_LIST_RESPONSE107
CLIENT_BATCH_GET_REQUEST108
CLIENT_BATCH_GET_RESPONSE109
CLIENT_TRANSACTION_LIST_REQUEST110
CLIENT_TRANSACTION_LIST_RESPONSE111
CLIENT_TRANSACTION_GET_REQUEST112
CLIENT_TRANSACTION_GET_RESPONSE113
CLIENT_STATE_CURRENT_REQUEST114Client state request of the current state hash to be retrieved from the journal
CLIENT_STATE_CURRENT_RESPONSE115Response with the current state hash
CLIENT_STATE_LIST_REQUEST116A request of all the addresses under a particular prefix, for a state hash.
CLIENT_STATE_LIST_RESPONSE117The response of the addresses
CLIENT_STATE_GET_REQUEST118Get the address:data entry at a particular address
CLIENT_STATE_GET_RESPONSE119The response with the entry
CLIENT_BATCH_STATUS_REQUEST120A request for the status of a batch or batches
CLIENT_BATCH_STATUS_RESPONSE121A response with the batch statuses
CLIENT_RECEIPT_GET_REQUEST122A request for one or more transaction receipts
CLIENT_RECEIPT_GET_RESPONSE123A response with the receipts
CLIENT_BLOCK_GET_BY_NUM_REQUEST124
CLIENT_PEERS_GET_REQUEST125A request for a validator's peers
CLIENT_PEERS_GET_RESPONSE126A response with the validator's peers
CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST127
CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST128
CLIENT_STATUS_GET_REQUEST129A request for a validator's status
CLIENT_STATUS_GET_RESPONSE130A response with the validator's status
CLIENT_EVENTS_SUBSCRIBE_REQUEST500Message types for events
CLIENT_EVENTS_SUBSCRIBE_RESPONSE501
CLIENT_EVENTS_UNSUBSCRIBE_REQUEST502
CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE503
CLIENT_EVENTS504
CLIENT_EVENTS_GET_REQUEST505
CLIENT_EVENTS_GET_RESPONSE506
GOSSIP_MESSAGE200Temp message types until a discussion can be had about gossip msg
GOSSIP_REGISTER201
GOSSIP_UNREGISTER202
GOSSIP_BLOCK_REQUEST205
GOSSIP_BLOCK_RESPONSE206
GOSSIP_BATCH_BY_BATCH_ID_REQUEST207
GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST208
GOSSIP_BATCH_RESPONSE209
GOSSIP_GET_PEERS_REQUEST210
GOSSIP_GET_PEERS_RESPONSE211
GOSSIP_CONSENSUS_MESSAGE212
NETWORK_ACK300
NETWORK_CONNECT301
NETWORK_DISCONNECT302
AUTHORIZATION_CONNECTION_RESPONSE600Message types for Authorization Types
AUTHORIZATION_VIOLATION601
AUTHORIZATION_TRUST_REQUEST602
AUTHORIZATION_TRUST_RESPONSE603
AUTHORIZATION_CHALLENGE_REQUEST604
AUTHORIZATION_CHALLENGE_RESPONSE605
AUTHORIZATION_CHALLENGE_SUBMIT606
AUTHORIZATION_CHALLENGE_RESULT607
PING_REQUEST700
PING_RESPONSE701
CONSENSUS_REGISTER_REQUEST800Consensus service messages
CONSENSUS_REGISTER_RESPONSE801
CONSENSUS_SEND_TO_REQUEST802
CONSENSUS_SEND_TO_RESPONSE803
CONSENSUS_BROADCAST_REQUEST804
CONSENSUS_BROADCAST_RESPONSE805
CONSENSUS_INITIALIZE_BLOCK_REQUEST806
CONSENSUS_INITIALIZE_BLOCK_RESPONSE807
CONSENSUS_FINALIZE_BLOCK_REQUEST808
CONSENSUS_FINALIZE_BLOCK_RESPONSE809
CONSENSUS_SUMMARIZE_BLOCK_REQUEST828
CONSENSUS_SUMMARIZE_BLOCK_RESPONSE829
CONSENSUS_CANCEL_BLOCK_REQUEST810
CONSENSUS_CANCEL_BLOCK_RESPONSE811
CONSENSUS_CHECK_BLOCKS_REQUEST812
CONSENSUS_CHECK_BLOCKS_RESPONSE813
CONSENSUS_COMMIT_BLOCK_REQUEST814
CONSENSUS_COMMIT_BLOCK_RESPONSE815
CONSENSUS_IGNORE_BLOCK_REQUEST816
CONSENSUS_IGNORE_BLOCK_RESPONSE817
CONSENSUS_FAIL_BLOCK_REQUEST818
CONSENSUS_FAIL_BLOCK_RESPONSE819
CONSENSUS_SETTINGS_GET_REQUEST820
CONSENSUS_SETTINGS_GET_RESPONSE821
CONSENSUS_STATE_GET_REQUEST822
CONSENSUS_STATE_GET_RESPONSE823
CONSENSUS_BLOCKS_GET_REQUEST824
CONSENSUS_BLOCKS_GET_RESPONSE825
CONSENSUS_CHAIN_HEAD_GET_REQUEST826
CONSENSUS_CHAIN_HEAD_GET_RESPONSE827
CONSENSUS_NOTIFY_PEER_CONNECTED900Consensus notification messages
CONSENSUS_NOTIFY_PEER_DISCONNECTED901
CONSENSUS_NOTIFY_PEER_MESSAGE902
CONSENSUS_NOTIFY_BLOCK_NEW903
CONSENSUS_NOTIFY_BLOCK_VALID904
CONSENSUS_NOTIFY_BLOCK_INVALID905
CONSENSUS_NOTIFY_BLOCK_COMMIT906
CONSENSUS_NOTIFY_ENGINE_ACTIVATED907
CONSENSUS_NOTIFY_ENGINE_DEACTIVATED908
CONSENSUS_NOTIFY_ACK999

Top

consensus.proto

ConsensusBlock

All information about a block that is relevant to consensus

FieldTypeLabelDescription
block_idbytes
previous_idbytes
signer_idbytesThe id of peer that signed this block
block_numuint64
payloadbytes
summarybytesA summary of the contents of the block

ConsensusBlocksGetRequest

Retrieve consensus-related information about blocks. If some blocks could not be found, only the blocks that could be found will be returned.

FieldTypeLabelDescription
block_idsbytesrepeated

ConsensusBlocksGetResponse

FieldTypeLabelDescription
statusConsensusBlocksGetResponse.Status
blocksConsensusBlockrepeated

ConsensusBroadcastRequest

Broadcast a consensus message to all peers

FieldTypeLabelDescription
contentbytesPayload to broadcast peers

NOTE: This payload will be wrapped up in a ConsensusPeerMessage struct, which includes computing its SHA-512 digest, inserting this engine's registration info, and the validator's public key, and signing everything with the validator's private key. | | message_type | string | | |

ConsensusBroadcastResponse

FieldTypeLabelDescription
statusConsensusBroadcastResponse.Status

ConsensusCancelBlockRequest

Stop adding batches to the current block and abandon it.

ConsensusCancelBlockResponse

FieldTypeLabelDescription
statusConsensusCancelBlockResponse.Status

ConsensusChainHeadGetRequest

Retrieve consensus-related information about the chain head.

ConsensusChainHeadGetResponse

FieldTypeLabelDescription
statusConsensusChainHeadGetResponse.Status
blockConsensusBlock

ConsensusCheckBlocksRequest

Request that, for each block block in order, the block is checked to determine whether the block can be committed successfully or not. Blocks may be checked in parallel. If a new request arrives, it overrides the previous request allowing the engine to reprioritize the list of blocks to check.

NOTE: OK does not mean the blocks will all commit successfully, only that the directive was received successfully. The engine must listen for notifications from the consuming component to learn if the blocks would commit or not.

FieldTypeLabelDescription
block_idsbytesrepeated

ConsensusCheckBlocksResponse

FieldTypeLabelDescription
statusConsensusCheckBlocksResponse.Status

ConsensusCommitBlockRequest

Request that the block be committed. This request fails if the block has not already been checked.

NOTE: OK does not mean the block has been committed, only that the directive was received successfully. The engine must listen for notifications from the consuming component to learn when the block commits.

FieldTypeLabelDescription
block_idbytes

ConsensusCommitBlockResponse

FieldTypeLabelDescription
statusConsensusCommitBlockResponse.Status

ConsensusFailBlockRequest

Fail this block and any of its descendants and purge them as needed.

FieldTypeLabelDescription
block_idbytes

ConsensusFailBlockResponse

FieldTypeLabelDescription
statusConsensusFailBlockResponse.Status

ConsensusFinalizeBlockRequest

Insert the given consensus data into the block and sign it. If this call is successful, the consensus engine will receive the block afterwards.

FieldTypeLabelDescription
databytesThe consensus data to include in the finalized block

ConsensusFinalizeBlockResponse

FieldTypeLabelDescription
statusConsensusFinalizeBlockResponse.Status
block_idbytesThe block id of the newly created block

ConsensusIgnoreBlockRequest

Inform the consuming component that this block is no longer being considered and can be held or freed as needed.

FieldTypeLabelDescription
block_idbytes

ConsensusIgnoreBlockResponse

FieldTypeLabelDescription
statusConsensusIgnoreBlockResponse.Status

ConsensusInitializeBlockRequest

Initialize a new block built on the block with the given previous id and begin adding batches to it. If no previous id is specified, the current head will be used.

FieldTypeLabelDescription
previous_idbytes

ConsensusInitializeBlockResponse

FieldTypeLabelDescription
statusConsensusInitializeBlockResponse.Status

ConsensusNotifyAck

Confirm that the notification was received. The validator message correlation id is used to determine which notification this is an ack for.

ConsensusNotifyBlockCommit

This block has been committed

FieldTypeLabelDescription
block_idbytes

ConsensusNotifyBlockInvalid

This block cannot be committed successfully

FieldTypeLabelDescription
block_idbytes

ConsensusNotifyBlockNew

A new block was received and passed initial consensus validation

FieldTypeLabelDescription
blockConsensusBlock

ConsensusNotifyBlockValid

This block can be committed successfully

FieldTypeLabelDescription
block_idbytes

ConsensusNotifyEngineActivated

The engine has been activated

FieldTypeLabelDescription
chain_headConsensusBlockStartup Info
peersConsensusPeerInforepeated
local_peer_infoConsensusPeerInfo

ConsensusNotifyEngineDeactivated

The engine has been deactivated

ConsensusNotifyPeerConnected

A new peer was added

FieldTypeLabelDescription
peer_infoConsensusPeerInfo

ConsensusNotifyPeerDisconnected

An existing peer was dropped

FieldTypeLabelDescription
peer_idbytes

ConsensusNotifyPeerMessage

A new message was received from a peer

FieldTypeLabelDescription
messageConsensusPeerMessageThe message sent
sender_idbytesThe node that sent the message, not necessarily the node that created it

ConsensusPeerInfo

Information about a peer that is relevant to consensus

FieldTypeLabelDescription
peer_idbytesThe unique id for this peer. This can be correlated with the signer id on consensus blocks.

ConsensusPeerMessage

A consensus-related message sent between peers

FieldTypeLabelDescription
headerbytesThe serialized version of the ConsensusPeerMessageHeader
header_signaturebytesThe signature derived from signing the header
contentbytesThe opaque payload to send to other nodes

ConsensusPeerMessageHeader

FieldTypeLabelDescription
signer_idbytesPublic key for the component internal to the validator that signed the message
content_sha512bytesThe sha512 hash of the encoded message
message_typestringInterpretation is left to the consensus engine implementation
namestringUsed to identify the consensus engine that produced this message
versionstring

ConsensusRegisterRequest

Sent to connect with the validator

FieldTypeLabelDescription
namestringThe name of this consensus engine
versionstringThe version of this consensus engine
additional_protocolsConsensusRegisterRequest.ProtocolrepeatedAny additional name/version pairs the consensus engine supports

ConsensusRegisterRequest.Protocol

FieldTypeLabelDescription
namestring
versionstring

ConsensusRegisterResponse

FieldTypeLabelDescription
statusConsensusRegisterResponse.Status
chain_headConsensusBlockStartup Info
peersConsensusPeerInforepeated
local_peer_infoConsensusPeerInfo

ConsensusSendToRequest

Send a consensus message to a specific, connected peer

FieldTypeLabelDescription
contentbytesPayload to send to peer

NOTE: This payload will be wrapped up in a ConsensusPeerMessage struct, which includes computing its SHA-512 digest, inserting this engine's registration info, and the validator's public key, and signing everything with the validator's private key. | | message_type | string | | | | receiver_id | bytes | | Peer that this message is destined for |

ConsensusSendToResponse

FieldTypeLabelDescription
statusConsensusSendToResponse.Status

ConsensusSettingsEntry

A settings key-value pair

FieldTypeLabelDescription
keystring
valuestring

ConsensusSettingsGetRequest

Read the values of these settings from state as of the given block. If some values settings keys cannot be found, the keys that were found will be returned.

FieldTypeLabelDescription
block_idbytes
keysstringrepeated

ConsensusSettingsGetResponse

FieldTypeLabelDescription
statusConsensusSettingsGetResponse.Status
entriesConsensusSettingsEntryrepeated

ConsensusStateEntry

A state key-value pair

FieldTypeLabelDescription
addressstring
databytes

ConsensusStateGetRequest

Read the data at these addresses from state as of the given block. If some addresses cannot be found, state at the addresses that were found will be returned.

FieldTypeLabelDescription
block_idbytes
addressesstringrepeated

ConsensusStateGetResponse

FieldTypeLabelDescription
statusConsensusStateGetResponse.Status
entriesConsensusStateEntryrepeated

ConsensusSummarizeBlockRequest

Stop adding batches to the current block and return a summary of its contents.

ConsensusSummarizeBlockResponse

FieldTypeLabelDescription
statusConsensusSummarizeBlockResponse.Status
summarybytesA summary of the block contents

ConsensusBlocksGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusBroadcastResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
NOT_ACTIVE_ENGINE5

ConsensusCancelBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
INVALID_STATE5
NOT_ACTIVE_ENGINE6

ConsensusChainHeadGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
NO_CHAIN_HEAD5
NOT_ACTIVE_ENGINE6

ConsensusCheckBlocksResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusCommitBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusFailBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusFinalizeBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
INVALID_STATE5
BLOCK_NOT_READY6
NOT_ACTIVE_ENGINE7

ConsensusIgnoreBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusInitializeBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
INVALID_STATE5
UNKNOWN_BLOCK6
NOT_ACTIVE_ENGINE7

ConsensusRegisterResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4

ConsensusSendToResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_PEER5
NOT_ACTIVE_ENGINE6

ConsensusSettingsGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusStateGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
UNKNOWN_BLOCK5
NOT_ACTIVE_ENGINE6

ConsensusSummarizeBlockResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
BAD_REQUEST2
SERVICE_ERROR3
NOT_READY4
INVALID_STATE5
BLOCK_NOT_READY6
NOT_ACTIVE_ENGINE7

Top

client_batch_submit.proto

ClientBatchStatus

Information about the status of a batch submitted to the validator.

Attributes: batch_id: The id (header_signature) of the batch status: The committed status of the batch invalid_transactions: Info for transactions that failed, if any

Statuses: COMMITTED - the batch was accepted and has been committed to the chain INVALID - the batch failed validation, it should be resubmitted PENDING - the batch is still being processed UNKNOWN - no status for the batch could be found (possibly invalid)

FieldTypeLabelDescription
batch_idstring
statusClientBatchStatus.Status
invalid_transactionsClientBatchStatus.InvalidTransactionrepeated

ClientBatchStatus.InvalidTransaction

FieldTypeLabelDescription
transaction_idstring
messagestring
extended_databytes

ClientBatchStatusRequest

A request for the status of one or more batches, specified by id. If wait is set to true, the validator will wait to respond until all batches are committed, or until the specified timeout in seconds has elapsed. Defaults to 300.

FieldTypeLabelDescription
batch_idsstringrepeated
waitbool
timeoutuint32

ClientBatchStatusResponse

This is a response to a request for the status of specific batches. Statuses:

  • OK - everything with the request worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NO_RESOURCE - the response contains no data, likely because no ids were specified in the request
FieldTypeLabelDescription
statusClientBatchStatusResponse.Status
batch_statusesClientBatchStatusrepeated

ClientBatchSubmitRequest

Submits a list of Batches to be added to the blockchain.

FieldTypeLabelDescription
batchesBatchrepeated

ClientBatchSubmitResponse

This is a response to a submission of one or more Batches. Statuses:

  • OK - everything with the request worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • INVALID_BATCH - the batch failed validation, likely due to a bad signature
  • QUEUE_FULL - the batch is unable to be queued for processing, due to a full processing queue. The batch may be submitted again.
FieldTypeLabelDescription
statusClientBatchSubmitResponse.Status

ClientBatchStatus.Status

NameNumberDescription
STATUS_UNSET0
COMMITTED1
INVALID2
PENDING3
UNKNOWN4

ClientBatchStatusResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NO_RESOURCE5
INVALID_ID8

ClientBatchSubmitResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
INVALID_BATCH3
QUEUE_FULL4

Top

client_block.proto

ClientBlockGetByBatchIdRequest

A request to return a specific block from the validator. The block containing the given batch is returned. If no block on the current chain contains the batch, NO_RESOURCE is returned.

FieldTypeLabelDescription
batch_idstring

ClientBlockGetByIdRequest

A request to return a specific block from the validator. The block must be specified by its unique id, in this case the block's header signature

FieldTypeLabelDescription
block_idstring

ClientBlockGetByNumRequest

A request to return a specific block from the validator. The block must be specified by its block number

FieldTypeLabelDescription
block_numuint64

ClientBlockGetByTransactionIdRequest

A request to return a specific block from the validator. The block containing the given transaction is returned. If no block on the current chain contains the transaction, NO_RESOURCE is returned.

FieldTypeLabelDescription
transaction_idstring

ClientBlockGetResponse

A response that returns the block specified by a ClientBlockGetByIdRequest or ClientBlockGetByNumRequest.

Statuses:

  • OK - everything worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NO_RESOURCE - no block with the specified id exists
FieldTypeLabelDescription
statusClientBlockGetResponse.Status
blockBlock

ClientBlockListRequest

A request to return a list of blocks from the validator. May include the id of a particular block to be the head of the chain being requested. In that case the list will include that block (if found), and all blocks previous to it on the chain. Can be filtered using specific block_ids.

FieldTypeLabelDescription
head_idstring
block_idsstringrepeated
pagingClientPagingControls
sortingClientSortControlsrepeated

ClientBlockListResponse

A response that lists a chain of blocks with the newest at the beginning, and the oldest (genesis) block at the end.

Statuses:

  • OK - everything worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NOT_READY - the validator does not yet have a genesis block
  • NO_ROOT - the head block specified was not found
  • NO_RESOURCE - no blocks were found with the parameters specified
  • INVALID_PAGING - the paging controls were malformed or out of range
  • INVALID_SORT - the sorting controls were malformed or invalid
FieldTypeLabelDescription
statusClientBlockListResponse.Status
blocksBlockrepeated
head_idstring
pagingClientPagingResponse

ClientBlockGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NO_RESOURCE5
INVALID_ID8

ClientBlockListResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NOT_READY3
NO_ROOT4
NO_RESOURCE5
INVALID_PAGING6
INVALID_SORT7
INVALID_ID8

Top

processor.proto

TpProcessRequest

The request from the validator/executor of the transaction processor to verify a transaction.

FieldTypeLabelDescription
headerTransactionHeaderThe de-serialized transaction header from client request
payloadbytesThe transaction payload
signaturestringThe transaction header_signature
context_idstringThe context_id for state requests.
header_bytesbytesThe serialized header as received by client. Controlled by a flag during transaction processor registration.

TpProcessResponse

The response from the transaction processor to the validator/executor used to respond about the validity of a transaction

FieldTypeLabelDescription
statusTpProcessResponse.Status
messagestringA message to include on responses in the cases where status is either INVALID_TRANSACTION or INTERNAL_ERROR
extended_databytesInformation that may be included with the response. This information is an opaque, application-specific encoded block of data that will be propagated back to the transaction submitter.

TpRegisterRequest

The registration request from the transaction processor to the validator/executor.

The protocol_version field is used to check if the validator supports requested features by a transaction processor. Following are the versions supported: 1 Transaction processor can request for either raw header bytes or deserialized TransactionHeader field in the TpProcessRequest message. The default option is set to send deserialized TransactionHeader.

FieldTypeLabelDescription
familystringA settled upon name for the capabilities of the transaction processor. For example: intkey, xo
versionstringThe version supported. For example: 1.0 for version 1.0 2.1 for version 2.1
namespacesstringrepeatedThe namespaces this transaction processor expects to interact with when processing transactions matching this specification; will be enforced by the state API on the validator.
max_occupancyuint32The maximum number of transactions that this transaction processor can handle at once.
protocol_versionuint32Validator can make use of this field to check if the requested features are supported. Registration requests can be either accepted or rejected based on this field.
request_header_styleTpRegisterRequest.TpProcessRequestHeaderStyleSetting it to RAW, validator would fill in serialized transaction header when sending TpProcessRequest to the transaction processor.

TpRegisterResponse

A response sent from the validator to the transaction processor acknowledging the registration

FieldTypeLabelDescription
statusTpRegisterResponse.Status
protocol_versionuint32Respond back with protocol_version, the value that can be used by SDK to know if validator supports expected feature.

TpUnregisterRequest

The unregistration request from the transaction processor to the validator/executor. The correct handlers are determined from the zeromq identity of the tp, on the validator side.

TpUnregisterResponse

A response sent from the validator to the transaction processor acknowledging the unregistration

FieldTypeLabelDescription
statusTpUnregisterResponse.Status

TpProcessResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INVALID_TRANSACTION2
INTERNAL_ERROR3

TpRegisterRequest.TpProcessRequestHeaderStyle

enum used to fill in transaction header field in TpProcessRequest. This field can be set before transaction processor registers with validator.

NameNumberDescription
HEADER_STYLE_UNSET0
EXPANDED1
RAW2

TpRegisterResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

TpUnregisterResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

Top

client_transaction.proto

ClientTransactionGetRequest

Fetches a specific txn by its id (header_signature) from the blockchain.

FieldTypeLabelDescription
transaction_idstring

ClientTransactionGetResponse

A response that returns the txn specified by a ClientTransactionGetRequest.

Statuses:

  • OK - everything worked as expected, txn has been fetched
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NO_RESOURCE - no txn with the specified id exists
FieldTypeLabelDescription
statusClientTransactionGetResponse.Status
transactionTransaction

ClientTransactionListRequest

A request to return a list of txns from the validator. May include the id of a particular block to be the head of the chain being requested. In that case the list will include the txns from that block, and all txns previous to that block on the chain. Filter with specific transaction_ids.

FieldTypeLabelDescription
head_idstring
transaction_idsstringrepeated
pagingClientPagingControls
sortingClientSortControlsrepeated

ClientTransactionListResponse

A response that lists transactions from newest to oldest.

Statuses:

  • OK - everything worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NOT_READY - the validator does not yet have a genesis block
  • NO_ROOT - the head block specified was not found
  • NO_RESOURCE - no txns were found with the parameters specified
  • INVALID_PAGING - the paging controls were malformed or out of range
  • INVALID_SORT - the sorting controls were malformed or invalid
FieldTypeLabelDescription
statusClientTransactionListResponse.Status
transactionsTransactionrepeated
head_idstring
pagingClientPagingResponse

ClientTransactionGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NO_RESOURCE5
INVALID_ID8

ClientTransactionListResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NOT_READY3
NO_ROOT4
NO_RESOURCE5
INVALID_PAGING6
INVALID_SORT7
INVALID_ID8

Top

client_list_control.proto

ClientPagingControls

Paging controls to be sent with List requests. Attributes: start: The id of a resource to start the page with limit: The number of results per page, defaults to 100 and maxes out at 1000

FieldTypeLabelDescription
startstring
limitint32

ClientPagingResponse

Information about the pagination used, sent back with List responses. Attributes: next: The id of the first resource in the next page start: The id of the first resource in the returned page limit: The number of results per page, defaults to 100 and maxes out at 1000

FieldTypeLabelDescription
nextstring
startstring
limitint32

ClientSortControls

Sorting controls to be sent with List requests. More than one can be sent. If so, the first is used, and additional controls are tie-breakers. Attributes: keys: Nested set of keys to sort by (i.e. ['default, block_num']) reverse: Whether or not to reverse the sort (i.e. descending order)

FieldTypeLabelDescription
keysstringrepeated
reversebool

Top

batch.proto

Batch

FieldTypeLabelDescription
headerbytesThe serialized version of the BatchHeader
header_signaturestringThe signature derived from signing the header
transactionsTransactionrepeatedA list of the transactions that match the list of transaction_ids listed in the batch header
traceboolA debugging flag which indicates this batch should be traced through the system, resulting in a higher level of debugging output.

BatchHeader

FieldTypeLabelDescription
signer_public_keystringPublic key for the client that signed the BatchHeader
transaction_idsstringrepeatedList of transaction.header_signatures that match the order of transactions required for the batch

BatchList

FieldTypeLabelDescription
batchesBatchrepeated

Top

events.proto

Event

FieldTypeLabelDescription
event_typestringUsed to subscribe to events and servers as a hint for how to deserialize event_data and what pairs to expect in attributes.
attributesEvent.Attributerepeated
databytesOpaque data defined by the event_type.

Event.Attribute

Transparent data defined by the event_type.

FieldTypeLabelDescription
keystring
valuestring

EventFilter

FieldTypeLabelDescription
keystringEventFilter is used when subscribing to events to limit the events received within a given event type. See validator/server/events/subscription.py for further explanation.
match_stringstring
filter_typeEventFilter.FilterType

EventList

FieldTypeLabelDescription
eventsEventrepeated

EventSubscription

FieldTypeLabelDescription
event_typestringEventSubscription is used when subscribing to events to specify the type of events being subscribed to, along with any additional filters. See validator/server/events/subscription.py for further explanation.
filtersEventFilterrepeated

EventFilter.FilterType

NameNumberDescription
FILTER_TYPE_UNSET0
SIMPLE_ANY1
SIMPLE_ALL2
REGEX_ANY3
REGEX_ALL4

Top

identity.proto

Policy

FieldTypeLabelDescription
namestringname of the policy, this should be unique.
entriesPolicy.Entryrepeatedlist of Entries The entries will be processed in order from first to last.

Policy.Entry

FieldTypeLabelDescription
typePolicy.EntryTypeWhether this is a Permit_KEY or Deny_KEY entry
keystringThis should be a public key or * to refer to all participants.

PolicyList

Policy will be stored in a Policy list to account for state collisions

FieldTypeLabelDescription
policiesPolicyrepeated

Role

FieldTypeLabelDescription
namestringRole name
policy_namestringName of corresponding policy

RoleList

Roles will be stored in a RoleList to account for state collisions

FieldTypeLabelDescription
rolesRolerepeated

Policy.EntryType

NameNumberDescription
ENTRY_TYPE_UNSET0
PERMIT_KEY1
DENY_KEY2

Top

block.proto

Block

FieldTypeLabelDescription
headerbytesThe serialized version of the BlockHeader
header_signaturestringThe signature derived from signing the header
batchesBatchrepeatedA list of batches. The batches may contain new batches that other validators may not have received yet, or they will be all batches needed for block validation when passed to the journal

BlockHeader

FieldTypeLabelDescription
block_numuint64Block number in the chain
previous_block_idstringThe header_signature of the previous block that was added to the chain.
signer_public_keystringPublic key for the component internal to the validator that signed the BlockHeader
batch_idsstringrepeatedList of batch.header_signatures that match the order of batches required for the block
consensusbytesBytes that are set and verified by the consensus algorithm used to create and validate the block
state_root_hashstringThe state_root_hash should match the final state_root after all transactions in the batches have been applied, otherwise the block is not valid

Top

client_state.proto

ClientStateGetRequest

A request from a client for a particular entry in global state. Like State List, it defaults to the newest state, but a state root can be used to specify older data. Unlike State List the request must be provided with a full address that corresponds to a single entry.

FieldTypeLabelDescription
state_rootstring
addressstring

ClientStateGetResponse

The response to a State Get Request from the client. Sends back just the data stored at the entry, not the address. Also sends back the head block id used to facilitate further requests.

Statuses:

  • OK - everything worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NOT_READY - the validator does not yet have a genesis block
  • NO_ROOT - the state_root specified was not found
  • NO_RESOURCE - the address specified doesn't exist
  • INVALID_ADDRESS - address isn't a valid, i.e. it's a subtree (truncated)
FieldTypeLabelDescription
statusClientStateGetResponse.Status
valuebytes
state_rootstring

ClientStateListRequest

A request to list every entry in global state. Defaults to the most current tree, but can fetch older state by specifying a state root. Results can be further filtered by specifying a subtree with a partial address.

FieldTypeLabelDescription
state_rootstring
addressstring
pagingClientPagingControls
sortingClientSortControlsrepeated

ClientStateListResponse

FieldTypeLabelDescription
statusClientStateListResponse.Status
entriesClientStateListResponse.Entryrepeated
state_rootstring
pagingClientPagingResponse

ClientStateListResponse.Entry

An entry in the State

FieldTypeLabelDescription
addressstring
databytes

ClientStateGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NOT_READY3
NO_ROOT4
NO_RESOURCE5
INVALID_ADDRESS6
INVALID_ROOT7

ClientStateListResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NOT_READY3
NO_ROOT4
NO_RESOURCE5
INVALID_PAGING6
INVALID_SORT7
INVALID_ADDRESS8
INVALID_ROOT9

Top

client_event.proto

ClientEventsGetRequest

FieldTypeLabelDescription
subscriptionsEventSubscriptionrepeated
block_idsstringrepeated

ClientEventsGetResponse

FieldTypeLabelDescription
statusClientEventsGetResponse.Status
eventsEventrepeated

ClientEventsSubscribeRequest

FieldTypeLabelDescription
subscriptionsEventSubscriptionrepeated
last_known_block_idsstringrepeatedThe block id (or ids, if trying to walk back a fork) the subscriber last received events on. It can be set to empty if it has not yet received the genesis block.

ClientEventsSubscribeResponse

FieldTypeLabelDescription
statusClientEventsSubscribeResponse.Status
response_messagestringAdditional information about the response status

ClientEventsUnsubscribeRequest

ClientEventsUnsubscribeResponse

FieldTypeLabelDescription
statusClientEventsUnsubscribeResponse.Status

ClientEventsGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
INVALID_FILTER3
UNKNOWN_BLOCK4

ClientEventsSubscribeResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INVALID_FILTER2
UNKNOWN_BLOCK3

ClientEventsUnsubscribeResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2

Top

state_context.proto

TpEventAddRequest

FieldTypeLabelDescription
context_idstring
eventEvent

TpEventAddResponse

FieldTypeLabelDescription
statusTpEventAddResponse.Status

TpReceiptAddDataRequest

The request from the transaction processor to the validator append data to a transaction receipt

FieldTypeLabelDescription
context_idstringThe context id that references a context in the context manager
databytes

TpReceiptAddDataResponse

The response from the validator to the transaction processor to verify that data has been appended to a transaction receipt

FieldTypeLabelDescription
statusTpReceiptAddDataResponse.Status

TpStateDeleteRequest

A request from the handler/tp to delete state entries at an collection of addresses

FieldTypeLabelDescription
context_idstring
addressesstringrepeated

TpStateDeleteResponse

A response form the contextmanager/validator with the addresses that were deleted

FieldTypeLabelDescription
addressesstringrepeated
statusTpStateDeleteResponse.Status

TpStateEntry

An entry in the State

FieldTypeLabelDescription
addressstring
databytes

TpStateGetRequest

A request from a handler/tp for the values at a series of addresses

FieldTypeLabelDescription
context_idstringThe context id that references a context in the contextmanager
addressesstringrepeated

TpStateGetResponse

A response from the contextmanager/validator with a series of State entries

FieldTypeLabelDescription
entriesTpStateEntryrepeated
statusTpStateGetResponse.Status

TpStateSetRequest

A request from the handler/tp to put entries in the state of a context

FieldTypeLabelDescription
context_idstring
entriesTpStateEntryrepeated

TpStateSetResponse

A response from the contextmanager/validator with the addresses that were set

FieldTypeLabelDescription
addressesstringrepeated
statusTpStateSetResponse.Status

TpEventAddResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

TpReceiptAddDataResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

TpStateDeleteResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
AUTHORIZATION_ERROR2

TpStateGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
AUTHORIZATION_ERROR2

TpStateSetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
AUTHORIZATION_ERROR2

Top

setting.proto

Setting

Setting Container for on-chain configuration key/value pairs

FieldTypeLabelDescription
entriesSetting.EntryrepeatedList of setting entries - more than one implies a state key collision

Setting.Entry

Contains a setting entry (or entries, in the case of collisions).

FieldTypeLabelDescription
keystring
valuestring

Top

block_info.proto

BlockInfo

FieldTypeLabelDescription
block_numuint64Block number in the chain
previous_block_idstringThe header_signature of the previous block that was added to the chain.
signer_public_keystringPublic key for the component internal to the validator that signed the BlockHeader
header_signaturestringThe signature derived from signing the header
timestampuint64Approximately when this block was committed, as a Unix UTC timestamp

BlockInfoConfig

FieldTypeLabelDescription
latest_blockuint64
oldest_blockuint64
target_countuint64
sync_toleranceuint64

BlockInfoTxn

FieldTypeLabelDescription
blockBlockInfoThe new block to add to state
target_countuint64If this is set, the new target number of blocks to store in state
sync_toleranceuint64If set, the new network time synchronization tolerance.

Top

transaction_receipt.proto

StateChange

StateChange objects have the type of SET, which is either an insert or update, or DELETE. Items marked as a DELETE will have no byte value.

FieldTypeLabelDescription
addressstring
valuebytes
typeStateChange.Type

StateChangeList

A collection of state changes.

FieldTypeLabelDescription
state_changesStateChangerepeated

TransactionReceipt

FieldTypeLabelDescription
state_changesStateChangerepeatedState changes made by this transaction StateChange is defined in protos/transaction_receipt.proto
eventsEventrepeatedEvents fired by this transaction
databytesrepeatedTransaction family defined data
transaction_idstring

StateChange.Type

NameNumberDescription
TYPE_UNSET0
SET1
DELETE2

Top

client_batch.proto

ClientBatchGetRequest

Fetches a specific batch by its id (header_signature) from the blockchain.

FieldTypeLabelDescription
batch_idstring

ClientBatchGetResponse

A response that returns the batch specified by a ClientBatchGetRequest.

Statuses:

  • OK - everything worked as expected, batch has been fetched
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NO_RESOURCE - no batch with the specified id exists
FieldTypeLabelDescription
statusClientBatchGetResponse.Status
batchBatch

ClientBatchListRequest

A request to return a list of batches from the validator. May include the id of a particular block to be the head of the chain being requested. In that case the list will include the batches from that block, and all batches previous to that block on the chain. Filter with specific batch_ids.

FieldTypeLabelDescription
head_idstring
batch_idsstringrepeated
pagingClientPagingControls
sortingClientSortControlsrepeated

ClientBatchListResponse

A response that lists batches from newest to oldest.

Statuses:

  • OK - everything worked as expected
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NOT_READY - the validator does not yet have a genesis block
  • NO_ROOT - the head block specified was not found
  • NO_RESOURCE - no batches were found with the parameters specified
  • INVALID_PAGING - the paging controls were malformed or out of range
  • INVALID_SORT - the sorting controls were malformed or invalid
FieldTypeLabelDescription
statusClientBatchListResponse.Status
batchesBatchrepeated
head_idstring
pagingClientPagingResponse

ClientBatchGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NO_RESOURCE5
INVALID_ID8

ClientBatchListResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NOT_READY3
NO_ROOT4
NO_RESOURCE5
INVALID_PAGING6
INVALID_SORT7
INVALID_ID8

Top

authorization.proto

AuthorizationChallengeRequest

Empty message sent to request a payload to sign

AuthorizationChallengeResponse

FieldTypeLabelDescription
payloadbytesRandom payload that the connecting node must sign

AuthorizationChallengeResult

FieldTypeLabelDescription
rolesRoleTyperepeatedThe approved roles for that connection

AuthorizationChallengeSubmit

FieldTypeLabelDescription
public_keystringpublic key of node
signaturestringsignature derived from signing the challenge payload
rolesRoleTyperepeatedA set of requested Roles

AuthorizationTrustRequest

FieldTypeLabelDescription
rolesRoleTyperepeatedA set of requested RoleTypes
public_keystring

AuthorizationTrustResponse

FieldTypeLabelDescription
rolesRoleTyperepeatedThe actual set the requester has access to

AuthorizationViolation

FieldTypeLabelDescription
violationRoleTypeThe Role the requester did not have access to

ConnectionRequest

FieldTypeLabelDescription
endpointstringThis is the first message that must be sent to start off authorization. The endpoint of the connection.

ConnectionResponse

FieldTypeLabelDescription
rolesConnectionResponse.RoleEntryrepeated
statusConnectionResponse.Status

ConnectionResponse.RoleEntry

FieldTypeLabelDescription
roleRoleTypeThe role type for this role entry
auth_typeConnectionResponse.AuthorizationTypeThe Authorization Type required for the above role

ConnectionResponse.AuthorizationType

Authorization Type required for the authorization procedure

NameNumberDescription
AUTHORIZATION_TYPE_UNSET0
TRUST1
CHALLENGE2

ConnectionResponse.Status

Whether the connection can participate in authorization

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

RoleType

NameNumberDescription
ROLE_TYPE_UNSET0
ALL1A shorthand request for asking for all allowed roles.
NETWORK2Role defining validator to validator communication

Top

genesis.proto

GenesisData

FieldTypeLabelDescription
batchesBatchrepeatedThe list of batches that will be applied during the genesis process

Top

merkle.proto

ChangeLogEntry

An Entry in the change log for a given state root.

FieldTypeLabelDescription
parentbytesA root hash of a merkle trie this tree was based off.
additionsbytesrepeatedThe hashes that were added for this root. These may be deleted during pruning, if this root is being abandoned.
successorsChangeLogEntry.SuccessorrepeatedThe list of successors.

ChangeLogEntry.Successor

A state root that succeed this root.

FieldTypeLabelDescription
successorbytesA root hash of a merkle trie based of off this root.
deletionsbytesrepeatedThe keys (i.e. hashes) that were replaced (i.e. deleted) by this successor. These may be deleted during pruning.

Top

network.proto

DisconnectMessage

The disconnect message from a client to the server

GetPeersRequest

GetPeersResponse

FieldTypeLabelDescription
peer_endpointsstringrepeated

GossipBatchByBatchIdRequest

FieldTypeLabelDescription
idstringThe id of the batch that is being requested
noncestringA random string that provides uniqueness for requests with otherwise identical fields.
time_to_liveuint32

GossipBatchByTransactionIdRequest

FieldTypeLabelDescription
idsstringrepeatedThe id's of the transaction that are in the batches requested
noncestringA random string that provides uniqueness for requests with otherwise identical fields.
time_to_liveuint32

GossipBatchResponse

FieldTypeLabelDescription
contentbytesThe batch

GossipBlockRequest

FieldTypeLabelDescription
block_idstringThe id of the block that is being requested
noncestringA random string that provides uniqueness for requests with otherwise identical fields.
time_to_liveuint32

GossipBlockResponse

FieldTypeLabelDescription
contentbytesThe block

GossipMessage

FieldTypeLabelDescription
contentbytes
content_typeGossipMessage.ContentType
time_to_liveuint32

NetworkAcknowledgement

A response sent from the validator to the peer acknowledging message receipt

FieldTypeLabelDescription
statusNetworkAcknowledgement.Status

PeerRegisterRequest

The registration request from a peer to the validator

FieldTypeLabelDescription
endpointstring
protocol_versionuint32The current version of the network protocol that is being used by the sender. This version is an increasing value.

PeerUnregisterRequest

The unregistration request from a peer to the validator

PingRequest

PingResponse

GossipMessage.ContentType

NameNumberDescription
CONTENT_TYPE_UNSET0
BLOCK1
BATCH2
CONSENSUS3

NetworkAcknowledgement.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

Top

client_peers.proto

ClientPeersGetRequest

ClientPeersGetResponse

FieldTypeLabelDescription
statusClientPeersGetResponse.Status
peersstringrepeated

ClientPeersGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
ERROR2

Top

client_receipt.proto

ClientReceiptGetRequest

Fetches a specific txn by its id (header_signature) from the blockchain.

FieldTypeLabelDescription
transaction_idsstringrepeated

ClientReceiptGetResponse

A response that returns the txn receipt specified by a ClientTransactionReceiptGetRequest.

Statuses:

  • OK - everything worked as expected, txn receipt has been fetched
  • INTERNAL_ERROR - general error, such as protobuf failing to deserialize
  • NO_RESOURCE - no receipt exists for the transaction id specified
FieldTypeLabelDescription
statusClientReceiptGetResponse.Status
receiptsTransactionReceiptrepeated

ClientReceiptGetResponse.Status

NameNumberDescription
STATUS_UNSET0
OK1
INTERNAL_ERROR2
NO_RESOURCE5
INVALID_ID8

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── authorization.proto
├── batch.proto
├── block_info.proto
├── block.proto
├── client_batch.proto
├── client_batch_submit.proto
├── client_block.proto
├── client_event.proto
├── client_list_control.proto
├── client_peers.proto
├── client_receipt.proto
├── client_state.proto
├── client_status.proto
├── client_transaction.proto
├── consensus.proto
├── events.proto
├── genesis.proto
├── identity.proto
├── merkle.proto
├── network.proto
├── processor.proto
├── setting.proto
├── state_context.proto
├── transaction.proto
├── transaction_receipt.proto
└── validator.proto

0 directories, 26 files

Protobuf sources

src:./transaction.proto


// Copyright 2016 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "transaction_pb2";

message TransactionHeader {
    // Public key for the client who added this transaction to a batch
    string batcher_public_key = 1;

    // A list of transaction signatures that describe the transactions that
    // must be processed before this transaction can be valid
    repeated string dependencies = 2;

    // The family name correlates to the transaction processor's family name
    // that this transaction can be processed on, for example 'intkey'
    string family_name = 3;

    // The family version correlates to the transaction processor's family
    // version that this transaction can be processed on, for example "1.0"
    string family_version = 4;

    // A list of addresses that are given to the context manager and control
    // what addresses the transaction processor is allowed to read from.
    repeated string inputs = 5;

    // A random string that provides uniqueness for transactions with
    // otherwise identical fields.
    string nonce = 6;

    // A list of addresses that are given to the context manager and control
    // what addresses the transaction processor is allowed to write to.
    repeated string outputs = 7;

    //The sha512 hash of the encoded payload
    string payload_sha512 = 9;

    // Public key for the client that signed the TransactionHeader
    string signer_public_key = 10;
}

message Transaction {
    // The serialized version of the TransactionHeader
    bytes header = 1;

    // The signature derived from signing the header
    string header_signature = 2;

    // The payload is the encoded family specific information of the
    // transaction. Example cbor({'Verb': verb, 'Name': name,'Value': value})
    bytes payload = 3;
}

// A simple list of transactions that needs to be serialized before
// it can be transmitted to a batcher.
message TransactionList {
    repeated Transaction transactions = 1;
}

src:./client_status.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_status";

// A request to get miscellaneous information about the validator
message ClientStatusGetRequest{
}

message ClientStatusGetResponse {
  // The status of the response message, not the validator's status
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    ERROR = 2;
  }

  // Information about the validator's peers
  message Peer {
    // The peer's public network endpoint
    string endpoint = 1;
  }

  Status status = 1;
  repeated Peer peers = 2;
  // The validator's public network endpoint
  string endpoint = 3;
}

src:./validator.proto


// Copyright 2016, 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "validator_pb2";

// A list of messages to be transmitted together.
message MessageList {
    repeated Message messages = 1;
}

// The message passed between the validator and client, containing the
// header fields and content.
message Message {

    enum MessageType {
        DEFAULT = 0;
        // Registration request from the transaction processor to the validator
        TP_REGISTER_REQUEST = 1;
        // Registration response from the validator to the
        // transaction processor
        TP_REGISTER_RESPONSE = 2;
        // Tell the validator that the transaction processor
        // won't take any more transactions
        TP_UNREGISTER_REQUEST = 3;
        // Response from the validator to the tp that it won't
        // send any more transactions
        TP_UNREGISTER_RESPONSE = 4;
        // Process Request from the validator/executor to the
        // transaction processor
        TP_PROCESS_REQUEST = 5;
        // Process response from the transaction processor to the validator/executor
        TP_PROCESS_RESPONSE = 6;
        // State get request from the transaction processor to validator/context_manager
        TP_STATE_GET_REQUEST = 7;
        // State get response from the validator/context_manager to the transaction processor
        TP_STATE_GET_RESPONSE = 8;
        // State set request from the transaction processor to the validator/context_manager
        TP_STATE_SET_REQUEST = 9;
        // State set response from the validator/context_manager to the transaction processor
        TP_STATE_SET_RESPONSE = 10;
        // State delete request from the transaction processor to the validator/context_manager
        TP_STATE_DELETE_REQUEST = 11;
        // State delete response from the validator/context_manager to the transaction processor
        TP_STATE_DELETE_RESPONSE = 12;
        // Message to append data to a transaction receipt
        TP_RECEIPT_ADD_DATA_REQUEST = 13;
        // Response from validator to tell transaction processor that data has been appended
        TP_RECEIPT_ADD_DATA_RESPONSE = 14;
        // Message to add event
        TP_EVENT_ADD_REQUEST = 15;
        // Response from validator to tell transaction processor that event has been created
        TP_EVENT_ADD_RESPONSE = 16;

        // Submission of a batchlist from the web api or another client to the validator
        CLIENT_BATCH_SUBMIT_REQUEST = 100;
        // Response from the validator to the web api/client that the submission was accepted
        CLIENT_BATCH_SUBMIT_RESPONSE = 101;
        // A request to list blocks from the web api/client to the validator
        CLIENT_BLOCK_LIST_REQUEST = 102;
        CLIENT_BLOCK_LIST_RESPONSE = 103;
        CLIENT_BLOCK_GET_BY_ID_REQUEST = 104;
        CLIENT_BLOCK_GET_RESPONSE = 105;
        CLIENT_BATCH_LIST_REQUEST = 106;
        CLIENT_BATCH_LIST_RESPONSE = 107;
        CLIENT_BATCH_GET_REQUEST = 108;
        CLIENT_BATCH_GET_RESPONSE = 109;
        CLIENT_TRANSACTION_LIST_REQUEST = 110;
        CLIENT_TRANSACTION_LIST_RESPONSE = 111;
        CLIENT_TRANSACTION_GET_REQUEST = 112;
        CLIENT_TRANSACTION_GET_RESPONSE = 113;
        // Client state request of the current state hash to be retrieved from the journal
        CLIENT_STATE_CURRENT_REQUEST = 114;
        // Response with the current state hash
        CLIENT_STATE_CURRENT_RESPONSE = 115;
        // A request of all the addresses under a particular prefix, for a state hash.
        CLIENT_STATE_LIST_REQUEST = 116;
        // The response of the addresses
        CLIENT_STATE_LIST_RESPONSE = 117;
        // Get the address:data entry at a particular address
        CLIENT_STATE_GET_REQUEST = 118;
        // The response with the entry
        CLIENT_STATE_GET_RESPONSE = 119;
        // A request for the status of a batch or batches
        CLIENT_BATCH_STATUS_REQUEST = 120;
        // A response with the batch statuses
        CLIENT_BATCH_STATUS_RESPONSE = 121;
        // A request for one or more transaction receipts
        CLIENT_RECEIPT_GET_REQUEST = 122;
        // A response with the receipts
        CLIENT_RECEIPT_GET_RESPONSE = 123;
        CLIENT_BLOCK_GET_BY_NUM_REQUEST = 124;
        // A request for a validator's peers
        CLIENT_PEERS_GET_REQUEST = 125;
        // A response with the validator's peers
        CLIENT_PEERS_GET_RESPONSE = 126;
        CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST = 127;
        CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST = 128;
        // A request for a validator's status
        CLIENT_STATUS_GET_REQUEST = 129;
        // A response with the validator's status
        CLIENT_STATUS_GET_RESPONSE = 130;

        // Message types for events
        CLIENT_EVENTS_SUBSCRIBE_REQUEST = 500;
        CLIENT_EVENTS_SUBSCRIBE_RESPONSE = 501;
        CLIENT_EVENTS_UNSUBSCRIBE_REQUEST = 502;
        CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE = 503;
        CLIENT_EVENTS = 504;
        CLIENT_EVENTS_GET_REQUEST = 505;
        CLIENT_EVENTS_GET_RESPONSE = 506;

        // Temp message types until a discussion can be had about gossip msg
        GOSSIP_MESSAGE = 200;
        GOSSIP_REGISTER = 201;
        GOSSIP_UNREGISTER = 202;
        GOSSIP_BLOCK_REQUEST = 205;
        GOSSIP_BLOCK_RESPONSE = 206;
        GOSSIP_BATCH_BY_BATCH_ID_REQUEST = 207;
        GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST = 208;
        GOSSIP_BATCH_RESPONSE = 209;
        GOSSIP_GET_PEERS_REQUEST = 210;
        GOSSIP_GET_PEERS_RESPONSE = 211;
        GOSSIP_CONSENSUS_MESSAGE = 212;

        NETWORK_ACK = 300;
        NETWORK_CONNECT = 301;
        NETWORK_DISCONNECT = 302;

        // Message types for Authorization Types
        AUTHORIZATION_CONNECTION_RESPONSE = 600;
        AUTHORIZATION_VIOLATION = 601;
        AUTHORIZATION_TRUST_REQUEST = 602;
        AUTHORIZATION_TRUST_RESPONSE = 603;
        AUTHORIZATION_CHALLENGE_REQUEST = 604;
        AUTHORIZATION_CHALLENGE_RESPONSE = 605;
        AUTHORIZATION_CHALLENGE_SUBMIT = 606;
        AUTHORIZATION_CHALLENGE_RESULT = 607;

        PING_REQUEST = 700;
        PING_RESPONSE = 701;

        // Consensus service messages
        CONSENSUS_REGISTER_REQUEST = 800;
        CONSENSUS_REGISTER_RESPONSE = 801;

        CONSENSUS_SEND_TO_REQUEST = 802;
        CONSENSUS_SEND_TO_RESPONSE = 803;
        CONSENSUS_BROADCAST_REQUEST = 804;
        CONSENSUS_BROADCAST_RESPONSE = 805;

        CONSENSUS_INITIALIZE_BLOCK_REQUEST = 806;
        CONSENSUS_INITIALIZE_BLOCK_RESPONSE = 807;
        CONSENSUS_FINALIZE_BLOCK_REQUEST = 808;
        CONSENSUS_FINALIZE_BLOCK_RESPONSE = 809;
        CONSENSUS_SUMMARIZE_BLOCK_REQUEST = 828;
        CONSENSUS_SUMMARIZE_BLOCK_RESPONSE = 829;
        CONSENSUS_CANCEL_BLOCK_REQUEST = 810;
        CONSENSUS_CANCEL_BLOCK_RESPONSE = 811;

        CONSENSUS_CHECK_BLOCKS_REQUEST = 812;
        CONSENSUS_CHECK_BLOCKS_RESPONSE = 813;
        CONSENSUS_COMMIT_BLOCK_REQUEST = 814;
        CONSENSUS_COMMIT_BLOCK_RESPONSE = 815;
        CONSENSUS_IGNORE_BLOCK_REQUEST = 816;
        CONSENSUS_IGNORE_BLOCK_RESPONSE = 817;
        CONSENSUS_FAIL_BLOCK_REQUEST = 818;
        CONSENSUS_FAIL_BLOCK_RESPONSE = 819;

        CONSENSUS_SETTINGS_GET_REQUEST = 820;
        CONSENSUS_SETTINGS_GET_RESPONSE = 821;
        CONSENSUS_STATE_GET_REQUEST = 822;
        CONSENSUS_STATE_GET_RESPONSE = 823;
        CONSENSUS_BLOCKS_GET_REQUEST = 824;
        CONSENSUS_BLOCKS_GET_RESPONSE = 825;
        CONSENSUS_CHAIN_HEAD_GET_REQUEST = 826;
        CONSENSUS_CHAIN_HEAD_GET_RESPONSE = 827;

        // Consensus notification messages
        CONSENSUS_NOTIFY_PEER_CONNECTED = 900;
        CONSENSUS_NOTIFY_PEER_DISCONNECTED = 901;
        CONSENSUS_NOTIFY_PEER_MESSAGE = 902;

        CONSENSUS_NOTIFY_BLOCK_NEW = 903;
        CONSENSUS_NOTIFY_BLOCK_VALID = 904;
        CONSENSUS_NOTIFY_BLOCK_INVALID = 905;
        CONSENSUS_NOTIFY_BLOCK_COMMIT = 906;

        CONSENSUS_NOTIFY_ENGINE_ACTIVATED = 907;
        CONSENSUS_NOTIFY_ENGINE_DEACTIVATED = 908;

        CONSENSUS_NOTIFY_ACK = 999;
    }
    // The type of message, used to determine how to 'route' the message
    // to the appropriate handler as well as how to deserialize the
    // content.
    MessageType message_type = 1;

    // The identifier used to correlate response messages to their related
    // request messages.  correlation_id should be set to a random string
    // for messages which are not responses to previously sent messages.  For
    // response messages, correlation_id should be set to the same string as
    // contained in the request message.
    string correlation_id = 2;

    // The content of the message, defined by message_type.  In many
    // cases, this data has been serialized with Protocol Buffers or
    // CBOR.
    bytes content = 3;

}

src:./consensus.proto


// Copyright 2018 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

// --== Data Structures ==--

message ConsensusPeerMessageHeader {
  // Public key for the component internal to the validator that
  // signed the message
  bytes signer_id = 1;

  // The sha512 hash of the encoded message
  bytes content_sha512 = 2;
  // Interpretation is left to the consensus engine implementation
  string message_type = 5;

  // Used to identify the consensus engine that produced this message
  string name = 3;
  string version = 4;
}

// A consensus-related message sent between peers
message ConsensusPeerMessage {
  // The serialized version of the ConsensusPeerMessageHeader
  bytes header = 1;

  // The signature derived from signing the header
  bytes header_signature = 3;

  // The opaque payload to send to other nodes
  bytes content = 2;
}

// All information about a block that is relevant to consensus
message ConsensusBlock {
  bytes block_id = 1;
  bytes previous_id = 2;
  // The id of peer that signed this block
  bytes signer_id = 3;
  uint64 block_num = 4;
  bytes payload = 5;
  // A summary of the contents of the block
  bytes summary = 6;
}

// Information about a peer that is relevant to consensus
message ConsensusPeerInfo {
  // The unique id for this peer. This can be correlated with the signer id
  // on consensus blocks.
  bytes peer_id = 1;
}

// A settings key-value pair
message ConsensusSettingsEntry {
  string key = 1;
  string value = 2;
}

// A state key-value pair
message ConsensusStateEntry {
  string address = 1;
  bytes data = 2;
}

// --== Registration ==--

// Sent to connect with the validator
message ConsensusRegisterRequest {
  message Protocol {
    string name = 1;
    string version = 2;
  }

  // The name of this consensus engine
  string name = 1;
  // The version of this consensus engine
  string version = 2;
  // Any additional name/version pairs the consensus engine supports
  repeated Protocol additional_protocols = 3;
}

message ConsensusRegisterResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;
  }

  Status status = 1;

  // Startup Info
  ConsensusBlock chain_head = 2;
  repeated ConsensusPeerInfo peers = 3;
  ConsensusPeerInfo local_peer_info = 4;
}

// --== Notifications ==--

// The following are notifications provided by the validator to the consensus
// engine. An ack should be sent in response to all notifications.

// - P2P -

// A new peer was added
message ConsensusNotifyPeerConnected {
  ConsensusPeerInfo peer_info = 1;
}

// An existing peer was dropped
message ConsensusNotifyPeerDisconnected {
  bytes peer_id = 1;
}

// A new message was received from a peer
message ConsensusNotifyPeerMessage {
  // The message sent
  ConsensusPeerMessage message = 1;
  // The node that sent the message, not necessarily the node that created it
  bytes sender_id = 2;
}

// - Blocks -

// A new block was received and passed initial consensus validation
message ConsensusNotifyBlockNew {
  ConsensusBlock block = 1;
}

// This block can be committed successfully
message ConsensusNotifyBlockValid {
  bytes block_id = 1;
}

// This block cannot be committed successfully
message ConsensusNotifyBlockInvalid {
  bytes block_id = 1;
}

// This block has been committed
message ConsensusNotifyBlockCommit {
  bytes block_id = 1;
}

// The engine has been activated
message ConsensusNotifyEngineActivated {
  // Startup Info
  ConsensusBlock chain_head = 1;
  repeated ConsensusPeerInfo peers = 2;
  ConsensusPeerInfo local_peer_info = 3;
}

// The engine has been deactivated
message ConsensusNotifyEngineDeactivated {}

// Confirm that the notification was received. The validator message
// correlation id is used to determine which notification this is an ack for.
message ConsensusNotifyAck {}

// --== Services Provided ==--

// The following are services provided by the validator to the consensus
// engine. All service messages have at a minimum the following possible return
// statuses:
//
//    STATUS_UNSET
//        No status was set by the validator, this should never happen
//    OK
//        The request was completed successfully
//    BAD_REQUEST
//        The request was malformed in some way
//    SERVICE_ERROR
//        The validator failed to perform the request
//    NOT_READY
//        The validator is not accepting requests, usually because it is still
//        starting up
//    NOT_ACTIVE_ENGINE
//        The consensus engine making the request is not the active engine
//
// Additionally, messages may have the following additional return statuses:
//
//    INVALID_STATE
//        The request is not valid given the current state of the validator
//    UNKNOWN_BLOCK
//        No block with the given id could be found
//    UNKNOWN_PEER
//        No peer with the given id could be found

// - P2P Messaging -

// Send a consensus message to a specific, connected peer
message ConsensusSendToRequest {
  // Payload to send to peer
  //
  // NOTE: This payload will be wrapped up in a ConsensusPeerMessage struct,
  // which includes computing its SHA-512 digest, inserting this engine's
  // registration info, and the validator's public key, and signing everything
  // with the validator's private key.
  bytes content = 1;
  string message_type = 3;

  // Peer that this message is destined for
  bytes receiver_id = 2;
}

message ConsensusSendToResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_PEER = 5;

    NOT_ACTIVE_ENGINE = 6;
  }
  Status status = 1;
}

// Broadcast a consensus message to all peers
message ConsensusBroadcastRequest {
  // Payload to broadcast peers
  //
  // NOTE: This payload will be wrapped up in a ConsensusPeerMessage struct,
  // which includes computing its SHA-512 digest, inserting this engine's
  // registration info, and the validator's public key, and signing everything
  // with the validator's private key.
  bytes content = 1;
  string message_type = 2;
}

message ConsensusBroadcastResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;
    NOT_ACTIVE_ENGINE = 5;
  }
  Status status = 1;
}

// - Block Creation -

// Initialize a new block built on the block with the given previous id and
// begin adding batches to it. If no previous id is specified, the current
// head will be used.
message ConsensusInitializeBlockRequest {
  bytes previous_id = 1;
}

message ConsensusInitializeBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    INVALID_STATE = 5;
    UNKNOWN_BLOCK = 6;

    NOT_ACTIVE_ENGINE = 7;
  }
  Status status = 1;
}

// Stop adding batches to the current block and return a summary of its
// contents.
message ConsensusSummarizeBlockRequest {}

message ConsensusSummarizeBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    INVALID_STATE = 5;
    BLOCK_NOT_READY = 6;

    NOT_ACTIVE_ENGINE = 7;
  }
  Status status = 1;

  // A summary of the block contents
  bytes summary = 2;
}

// Insert the given consensus data into the block and sign it. If this call is
// successful, the consensus engine will receive the block afterwards.
message ConsensusFinalizeBlockRequest {
  // The consensus data to include in the finalized block
  bytes data = 1;
}

message ConsensusFinalizeBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    INVALID_STATE = 5;
    BLOCK_NOT_READY = 6;

    NOT_ACTIVE_ENGINE = 7;
  }
  Status status = 1;

  // The block id of the newly created block
  bytes block_id = 2;
}

// Stop adding batches to the current block and abandon it.
message ConsensusCancelBlockRequest {}

message ConsensusCancelBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    INVALID_STATE = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
}

// - Block Directives -

// Request that, for each block block in order, the block is checked to
// determine whether the block can be committed successfully or not. Blocks
// may be checked in parallel. If a new request arrives, it overrides the
// previous request allowing the engine to reprioritize the list of blocks to
// check.
//
// NOTE: OK does not mean the blocks will all commit successfully, only that
// the directive was received successfully. The engine must listen for
// notifications from the consuming component to learn if the blocks would
// commit or not.
message ConsensusCheckBlocksRequest {
  repeated bytes block_ids = 1;
}

message ConsensusCheckBlocksResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
}

// Request that the block be committed. This request fails if the block has
// not already been checked.
//
// NOTE: OK does not mean the block has been committed, only that the directive
// was received successfully. The engine must listen for notifications from the
// consuming component to learn when the block commits.
message ConsensusCommitBlockRequest {
  bytes block_id = 1;
}

message ConsensusCommitBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
}

// Inform the consuming component that this block is no longer being considered
// and can be held or freed as needed.
message ConsensusIgnoreBlockRequest {
  bytes block_id = 1;
}

message ConsensusIgnoreBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
}

// Fail this block and any of its descendants and purge them as needed.
message ConsensusFailBlockRequest {
  bytes block_id = 1;
}

message ConsensusFailBlockResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
}

// - Queries -

// Retrieve consensus-related information about blocks. If some blocks could
// not be found, only the blocks that could be found will be returned.
message ConsensusBlocksGetRequest {
  repeated bytes block_ids = 1;
}

message ConsensusBlocksGetResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
  repeated ConsensusBlock blocks = 2;
}

// Retrieve consensus-related information about the chain head.
message ConsensusChainHeadGetRequest {}

message ConsensusChainHeadGetResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    NO_CHAIN_HEAD = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
  ConsensusBlock block = 2;
}

// Read the values of these settings from state as of the given block. If some
// values settings keys cannot be found, the keys that were found will be
// returned.
message ConsensusSettingsGetRequest {
  bytes block_id = 1;
  repeated string keys = 2;
}

message ConsensusSettingsGetResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
  repeated ConsensusSettingsEntry entries = 2;
}

// Read the data at these addresses from state as of the given block. If some
// addresses cannot be found, state at the addresses that were found will be
// returned.
message ConsensusStateGetRequest {
  bytes block_id = 1;
  repeated string addresses = 2;
}

message ConsensusStateGetResponse {
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    BAD_REQUEST = 2;
    SERVICE_ERROR = 3;
    NOT_READY = 4;

    UNKNOWN_BLOCK = 5;

    NOT_ACTIVE_ENGINE = 6;
  }

  Status status = 1;
  repeated ConsensusStateEntry entries = 2;
}

src:./client_batch_submit.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_batch_submit_pb2";

import "batch.proto";


// Information about the status of a batch submitted to the validator.
//
// Attributes:
//     batch_id: The id (header_signature) of the batch
//     status: The committed status of the batch
//     invalid_transactions: Info for transactions that failed, if any
//
// Statuses:
//     COMMITTED - the batch was accepted and has been committed to the chain
//     INVALID - the batch failed validation, it should be resubmitted
//     PENDING - the batch is still being processed
//     UNKNOWN - no status for the batch could be found (possibly invalid)
message ClientBatchStatus {
    enum Status {
        STATUS_UNSET = 0;
        COMMITTED = 1;
        INVALID = 2;
        PENDING = 3;
        UNKNOWN = 4;
    }
    message InvalidTransaction {
        string transaction_id = 1;
        string message = 2;
        bytes extended_data = 3;
    }
    string batch_id = 1;
    Status status = 2;
    repeated InvalidTransaction invalid_transactions = 3;
}

// Submits a list of Batches to be added to the blockchain.
message ClientBatchSubmitRequest {
    repeated Batch batches = 1;
}

// This is a response to a submission of one or more Batches.
// Statuses:
//   * OK - everything with the request worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * INVALID_BATCH - the batch failed validation, likely due to a bad signature
//   * QUEUE_FULL - the batch is unable to be queued for processing, due to
//        a full processing queue.  The batch may be submitted again.
message ClientBatchSubmitResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        INVALID_BATCH = 3;
        QUEUE_FULL = 4;
    }
    Status status = 1;
}

// A request for the status of one or more batches, specified by id.
// If `wait` is set to true, the validator will wait to respond until all
// batches are committed, or until the specified `timeout` in seconds has
// elapsed. Defaults to 300.
message ClientBatchStatusRequest {
    repeated string batch_ids = 1;
    bool wait = 2;
    uint32 timeout = 3;
}

// This is a response to a request for the status of specific batches.
// Statuses:
//   * OK - everything with the request worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NO_RESOURCE - the response contains no data, likely because
//     no ids were specified in the request
message ClientBatchStatusResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NO_RESOURCE = 5;
        INVALID_ID = 8;
    }
    Status status = 1;
    repeated ClientBatchStatus batch_statuses = 2;
}

src:./client_block.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_block_pb2";

import "block.proto";
import "client_list_control.proto";


// A request to return a list of blocks from the validator. May include the id
// of a particular block to be the `head` of the chain being requested. In that
// case the list will include that block (if found), and all blocks previous
// to it on the chain. Can be filtered using specific `block_ids`.
message ClientBlockListRequest {
    string head_id = 1;
    repeated string block_ids = 2;
    ClientPagingControls paging = 3;
    repeated ClientSortControls sorting = 4;
}

// A response that lists a chain of blocks with the newest at the beginning,
// and the oldest (genesis) block at the end.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NOT_READY - the validator does not yet have a genesis block
//   * NO_ROOT - the head block specified was not found
//   * NO_RESOURCE - no blocks were found with the parameters specified
//   * INVALID_PAGING - the paging controls were malformed or out of range
//   * INVALID_SORT - the sorting controls were malformed or invalid
message ClientBlockListResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NOT_READY = 3;
        NO_ROOT = 4;
        NO_RESOURCE = 5;
        INVALID_PAGING = 6;
        INVALID_SORT = 7;
        INVALID_ID = 8;
    }
    Status status = 1;
    repeated Block blocks = 2;
    string head_id = 3;
    ClientPagingResponse paging = 4;
}

// A request to return a specific block from the validator. The block must be
// specified by its unique id, in this case the block's header signature
message ClientBlockGetByIdRequest {
    string block_id = 1;
}

// A request to return a specific block from the validator. The block must be
// specified by its block number
message ClientBlockGetByNumRequest {
    uint64 block_num = 1;
}

// A request to return a specific block from the validator. The block
// containing the given transaction is returned. If no block on the current
// chain contains the transaction, NO_RESOURCE is returned.
message ClientBlockGetByTransactionIdRequest {
    string transaction_id = 1;
}

// A request to return a specific block from the validator. The block
// containing the given batch is returned. If no block on the current chain
// contains the batch, NO_RESOURCE is returned.
message ClientBlockGetByBatchIdRequest {
    string batch_id = 1;
}

// A response that returns the block specified by a ClientBlockGetByIdRequest
// or  ClientBlockGetByNumRequest.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NO_RESOURCE - no block with the specified id exists
message ClientBlockGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NO_RESOURCE = 5;
        INVALID_ID = 8;
    }
    Status status = 1;
    Block block = 2;
}

src:./processor.proto


// Copyright 2016 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "processor_pb2";

import "transaction.proto";


// The registration request from the transaction processor to the
// validator/executor.
//
// The protocol_version field is used to check if the validator supports
// requested features by a transaction processor.
// Following are the versions supported:
//     1    Transaction processor can request for either raw header bytes or
//          deserialized TransactionHeader field in the TpProcessRequest
//          message. The default option is set to send deserialized
//          TransactionHeader.
message TpRegisterRequest {
    // enum used to fill in transaction header field in TpProcessRequest.
    // This field can be set before transaction processor registers with
    // validator.
    enum TpProcessRequestHeaderStyle {
        HEADER_STYLE_UNSET = 0;
        EXPANDED = 1;
        RAW = 2;
    }

    // A settled upon name for the capabilities of the transaction processor.
    // For example: intkey, xo
    string family = 1;

    // The version supported.  For example:
    //      1.0  for version 1.0
    //      2.1  for version 2.1
    string version = 2;

    // The namespaces this transaction processor expects to interact with
    // when processing transactions matching this specification; will be
    // enforced by the state API on the validator.
    repeated string namespaces = 4;

    // The maximum number of transactions that this transaction processor can
    // handle at once.
    uint32 max_occupancy = 5;

    // Validator can make use of this field to check if the requested features
    // are supported. Registration requests can be either accepted or rejected
    // based on this field.
    uint32 protocol_version = 6;

    // Setting it to RAW, validator would fill in serialized transaction header
    // when sending TpProcessRequest to the transaction processor.
    TpProcessRequestHeaderStyle request_header_style = 7;
}

// A response sent from the validator to the transaction processor
// acknowledging the registration
message TpRegisterResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        ERROR = 2;
    }

    Status status = 1;

    // Respond back with protocol_version, the value that can be used by SDK to
    // know if validator supports expected feature.
    uint32 protocol_version = 2;
}

// The unregistration request from the transaction processor to the
// validator/executor. The correct handlers are determined from the
// zeromq identity of the tp, on the validator side.
message TpUnregisterRequest {

}

// A response sent from the validator to the transaction processor
// acknowledging the unregistration
message TpUnregisterResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        ERROR = 2;
    }

    Status status = 1;
}


// The request from the validator/executor of the transaction processor
// to verify a transaction.
message TpProcessRequest {
    // The de-serialized transaction header from client request
    TransactionHeader header = 1;

    // The transaction payload
    bytes payload = 2;

    // The transaction header_signature
    string signature = 3;

    // The context_id for state requests.
    string context_id = 4;

    // The serialized header as received by client.
    // Controlled by a flag during transaction processor registration.
    bytes header_bytes = 5;
}


// The response from the transaction processor to the validator/executor
// used to respond about the validity of a transaction
message TpProcessResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INVALID_TRANSACTION = 2;
        INTERNAL_ERROR = 3;
    }

    Status status = 1;

    // A message to include on responses in the cases where
    // status is either INVALID_TRANSACTION or INTERNAL_ERROR
    string message = 2;

    // Information that may be included with the response.
    // This information is an opaque, application-specific encoded block of
    // data that will be propagated back to the transaction submitter.
    bytes extended_data = 3;
}

src:./client_transaction.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_transaction_pb2";

import "transaction.proto";
import "client_list_control.proto";


// A request to return a list of txns from the validator. May include the id
// of a particular block to be the `head` of the chain being requested. In that
// case the list will include the txns from that block, and all txns
// previous to that block on the chain. Filter with specific `transaction_ids`.
message ClientTransactionListRequest {
    string head_id = 1;
    repeated string transaction_ids = 2;
    ClientPagingControls paging = 3;
    repeated ClientSortControls sorting = 4;
}

// A response that lists transactions from newest to oldest.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NOT_READY - the validator does not yet have a genesis block
//   * NO_ROOT - the head block specified was not found
//   * NO_RESOURCE - no txns were found with the parameters specified
//   * INVALID_PAGING - the paging controls were malformed or out of range
//   * INVALID_SORT - the sorting controls were malformed or invalid
message ClientTransactionListResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NOT_READY = 3;
        NO_ROOT = 4;
        NO_RESOURCE = 5;
        INVALID_PAGING = 6;
        INVALID_SORT = 7;
        INVALID_ID = 8;
    }
    Status status = 1;
    repeated Transaction transactions = 2;
    string head_id = 3;
    ClientPagingResponse paging = 4;
}

// Fetches a specific txn by its id (header_signature) from the blockchain.
message ClientTransactionGetRequest {
    string transaction_id = 1;
}

// A response that returns the txn specified by a ClientTransactionGetRequest.
//
// Statuses:
//   * OK - everything worked as expected, txn has been fetched
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NO_RESOURCE - no txn with the specified id exists
message ClientTransactionGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NO_RESOURCE = 5;
        INVALID_ID = 8;
    }
    Status status = 1;
    Transaction transaction = 2;
}

src:./client_list_control.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_list_control_pb2";

// Paging controls to be sent with List requests.
// Attributes:
//     start: The id of a resource to start the page with
//     limit: The number of results per page, defaults to 100 and maxes out at 1000
message ClientPagingControls {
    string start = 1;
    int32 limit = 2;
}

// Information about the pagination used, sent back with List responses.
// Attributes:
//     next: The id of the first resource in the next page
//     start: The id of the first resource in the returned page
//     limit: The number of results per page, defaults to 100 and maxes out at 1000
message ClientPagingResponse {
    string next = 1;
    string start = 2;
    int32 limit = 3;

}

// Sorting controls to be sent with List requests. More than one can be sent.
// If so, the first is used, and additional controls are tie-breakers.
// Attributes:
//     keys: Nested set of keys to sort by (i.e. ['default, block_num'])
//     reverse: Whether or not to reverse the sort (i.e. descending order)
message ClientSortControls {
    repeated string keys = 1;
    bool reverse = 2;
}

src:./batch.proto


// Copyright 2016 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "batch_pb2";

import "transaction.proto";

message BatchHeader {
    // Public key for the client that signed the BatchHeader
    string signer_public_key = 1;

    // List of transaction.header_signatures that match the order of
    // transactions required for the batch
    repeated string transaction_ids = 2;
}

message Batch {
    // The serialized version of the BatchHeader
    bytes header = 1;

    // The signature derived from signing the header
    string header_signature = 2;

    // A list of the transactions that match the list of
    // transaction_ids listed in the batch header
    repeated Transaction transactions = 3;

    // A debugging flag which indicates this batch should be traced through the
    // system, resulting in a higher level of debugging output.
    bool trace = 4;
}

message BatchList {
    repeated Batch batches = 1;
}

src:./events.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "events_pb2";


message Event {
  // Used to subscribe to events and servers as a hint for how to deserialize
  // event_data and what pairs to expect in attributes.
  string event_type = 1;

  // Transparent data defined by the event_type.
  message Attribute {
    string key = 1;
    string value = 2;
  }
  repeated Attribute attributes = 2;

  // Opaque data defined by the event_type.
  bytes  data = 3;
}

message EventList {
    repeated Event events = 1;
}

message EventFilter {
    // EventFilter is used when subscribing to events to limit the events
    // received within a given event type. See
    // validator/server/events/subscription.py for further explanation.
    string key = 1;
    string match_string = 2;

    enum FilterType {
      FILTER_TYPE_UNSET = 0;
      SIMPLE_ANY = 1;
      SIMPLE_ALL = 2;
      REGEX_ANY  = 3;
      REGEX_ALL  = 4;
    }
    FilterType filter_type = 3;
}

message EventSubscription {
    // EventSubscription is used when subscribing to events to specify the type
    // of events being subscribed to, along with any additional filters. See
    // validator/server/events/subscription.py for further explanation.
    string event_type = 1;
    repeated EventFilter filters = 2;
}

src:./identity.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.identity.protobuf";

message Policy {

  enum EntryType {
    ENTRY_TYPE_UNSET = 0;
    PERMIT_KEY = 1;
    DENY_KEY = 2;
  }

  message Entry {
    // Whether this is a Permit_KEY or Deny_KEY entry
    EntryType type = 1;

    // This should be a public key or * to refer to all participants.
    string  key = 2;
  }

  // name of the policy, this should be unique.
  string name = 1;

  // list of Entries
  // The entries will be processed in order from first to last.
  repeated Entry entries = 2;
}

// Policy will be stored in a Policy list to account for state collisions
message PolicyList {
  repeated Policy policies = 1;
}


message Role {
  // Role name
  string name = 1;

  // Name of corresponding policy
  string policy_name = 2;
}

// Roles will be stored in a RoleList to account for state collisions
message RoleList {
  repeated Role roles = 1;
}

src:./block.proto


// Copyright 2016 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "block_pb2";

import "batch.proto";

message BlockHeader {
    // Block number in the chain
    uint64 block_num = 1;

    // The header_signature of the previous block that was added to the chain.
    string previous_block_id = 2;

    // Public key for the component internal to the validator that
    // signed the BlockHeader
    string signer_public_key = 3;

    // List of batch.header_signatures that match the order of batches
    // required for the block
    repeated string batch_ids = 4;

    // Bytes that are set and verified by the consensus algorithm used to
    // create and validate the block
    bytes consensus = 5;

    // The state_root_hash should match the final state_root after all
    // transactions in the batches have been applied, otherwise the block
    // is not valid
    string state_root_hash = 6;
}

message Block {
    // The serialized version of the BlockHeader
    bytes header = 1;

    // The signature derived from signing the header
    string header_signature = 2;

    // A list of batches. The batches may contain new batches that other
    // validators may not have received yet, or they will be all batches needed
    // for block validation when passed to the journal
    repeated Batch batches = 3;
}

src:./client_state.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_state_pb2";

import "client_list_control.proto";


// A request to list every entry in global state. Defaults to the most current
// tree, but can fetch older state by specifying a state root. Results can be
// further filtered by specifying a subtree with a partial address.
message ClientStateListRequest {
    string state_root = 1;
    string address = 3;
    ClientPagingControls paging = 4;
    repeated ClientSortControls sorting = 5;
}

// A response that lists the data Entries from global state, filtered by state
// root or subtree address according to the request. Returns the state root
// used to facilitate future requests.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NOT_READY - the validator does not yet have a genesis block
//   * NO_ROOT - the head block or merkle_root specified was not found
//   * NO_RESOURCE - the head/root specified is valid, but contains no data
//   * INVALID_PAGING - the paging controls were malformed or out of range
//   * INVALID_SORT - the sorting controls were malformed or invalid

message ClientStateListResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NOT_READY = 3;
        NO_ROOT = 4;
        NO_RESOURCE = 5;
        INVALID_PAGING = 6;
        INVALID_SORT = 7;
        INVALID_ADDRESS = 8;
        INVALID_ROOT = 9;
    }

    // An entry in the State
    message Entry {
        string address = 1;
        bytes data = 2;
    }

    Status status = 1;
    repeated Entry entries = 2;
    string state_root = 3;
    ClientPagingResponse paging = 4;
}

// A request from a client for a particular entry in global state.
// Like State List, it defaults to the newest state, but a state root
// can be used to specify older data. Unlike State List the request must be
// provided with a full address that corresponds to a single entry.
message ClientStateGetRequest {
    string state_root = 1;
    string address = 3;
}

// The response to a State Get Request from the client. Sends back just
// the data stored at the entry, not the address. Also sends back the
// head block id used to facilitate further requests.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NOT_READY - the validator does not yet have a genesis block
//   * NO_ROOT - the state_root specified was not found
//   * NO_RESOURCE - the address specified doesn't exist
//   * INVALID_ADDRESS - address isn't a valid, i.e. it's a subtree (truncated)
message ClientStateGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NOT_READY = 3;
        NO_ROOT = 4;
        NO_RESOURCE = 5;
        INVALID_ADDRESS = 6;
        INVALID_ROOT = 7;
    }
    Status status = 1;
    bytes value = 2;
    string state_root = 3;
}

src:./client_event.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_event_pb2";

import "events.proto";


message ClientEventsSubscribeRequest {
    repeated EventSubscription subscriptions = 1;
    // The block id (or ids, if trying to walk back a fork) the subscriber last
    // received events on. It can be set to empty if it has not yet received the
    // genesis block.
    repeated string last_known_block_ids = 2;
}

message ClientEventsSubscribeResponse {
    enum Status {
         STATUS_UNSET = 0;
         OK = 1;
         INVALID_FILTER = 2;
         UNKNOWN_BLOCK = 3;
    }
    Status status = 1;
    // Additional information about the response status
    string response_message = 2;
}

message ClientEventsUnsubscribeRequest {}

message ClientEventsUnsubscribeResponse {
    enum Status {
         STATUS_UNSET = 0;
         OK = 1;
         INTERNAL_ERROR = 2;
    }
    Status status = 1;
}

message ClientEventsGetRequest {
    repeated EventSubscription subscriptions = 1;
    repeated string block_ids = 2;
}

message ClientEventsGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        INVALID_FILTER = 3;
        UNKNOWN_BLOCK = 4;
    }
    Status status = 1;
    repeated Event events = 2;

}

src:./state_context.proto


// Copyright 2016 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "state_context_pb2";

import "events.proto";

// An entry in the State
message TpStateEntry {
    string address = 1;
    bytes data = 2;
}

// A request from a handler/tp for the values at a series of addresses
message TpStateGetRequest {
    // The context id that references a context in the contextmanager
    string context_id = 1;
    repeated string addresses = 2;
}

// A response from the contextmanager/validator with a series of State entries
message TpStateGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        AUTHORIZATION_ERROR = 2;
    }

    repeated TpStateEntry entries = 1;
    Status status = 2;
}

// A request from the handler/tp to put entries in the state of a context
message TpStateSetRequest {
    string context_id = 1;
    repeated TpStateEntry entries = 2;
}

// A response from the contextmanager/validator with the addresses that were set
message TpStateSetResponse {
  enum Status {
      STATUS_UNSET = 0;
      OK = 1;
      AUTHORIZATION_ERROR = 2;
  }

    repeated string addresses = 1;
    Status status = 2;
}

// A request from the handler/tp to delete state entries at an collection of addresses
message TpStateDeleteRequest {
    string context_id = 1;
    repeated string addresses = 2;
}

// A response form the contextmanager/validator with the addresses that were deleted
message TpStateDeleteResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        AUTHORIZATION_ERROR = 2;
    }

    repeated string addresses = 1;
    Status status = 2;
}

// The request from the transaction processor to the validator append data
// to a transaction receipt
message TpReceiptAddDataRequest {
    // The context id that references a context in the context manager
    string context_id = 1;
    bytes data = 3;
}

// The response from the validator to the transaction processor to verify that
// data has been appended to a transaction receipt
message TpReceiptAddDataResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        ERROR = 2;
    }

    Status status = 2;
}

message TpEventAddRequest {
    string context_id = 1;
    Event event = 2;
}

message TpEventAddResponse {
    enum Status {
      STATUS_UNSET = 0;
      OK = 1;
      ERROR = 2;
    }
    Status status = 2;
}

src:./setting.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "setting_pb2";


// Setting Container for on-chain configuration key/value pairs
message Setting {
    // Contains a setting entry (or entries, in the case of collisions).
    message Entry {
        string key = 1;
        string value = 2;
    }

    // List of setting entries - more than one implies a state key collision
    repeated Entry entries = 1;
}

src:./block_info.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.block_info.protobuf";
option go_package = "block_info_pb2";

message BlockInfoConfig {
    uint64 latest_block = 1;
    uint64 oldest_block = 2;
    uint64 target_count = 3;
    uint64 sync_tolerance = 4;
}

message BlockInfo {
    // Block number in the chain
    uint64 block_num = 1;
    // The header_signature of the previous block that was added to the chain.
    string previous_block_id = 2;
    // Public key for the component internal to the validator that
    // signed the BlockHeader
    string signer_public_key = 3;
    // The signature derived from signing the header
    string header_signature = 4;
    // Approximately when this block was committed, as a Unix UTC timestamp
    uint64 timestamp = 5;
}

message BlockInfoTxn {
    // The new block to add to state
    BlockInfo block = 1;
    // If this is set, the new target number of blocks to store in state
    uint64 target_count = 2;
    // If set, the new network time synchronization tolerance.
    uint64 sync_tolerance = 3;
}

src:./transaction_receipt.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "txn_receipt_pb2";

import "events.proto";


message TransactionReceipt {
  // State changes made by this transaction
  // StateChange is defined in protos/transaction_receipt.proto
  repeated StateChange state_changes = 1;
  // Events fired by this transaction
  repeated Event events = 2;
  // Transaction family defined data
  repeated bytes data = 3;

  string transaction_id = 4;
}

//  StateChange objects have the type of SET, which is either an insert or
//  update, or DELETE. Items marked as a DELETE will have no byte value.
message StateChange {
    enum Type {
        TYPE_UNSET = 0;
        SET = 1;
        DELETE = 2;
    }
    string address = 1;
    bytes value = 2;
    Type type = 3;
}

// A collection of state changes.
message StateChangeList {
    repeated StateChange state_changes = 1;
}

src:./client_batch.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_batch_pb2";

import "batch.proto";
import "client_list_control.proto";


// A request to return a list of batches from the validator. May include the id
// of a particular block to be the `head` of the chain being requested. In that
// case the list will include the batches from that block, and all batches
// previous to that block on the chain. Filter with specific `batch_ids`.
message ClientBatchListRequest {
    string head_id = 1;
    repeated string batch_ids = 2;
    ClientPagingControls paging = 3;
    repeated ClientSortControls sorting = 4;
}

// A response that lists batches from newest to oldest.
//
// Statuses:
//   * OK - everything worked as expected
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NOT_READY - the validator does not yet have a genesis block
//   * NO_ROOT - the head block specified was not found
//   * NO_RESOURCE - no batches were found with the parameters specified
//   * INVALID_PAGING - the paging controls were malformed or out of range
//   * INVALID_SORT - the sorting controls were malformed or invalid
message ClientBatchListResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NOT_READY = 3;
        NO_ROOT = 4;
        NO_RESOURCE = 5;
        INVALID_PAGING = 6;
        INVALID_SORT = 7;
        INVALID_ID = 8;
    }
    Status status = 1;
    repeated Batch batches = 2;
    string head_id = 3;
    ClientPagingResponse paging = 4;
}

// Fetches a specific batch by its id (header_signature) from the blockchain.
message ClientBatchGetRequest {
    string batch_id = 1;
}

// A response that returns the batch specified by a ClientBatchGetRequest.
//
// Statuses:
//   * OK - everything worked as expected, batch has been fetched
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NO_RESOURCE - no batch with the specified id exists
message ClientBatchGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NO_RESOURCE = 5;
        INVALID_ID = 8;
    }
    Status status = 1;
    Batch batch = 2;
}

src:./authorization.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "authorization_pb2";

message ConnectionRequest {
  // This is the first message that must be sent to start off authorization.
  // The endpoint of the connection.
  string endpoint = 1;
}

enum RoleType {
  ROLE_TYPE_UNSET = 0;

  // A shorthand request for asking for all allowed roles.
  ALL = 1;

  // Role defining validator to validator communication
  NETWORK = 2;
}

message ConnectionResponse {
  // Whether the connection can participate in authorization
  enum Status {
    STATUS_UNSET = 0;
    OK = 1;
    ERROR = 2;
  }

  //Authorization Type required for the authorization procedure
  enum AuthorizationType {
    AUTHORIZATION_TYPE_UNSET = 0;
    TRUST = 1;
    CHALLENGE = 2;
  }

  message RoleEntry {
    // The role type for this role entry
    RoleType role = 1;

    // The Authorization Type required for the above role
    AuthorizationType auth_type = 2;
  }

  repeated RoleEntry roles = 1;
  Status status = 2;
}

message AuthorizationTrustRequest {
  // A set of requested RoleTypes
  repeated RoleType roles = 1;
  string public_key = 2;
}

message AuthorizationTrustResponse {
  // The actual set the requester has access to
  repeated RoleType roles = 1;
}

message AuthorizationViolation {
  // The Role the requester did not have access to
  RoleType violation = 1;
}

message AuthorizationChallengeRequest {
  // Empty message sent to request a payload to sign
}

message AuthorizationChallengeResponse {
  // Random payload that the connecting node must sign
  bytes payload = 1;
}

message AuthorizationChallengeSubmit {
  // public key of node
  string public_key = 1;

  // signature derived from signing the challenge payload
  string signature = 3;

  // A set of requested Roles
  repeated RoleType roles = 4;
}

message AuthorizationChallengeResult {
  // The approved roles for that connection
  repeated RoleType roles = 1;
}

src:./genesis.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "genesis_pb2";

import "batch.proto";

message GenesisData {
    // The list of batches that will be applied during the genesis process
    repeated Batch batches = 1;
}

src:./merkle.proto


// Copyright 2018 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------
syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "merkle_pb2";

// An Entry in the change log for a given state root.
message ChangeLogEntry {
    // A state root that succeed this root.
    message Successor {
        // A root hash of a merkle trie based of off this root.
        bytes successor = 1;

        // The keys (i.e. hashes) that were replaced (i.e. deleted) by this
        // successor.  These may be deleted during pruning.
        repeated bytes deletions = 2;
    }

    // A root hash of a merkle trie this tree was based off.
    bytes parent = 1;

    // The hashes that were added for this root. These may be deleted during
    // pruning, if this root is being abandoned.
    repeated bytes additions = 2;

    // The list of successors.
    repeated Successor successors = 3;
}

src:./network.proto


// Copyright 2016, 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";
option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "network_pb2";

// The disconnect message from a client to the server
message DisconnectMessage {
}

// The registration request from a peer to the validator
message PeerRegisterRequest {
    string endpoint = 1;
    // The current version of the network protocol that is being used by the
    // sender.  This version is an increasing value.
    uint32 protocol_version = 2;
}

// The unregistration request from a peer to the validator
message PeerUnregisterRequest {
}

message GetPeersRequest {
}

message GetPeersResponse {
    repeated string peer_endpoints = 1;
}

message PingRequest {
}

message PingResponse{
}

message GossipMessage {
    enum ContentType{
        CONTENT_TYPE_UNSET = 0;
        BLOCK = 1;
        BATCH = 2;
        CONSENSUS = 3;
    }
    bytes content = 1;
    ContentType content_type = 2;
    uint32 time_to_live = 3;
}

// A response sent from the validator to the peer acknowledging message
// receipt
message NetworkAcknowledgement {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        ERROR = 2;
    }

    Status status = 1;
}

message GossipBlockRequest {
    // The id of the block that is being requested
    string block_id = 1;

    // A random string that provides uniqueness for requests with
    // otherwise identical fields.
    string nonce = 2;
    uint32 time_to_live = 3;

}

message GossipBlockResponse {
    // The block
    bytes content = 1;
}

message GossipBatchResponse {
    //The batch
    bytes content = 1;
}

message GossipBatchByBatchIdRequest {
    // The id of the batch that is being requested
    string id = 1;

    // A random string that provides uniqueness for requests with
    // otherwise identical fields.
    string nonce = 2;
    uint32 time_to_live = 3;

}

message GossipBatchByTransactionIdRequest {
    // The id's of the transaction that are in the batches requested
    repeated string ids = 1;

    // A random string that provides uniqueness for requests with
    // otherwise identical fields.
    string nonce = 2;
    uint32 time_to_live = 3;

}

src:./client_peers.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_peer";

message ClientPeersGetRequest{
}

message ClientPeersGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        ERROR = 2;
    }
    Status status = 1;
    repeated string peers = 2;
}

src:./client_receipt.proto


// Copyright 2017 Intel Corporation
//
// 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.
// -----------------------------------------------------------------------------

syntax = "proto3";

option java_multiple_files = true;
option java_package = "sawtooth.sdk.protobuf";
option go_package = "client_receipt_pb2";

import "transaction_receipt.proto";

// Fetches a specific txn by its id (header_signature) from the blockchain.
message ClientReceiptGetRequest {
    repeated string transaction_ids = 1;
}

// A response that returns the txn receipt specified by a
// ClientTransactionReceiptGetRequest.
//
// Statuses:
//   * OK - everything worked as expected, txn receipt has been fetched
//   * INTERNAL_ERROR - general error, such as protobuf failing to deserialize
//   * NO_RESOURCE - no receipt exists for the transaction id specified
message ClientReceiptGetResponse {
    enum Status {
        STATUS_UNSET = 0;
        OK = 1;
        INTERNAL_ERROR = 2;
        NO_RESOURCE = 5;
        INVALID_ID = 8;
    }
    Status status = 1;
    repeated TransactionReceipt receipts = 2;
}

HyperLedger Burrow

TOC

如何生成 Google Protocol Buffers 文件

burrow/protobuf at master · hyperledger/burrow

git clone https://github.com/hyperledger/burrow.git /tmp/src/burrow
bash tc.sh --gen-proto-doc /tmp/src/burrow/protobuf /tmp/output.md

Generated Date:2019-09-12T14:23:17+08:00

Protocol Documentation

Table of Contents

Top

balance.proto

Balance

FieldTypeLabelDescription
Typeuint32
Amountuint64

Top

exec.proto

BeginBlock

FieldTypeLabelDescription
Heightuint64The height of this block
Headertypes.Header

BeginTx

FieldTypeLabelDescription
TxHeaderTxHeader
ResultResultResult of tx execution
Exceptionerrors.ExceptionIf tx execution was an exception

BlockExecution

FieldTypeLabelDescription
Heightuint64The height of this block
Headertypes.Header
TxExecutionsTxExecutionrepeated

CallData

FieldTypeLabelDescription
Callerbytes
Calleebytes
Databytes
Valueuint64
Gasuint64

CallEvent

FieldTypeLabelDescription
CallTypeuint32
CallDataCallData
Originbytes
StackDepthuint64
Returnbytes

EndBlock

FieldTypeLabelDescription
Heightuint64

EndTx

FieldTypeLabelDescription
TxHashbytesThe hash of the transaction that caused this event to be generated

Event

FieldTypeLabelDescription
HeaderHeader
InputInputEvent
OutputOutputEvent
CallCallEvent
LogLogEvent
GovernAccountGovernAccountEvent

GovernAccountEvent

FieldTypeLabelDescription
AccountUpdatespec.TemplateAccount

Header

FieldTypeLabelDescription
TxTypeuint32Transaction type
TxHashbytesThe hash of the transaction that caused this event to be generated
EventTypeuint32The type of event
EventIDstringEventID published with event
Heightuint64The block height at which this event was emitted
Indexuint64The index of this event relative to other events generated by the same transaction
Exceptionerrors.ExceptionIf event is exception

InputEvent

FieldTypeLabelDescription
Addressbytes

LogEvent

FieldTypeLabelDescription
Addressbytes
Databytes
Topicsbytesrepeated

Origin

FieldTypeLabelDescription
ChainIDstringThe original ChainID from for this transaction
Heightuint64The original height at which this transaction was committed
Indexuint64The original index in the block
Timegoogle.protobuf.TimestampThe original block time for this transaction

OutputEvent

FieldTypeLabelDescription
Addressbytes

Result

Could structure this further if needed - sum type of various results relevant to different transaction types

FieldTypeLabelDescription
ReturnbytesEVM execution return
GasUseduint64Gas used in computation
NameEntrynames.EntryName entry created
PermArgspermission.PermArgsPermission update performed

StreamEvent

FieldTypeLabelDescription
BeginBlockBeginBlock
BeginTxBeginTx
Envelopetxs.Envelope
EventEvent
EndTxEndTx
EndBlockEndBlock

StreamEvents

This message exists purely for framing []StreamEvent

FieldTypeLabelDescription
StreamEventsStreamEventrepeated

TxExecution

FieldTypeLabelDescription
HeaderTxHeader
Envelopetxs.EnvelopeSigned Tx that triggered this execution
EventsEventrepeatedExecution events
ResultResultThe execution results
Receipttxs.ReceiptThe transaction receipt
Exceptionerrors.ExceptionIf execution was an exception
TxExecutionsTxExecutionrepeatedA proposal may contain other transactions

TxExecutionKey

FieldTypeLabelDescription
Heightuint64The block height
Offsetuint64The offset of the TxExecution in bytes

TxHeader

FieldTypeLabelDescription
TxTypeuint32Transaction type
TxHashbytesThe hash of the transaction that caused this event to be generated
Heightuint64The block height at which this Tx was included
Indexuint64The index of this transaction within the block
OriginOriginThe origin information from the chain on which this tx was originally committed (if restored or otherwise imported)

Top

names.proto

Entry

NameReg provides a global key value store based on Name, Data pairs that are subject to expiry and ownership by an account.

FieldTypeLabelDescription
Namestringregistered name for the entry
Ownerbytesaddress that created the entry
Datastringdata to store under this name
Expiresuint64block at which this entry expires

Top

encoding.proto

TestMessage

For testing

FieldTypeLabelDescription
Typeuint32
Amountuint64

Top

validator.proto

Validator

FieldTypeLabelDescription
Addressbytes
PublicKeycrypto.PublicKey
Poweruint64

Top

txs.proto

Envelope

An envelope contains both the signable Tx and the signatures for each input (in signatories)

FieldTypeLabelDescription
SignatoriesSignatoryrepeated
TxbytesCanonical bytes of the Tx ready to be signed

Receipt

BroadcastTx or Transaction receipt

FieldTypeLabelDescription
TxTypeuint32Transaction type
TxHashbytesThe hash of the transaction that caused this event to be generated
CreatesContractboolWhether the transaction creates a contract
ContractAddressbytesThe address of the contract being called

Signatory

Signatory contains signature and one or both of Address and PublicKey to identify the signer

FieldTypeLabelDescription
Addressbytes
PublicKeycrypto.PublicKey
Signaturecrypto.Signature

Top

rpctransact.proto

CallCodeParam

FieldTypeLabelDescription
FromAddressbytes
Codebytes
Databytes

TxEnvelope

FieldTypeLabelDescription
Envelopetxs.Envelope

TxEnvelopeParam

FieldTypeLabelDescription
Envelopetxs.EnvelopeAn existing Envelope - either signed or unsigned - if the latter will be signed server-side
Payloadpayload.AnyIf no Envelope provided then one will be generated from the provided payload and signed server-side
Timeoutgoogle.protobuf.DurationThe amount of time to wait for the transaction to be committed and the TxExecution to be returned (server-side). If zero there wait is unbounded. Timed out transactions return SyncInfo state that may be helpful debugging non-committed transactions - this timeout must be less than client timeout to see such information!

Transact

Transaction Service Definition

Method NameRequest TypeResponse TypeDescription
BroadcastTxSyncTxEnvelopeParam.exec.TxExecutionBroadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side and wait for it to be included in block
BroadcastTxAsyncTxEnvelopeParam.txs.ReceiptBroadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side
SignTxTxEnvelopeParamTxEnvelopeSign transaction server-side
FormulateTx.payload.AnyTxEnvelopeFormulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign
CallTxSync.payload.CallTx.exec.TxExecutionFormulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response
CallTxAsync.payload.CallTx.txs.ReceiptFormulate and sign a CallTx transaction signed server-side
CallTxSim.payload.CallTx.exec.TxExecutionPerform a 'simulated' call of a contract against the current committed EVM state without any changes been saved and wait for the transaction to be included in a block
CallCodeSimCallCodeParam.exec.TxExecutionPerform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved
SendTxSync.payload.SendTx.exec.TxExecutionFormulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response
SendTxAsync.payload.SendTx.txs.ReceiptFormulate and SendTx transaction signed server-side
NameTxSync.payload.NameTx.exec.TxExecutionFormualte a NameTx signed server-side and wait for it to be included in a block returning the registered name
NameTxAsync.payload.NameTx.txs.ReceiptFormulate a NameTx signed server-side

Top

github.com/tendermint/tendermint/abci/types/types.proto

BlockGossip

BlockGossip determine consensus critical elements of how blocks are gossiped

FieldTypeLabelDescription
block_part_size_bytesint32Note: must not be 0

BlockID

FieldTypeLabelDescription
hashbytes
parts_headerPartSetHeader

BlockSize

BlockSize contains limits on the block size.

FieldTypeLabelDescription
max_bytesint32
max_gasint64

ConsensusParams

ConsensusParams contains all consensus-relevant parameters that can be adjusted by the abci app

FieldTypeLabelDescription
block_sizeBlockSize
tx_sizeTxSize
block_gossipBlockGossip

Evidence

FieldTypeLabelDescription
typestring
validatorValidator
heightint64
timegoogle.protobuf.Timestamp
total_voting_powerint64

Header

FieldTypeLabelDescription
chain_idstringbasic block info
heightint64
timegoogle.protobuf.Timestamp
num_txsint64
total_txsint64
last_block_idBlockIDprev block info
last_commit_hashbyteshashes of block data

commit from validators from the last block | | data_hash | bytes | | transactions | | validators_hash | bytes | | hashes from the app output from the prev block

validators for the current block | | next_validators_hash | bytes | | validators for the next block | | consensus_hash | bytes | | consensus params for current block | | app_hash | bytes | | state after txs from the previous block | | last_results_hash | bytes | | root hash of all results from the txs from the previous block | | evidence_hash | bytes | | consensus info

evidence included in the block | | proposer_address | bytes | | original proposer of the block |

LastCommitInfo

FieldTypeLabelDescription
roundint32
votesVoteInforepeated

PartSetHeader

FieldTypeLabelDescription
totalint32
hashbytes

PubKey

FieldTypeLabelDescription
typestring
databytes

Request

FieldTypeLabelDescription
echoRequestEcho
flushRequestFlush
infoRequestInfo
set_optionRequestSetOption
init_chainRequestInitChain
queryRequestQuery
begin_blockRequestBeginBlock
check_txRequestCheckTx
deliver_txRequestDeliverTx
end_blockRequestEndBlock
commitRequestCommit

RequestBeginBlock

NOTE: validators here have empty pubkeys.

FieldTypeLabelDescription
hashbytes
headerHeader
last_commit_infoLastCommitInfo
byzantine_validatorsEvidencerepeated

RequestCheckTx

FieldTypeLabelDescription
txbytes

RequestCommit

RequestDeliverTx

FieldTypeLabelDescription
txbytes

RequestEcho

FieldTypeLabelDescription
messagestring

RequestEndBlock

FieldTypeLabelDescription
heightint64

RequestFlush

RequestInfo

FieldTypeLabelDescription
versionstring

RequestInitChain

FieldTypeLabelDescription
timegoogle.protobuf.Timestamp
chain_idstring
consensus_paramsConsensusParams
validatorsValidatorUpdaterepeated
app_state_bytesbytes

RequestQuery

FieldTypeLabelDescription
databytes
pathstring
heightint64
provebool

RequestSetOption

nondeterministic

FieldTypeLabelDescription
keystring
valuestring

Response

FieldTypeLabelDescription
exceptionResponseException
echoResponseEcho
flushResponseFlush
infoResponseInfo
set_optionResponseSetOption
init_chainResponseInitChain
queryResponseQuery
begin_blockResponseBeginBlock
check_txResponseCheckTx
deliver_txResponseDeliverTx
end_blockResponseEndBlock
commitResponseCommit

ResponseBeginBlock

FieldTypeLabelDescription
tagscommon.KVPairrepeated

ResponseCheckTx

FieldTypeLabelDescription
codeuint32
databytes
logstringnondeterministic
infostringnondeterministic
gas_wantedint64
gas_usedint64
tagscommon.KVPairrepeated

ResponseCommit

FieldTypeLabelDescription
databytesreserve 1

ResponseDeliverTx

FieldTypeLabelDescription
codeuint32
databytes
logstringnondeterministic
infostringnondeterministic
gas_wantedint64
gas_usedint64
tagscommon.KVPairrepeated

ResponseEcho

FieldTypeLabelDescription
messagestring

ResponseEndBlock

FieldTypeLabelDescription
validator_updatesValidatorUpdaterepeated
consensus_param_updatesConsensusParams
tagscommon.KVPairrepeated

ResponseException

nondeterministic

FieldTypeLabelDescription
errorstring

ResponseFlush

ResponseInfo

FieldTypeLabelDescription
datastring
versionstring
last_block_heightint64
last_block_app_hashbytes

ResponseInitChain

FieldTypeLabelDescription
consensus_paramsConsensusParams
validatorsValidatorUpdaterepeated

ResponseQuery

FieldTypeLabelDescription
codeuint32
logstringbytes data = 2; // use "value" instead.

nondeterministic | | info | string | | nondeterministic | | index | int64 | | | | key | bytes | | | | value | bytes | | | | proof | bytes | | | | height | int64 | | |

ResponseSetOption

nondeterministic

FieldTypeLabelDescription
codeuint32
logstringbytes data = 2;
infostring

TxSize

TxSize contains limits on the tx size.

FieldTypeLabelDescription
max_bytesint32
max_gasint64

Validator

Validator

FieldTypeLabelDescription
addressbytes
powerint64PubKey pub_key = 2 [(gogoproto.nullable)=false];

ValidatorUpdate

ValidatorUpdate

FieldTypeLabelDescription
pub_keyPubKey
powerint64

VoteInfo

VoteInfo

FieldTypeLabelDescription
validatorValidator
signed_last_blockbool

ABCIApplication

Method NameRequest TypeResponse TypeDescription
EchoRequestEchoResponseEcho
FlushRequestFlushResponseFlush
InfoRequestInfoResponseInfo
SetOptionRequestSetOptionResponseSetOption
DeliverTxRequestDeliverTxResponseDeliverTx
CheckTxRequestCheckTxResponseCheckTx
QueryRequestQueryResponseQuery
CommitRequestCommitResponseCommit
InitChainRequestInitChainResponseInitChain
BeginBlockRequestBeginBlockResponseBeginBlock
EndBlockRequestEndBlockResponseEndBlock

Top

github.com/tendermint/tendermint/libs/common/types.proto

KI64Pair

Define these here for compatibility but use tmlibs/common.KI64Pair.

FieldTypeLabelDescription
keybytes
valueint64

KVPair

Define these here for compatibility but use tmlibs/common.KVPair.

FieldTypeLabelDescription
keybytes
valuebytes

Top

permission.proto

AccountPermissions

FieldTypeLabelDescription
BaseBasePermissionsoptional
Rolesstringrepeated

BasePermissions

FieldTypeLabelDescription
Permsuint64optional
SetBituint64optional

PermArgs

FieldTypeLabelDescription
Actionuint64optionalThe permission function
TargetbytesoptionalThe target of the action
Permissionuint64optionalPossible arguments
Rolestringoptional
Valuebooloptional

Top

acm.proto

Account

FieldTypeLabelDescription
Addressbytes
PublicKeycrypto.PublicKey
Sequenceuint64
Balanceuint64
EVMCodebytes
Permissionspermission.AccountPermissions
WASMCodebytes
CodeHashbytes
ContractMetaContractMetarepeated
ForebearbytesThe metadata is stored in the deployed account. When the deployed account creates new account (from Solidity/EVM), they point to the original deployed account where the metadata is stored. This original account is called the forebear.

ContractMeta

FieldTypeLabelDescription
CodeHashbytes
MetadataHashbytes
MetadatastringIn the dump format we would like the ABI rather than its hash

Top

rpcquery.proto

GetAccountParam

FieldTypeLabelDescription
Addressbytes

GetBlockParam

FieldTypeLabelDescription
Heightuint64

GetMetadataParam

FieldTypeLabelDescription
Addressbytes
MetadataHashbytes

GetNameParam

FieldTypeLabelDescription
Namestring

GetProposalParam

FieldTypeLabelDescription
Hashbytes

GetStatsParam

GetStorageParam

FieldTypeLabelDescription
Addressbytes
Keybytes

GetValidatorSetHistoryParam

FieldTypeLabelDescription
IncludePreviousint64Use -1 for all available history

GetValidatorSetParam

ListAccountsParam

FieldTypeLabelDescription
Querystring

ListNamesParam

FieldTypeLabelDescription
Querystring

ListProposalsParam

FieldTypeLabelDescription
Proposedbool

MetadataResult

FieldTypeLabelDescription
Metadatastring

ProposalResult

FieldTypeLabelDescription
Hashbytes
Ballotpayload.Ballot

Stats

FieldTypeLabelDescription
AccountsWithCodeuint64
AccountsWithoutCodeuint64

StatusParam

FieldTypeLabelDescription
BlockTimeWithinstring
BlockSeenTimeWithinstring

StorageValue

FieldTypeLabelDescription
Valuebytes

ValidatorSet

FieldTypeLabelDescription
heightuint64
Setvalidator.Validatorrepeated

ValidatorSetHistory

FieldTypeLabelDescription
HistoryValidatorSetrepeated

Query

Method NameRequest TypeResponse TypeDescription
StatusStatusParam.rpc.ResultStatus
GetAccountGetAccountParam.acm.Account
GetMetadataGetMetadataParamMetadataResult
GetStorageGetStorageParamStorageValue
ListAccountsListAccountsParam.acm.Account stream
GetNameGetNameParam.names.Entry
ListNamesListNamesParam.names.Entry stream
GetValidatorSetGetValidatorSetParamValidatorSet
GetValidatorSetHistoryGetValidatorSetHistoryParamValidatorSetHistory
GetProposalGetProposalParam.payload.Ballot
ListProposalsListProposalsParamProposalResult stream
GetStatsGetStatsParamStats
GetBlockHeaderGetBlockParam.types.Header

Top

tendermint.proto

Needed to proto2 rather than proto3 to get pointer field for PermArg

NodeInfo

FieldTypeLabelDescription
IDbytes
ListenAddressstring
Networkstring
Versionstring
Channelsbytes
Monikerstring
RPCAddressstring
TxIndexstring

Top

crypto.proto

PrivateKey

FieldTypeLabelDescription
CurveTypeuint32
PublicKeybytesNote may need initialisation
PrivateKeybytes

PublicKey

FieldTypeLabelDescription
CurveTypeuint32
PublicKeybytes

Signature

FieldTypeLabelDescription
CurveTypeuint32
Signaturebytes

Top

storage.proto

CommitID

This is the object that is stored in the leaves of the commitsTree - it captures the sub-tree hashes so that the commitsTree's hash becomes a mixture of the hashes of all the sub-trees.

FieldTypeLabelDescription
Versionint64
Hashbytes

Top

payload.proto

Any

FieldTypeLabelDescription
CallTxCallTx
SendTxSendTx
NameTxNameTx
PermsTxPermsTx
GovTxGovTx
BondTxBondTx
UnbondTxUnbondTx
BatchTxBatchTx
ProposalTxProposalTx

Ballot

FieldTypeLabelDescription
ProposalProposal
FinalizingTxbytes
proposalStateBallot.ProposalState
VotesVoterepeated

BatchTx

FieldTypeLabelDescription
InputsTxInputrepeated
TxsAnyrepeated

BondTx

FieldTypeLabelDescription
InputTxInputInput must be the validator that desires to bond

CallTx

A instruction to run smart contract code in the EVM

FieldTypeLabelDescription
InputTxInputThe caller's input
AddressbytesThe contract address to call or nil if we are creating a contract
GasLimituint64The upper bound on the amount of gas (and therefore EVM execution steps) this CallTx may generate
Feeuint64Fee to offer validators for processing transaction
DatabytesEVM bytecode
WASMbytesWASM bytecode
ContractMetaContractMetarepeatedSet of contracts this code will deploy

ContractMeta

FieldTypeLabelDescription
CodeHashbytes
Metastring

GovTx

FieldTypeLabelDescription
InputsTxInputrepeated
AccountUpdatesspec.TemplateAccountrepeated

NameTx

A request to claim a globally unique name across the entire chain with some optional data storage leased for a fee

FieldTypeLabelDescription
InputTxInputThe name updater
NamestringThe name to update or create
DatastringThe data to store against the name
Feeuint64The fee to provide that will determine the length of the name lease

PermsTx

An update to the on-chain permissions

FieldTypeLabelDescription
InputTxInputThe permission moderator
PermArgspermission.PermArgsThe modified permissions

Proposal

FieldTypeLabelDescription
Namestring
Descriptionstring
BatchTxBatchTx

ProposalTx

FieldTypeLabelDescription
InputTxInput
VotingWeightint64
ProposalHashbytes
ProposalProposal

SendTx

A payment between two sets of parties

FieldTypeLabelDescription
InputsTxInputrepeatedThe payers
OutputsTxOutputrepeatedThe payees

TxInput

An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than that associated with the account at Address at the time of being received

FieldTypeLabelDescription
AddressbytesThe address from which this input flows
Amountuint64The amount of native token to transfer from the input address
Sequenceuint64The sequence number that this transaction will induce (i.e. one greater than the input account's current sequence)

TxOutput

An output from a transaction that may carry an amount as a charge

FieldTypeLabelDescription
AddressbytesThe address to which this output flows
Amountuint64The amount of native token to transfer to the output address

UnbondTx

FieldTypeLabelDescription
InputTxInput
OutputTxOutputAccount to unbond

Vote

FieldTypeLabelDescription
Addressbytes
VotingWeightint64

Ballot.ProposalState

NameNumberDescription
PROPOSED0PROPOSED might be expired, if sequence number of any of the input accounts are out of date
EXECUTED1
FAILED2

Top

dump.proto

AccountStorage

FieldTypeLabelDescription
Addressbytes
StorageStoragerepeated

Dump

FieldTypeLabelDescription
Heightuint64
Accountacm.Account
AccountStorageAccountStorage
EVMEventEVMEvent
Namenames.Entry

EVMEvent

FieldTypeLabelDescription
ChainIDstringThe original ChainID from for this event
Indexuint64The original index for this event
Timegoogle.protobuf.TimestampThe original block time for this transaction
Eventexec.LogEventThe event itself

Storage

FieldTypeLabelDescription
Keybytes
Valuebytes

Top

rpcdump.proto

GetDumpParam

FieldTypeLabelDescription
heightuint64

Dump

Method NameRequest TypeResponse TypeDescription
GetDumpGetDumpParam.dump.Dump stream

Top

keys.proto

AddNameRequest

FieldTypeLabelDescription
Keynamestring
Addressstring

AddNameResponse

ExportRequest

FieldTypeLabelDescription
Passphrasestring
Namestring
Addressstring

ExportResponse

FieldTypeLabelDescription
Publickeybytes
Privatekeybytes
Addressbytes
CurveTypestring

GenRequest

FieldTypeLabelDescription
Passphrasestring
CurveTypestring
KeyNamestring

GenResponse

FieldTypeLabelDescription
Addressstring

HashRequest

FieldTypeLabelDescription
Hashtypestring
Messagebytes

HashResponse

FieldTypeLabelDescription
Hashstring

ImportJSONRequest

FieldTypeLabelDescription
Passphrasestring
JSONstring

ImportRequest

FieldTypeLabelDescription
Passphrasestring
Namestring
CurveTypestring
KeyBytesbytes

ImportResponse

FieldTypeLabelDescription
Addressstring

KeyID

FieldTypeLabelDescription
Addressstring
KeyNamestringrepeated

ListRequest

FieldTypeLabelDescription
KeyNamestring

ListResponse

FieldTypeLabelDescription
keyKeyIDrepeated

PubRequest

FieldTypeLabelDescription
Addressstring
Namestring

PubResponse

FieldTypeLabelDescription
PublicKeybytes
CurveTypestring

RemoveNameRequest

FieldTypeLabelDescription
KeyNamestring

RemoveNameResponse

SignRequest

FieldTypeLabelDescription
Passphrasestring
Addressstring
Namestring
Messagebytes

SignResponse

FieldTypeLabelDescription
Signaturecrypto.Signature

VerifyRequest

FieldTypeLabelDescription
PublicKeybytes
Messagebytes
Signaturecrypto.Signature

VerifyResponse

Keys

Method NameRequest TypeResponse TypeDescription
GenerateKeyGenRequestGenResponse
PublicKeyPubRequestPubResponse
SignSignRequestSignResponse
VerifyVerifyRequestVerifyResponse
ImportImportRequestImportResponse
ImportJSONImportJSONRequestImportResponse
ExportExportRequestExportResponse
HashHashRequestHashResponse
RemoveNameRemoveNameRequestRemoveNameResponse
ListListRequestListResponse
AddNameAddNameRequestAddNameResponse

Top

errors.proto

Exception

FieldTypeLabelDescription
Codeuint32
Exceptionstring

Top

rpc.proto

Needed to proto2 rather than proto3 to get pointer field for PermArg

ResultStatus

FieldTypeLabelDescription
ChainIDstring
RunIDstring
BurrowVersionstring
GenesisHashbytes
NodeInfotendermint.NodeInfo
SyncInfobcm.SyncInfo
CatchingUpboolWhen catching up in fast sync
ValidatorInfovalidator.Validator

Top

rpcevents.proto

BlockRange

An inclusive range of blocks to include in output

FieldTypeLabelDescription
StartBoundBounds can be set to: absolute: block height relative: block height counting back from latest latest: latest block when call is processed stream: for End keep sending new blocks, for start same as latest
EndBound

BlocksRequest

FieldTypeLabelDescription
BlockRangeBlockRange
QuerystringSpecify a query on which to match the tags of events. Tag

For example: EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF' |

Bound

FieldTypeLabelDescription
TypeBound.BoundType
Indexuint64

EventsResponse

FieldTypeLabelDescription
Heightuint64
Eventsexec.Eventrepeated

GetBlockRequest

FieldTypeLabelDescription
Heightuint64Height of block required
WaitboolWhether to wait for the block to become available

GetTxsRequest

FieldTypeLabelDescription
StartHeightuint64
EndHeightuint64
Querystring

GetTxsResponse

FieldTypeLabelDescription
Heightuint64
TxExecutionsexec.TxExecutionrepeated

TxRequest

FieldTypeLabelDescription
TxHashbytesHeight of block required
WaitboolWhether to wait for the block to become available

Bound.BoundType

NameNumberDescription
ABSOLUTE0Index is absolute index of an item
RELATIVE1Index is an offset relative to last item
FIRST2The first block
LATEST3Ignore provided index and evaluate to latest index
STREAM4Ignore provided index and stream new objects as they are generated

ExecutionEvents


Execution events

Method NameRequest TypeResponse TypeDescription
StreamBlocksRequest.exec.StreamEvent streamGet StreamEvents (including transactions) for a range of block heights
TxTxRequest.exec.TxExecutionGet a particular TxExecution by hash
EventsBlocksRequestEventsResponse streamGetEvents provides events streaming one block at a time - that is all events emitted in a particular block are guaranteed to be delivered in each GetEventsResponse

Top

bcm.proto

Needed to proto2 rather than proto3 to get pointer field for PermArg

PersistedState

FieldTypeLabelDescription
AppHashAfterLastBlockbytes
LastBlockTimegoogle.protobuf.Timestamp
LastBlockHeightuint64
GenesisHashbytes

SyncInfo

FieldTypeLabelDescription
LatestBlockHeightuint64
LatestBlockHashbytes
LatestAppHashbytes
LatestBlockTimegoogle.protobuf.TimestampTimestamp of block as set by the block proposer
LatestBlockSeenTimegoogle.protobuf.TimestampTime at which we committed the last block
LatestBlockDurationgoogle.protobuf.DurationTime elapsed since last commit

Top

spec.proto

TemplateAccount

FieldTypeLabelDescription
Namestring
Addressbytes
PublicKeycrypto.PublicKey
Amountsbalance.Balancerepeated
Permissionsstringrepeated
Rolesstringrepeated
Codebytes

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── acm.proto
├── balance.proto
├── bcm.proto
├── crypto.proto
├── dump.proto
├── encoding.proto
├── errors.proto
├── exec.proto
├── github.com
│   ├── gogo
│   │   └── protobuf
│   │       └── gogoproto
│   │           └── gogo.proto
│   └── tendermint
│       └── tendermint
│           ├── abci
│           │   └── types
│           │       └── types.proto
│           └── libs
│               └── common
│                   └── types.proto
├── google
│   └── protobuf
│       ├── descriptor.proto
│       └── timestamp.proto
├── keys.proto
├── names.proto
├── payload.proto
├── permission.proto
├── rpcdump.proto
├── rpcevents.proto
├── rpc.proto
├── rpcquery.proto
├── rpctransact.proto
├── spec.proto
├── storage.proto
├── tendermint.proto
├── txs.proto
└── validator.proto

12 directories, 27 files

Protobuf sources

src:./balance.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/acm/balance";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

package balance;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message Balance {
    option (gogoproto.goproto_sizecache) = false;
    option (gogoproto.goproto_unkeyed) = false;
    option (gogoproto.goproto_stringer) = false;
    uint32 Type = 1 [(gogoproto.casttype) = "Type"];
    uint64 Amount = 2;
}

src:./exec.proto


syntax = 'proto3';

package exec;

option go_package = "github.com/hyperledger/burrow/execution/exec";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "github.com/tendermint/tendermint/abci/types/types.proto";
import "google/protobuf/timestamp.proto";

import "errors.proto";
import "names.proto";
import "txs.proto";
import "permission.proto";
import "spec.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

// This message exists purely for framing []StreamEvent
message StreamEvents {
    repeated StreamEvent StreamEvents = 1;
}

message StreamEvent {
    option (gogoproto.onlyone) = true;
    BeginBlock BeginBlock = 1;
    BeginTx BeginTx = 2;
    txs.Envelope Envelope = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"];
    Event Event = 4;
    EndTx EndTx = 5;
    EndBlock EndBlock = 6;
}

message BeginBlock {
    // The height of this block
    uint64 Height = 1;
    types.Header Header = 2;
}

message EndBlock {
    uint64 Height = 1;
}

message BeginTx {
    TxHeader TxHeader = 1;
    // Result of tx execution
    Result Result = 2;
    // If tx execution was an exception
    errors.Exception Exception = 4;
}

message EndTx {
    // The hash of the transaction that caused this event to be generated
    bytes TxHash = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

message TxHeader {
    // Transaction type
    uint32 TxType = 1 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"];
    // The hash of the transaction that caused this event to be generated
    bytes TxHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // The block height at which this Tx was included
    uint64 Height = 3;
    // The index of this transaction within the block
    uint64 Index = 4;
    // The origin information from the chain on which this tx was originally committed (if restored or otherwise imported)
    Origin Origin = 5;
}

message BlockExecution {
    // The height of this block
    uint64 Height = 1;
    types.Header Header = 2;
    repeated TxExecution TxExecutions = 3;
}

message TxExecutionKey {
    // The block height
    uint64 Height = 1;
    // The offset of the TxExecution in bytes
    uint64 Offset = 2;
}

message TxExecution {
    TxHeader Header = 1 [(gogoproto.embed) = true];
    // Signed Tx that triggered this execution
    txs.Envelope Envelope = 6 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"];
    // Execution events
    repeated Event Events = 7;
    // The execution results
    Result Result = 8;
    // The transaction receipt
    txs.Receipt Receipt = 9;
    // If execution was an exception
    errors.Exception Exception = 10;
    // A proposal may contain other transactions
    repeated TxExecution TxExecutions = 11;
}

message Origin {
    // The original ChainID from for this transaction
    string ChainID = 1;
    // The original height at which this transaction was committed
    uint64 Height = 2;
    // The original index in the block
    uint64 Index = 3;
    // The original block time for this transaction
    google.protobuf.Timestamp Time = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
}

message Header {
    option (gogoproto.goproto_stringer) = false;
    // Transaction type
    uint32 TxType = 1 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"];
    // The hash of the transaction that caused this event to be generated
    bytes TxHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // The type of event
    uint32 EventType = 3 [(gogoproto.casttype) = "EventType"];
    // EventID published with event
    string EventID = 4;
    // The block height at which this event was emitted
    uint64 Height = 5;
    // The index of this event relative to other events generated by the same transaction
    uint64 Index = 6;
    // If event is exception
    errors.Exception Exception = 7;
}

message Event {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.onlyone) = true;
    Header Header = 1;
    InputEvent Input = 2;
    OutputEvent Output = 3;
    CallEvent Call = 4;
    LogEvent Log = 5;
    GovernAccountEvent GovernAccount = 6;
}

// Could structure this further if needed - sum type of various results relevant to different transaction types
message Result {
    // EVM execution return
    bytes Return = 1;
    // Gas used in computation
    uint64 GasUsed = 2;
    // Name entry created
    names.Entry NameEntry = 3;
    // Permission update performed
    permission.PermArgs PermArgs = 4;
}

message LogEvent {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    bytes Data = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    repeated bytes Topics = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.Word256", (gogoproto.nullable) = false];
}

message CallEvent {
    uint32 CallType = 5 [(gogoproto.casttype) = "CallType"];
    CallData CallData = 1;
    bytes Origin = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    uint64 StackDepth = 3;
    bytes Return = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

message GovernAccountEvent {
    spec.TemplateAccount AccountUpdate = 1;
}

message InputEvent {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
}

message OutputEvent {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
}

message CallData {
    bytes Caller = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    bytes Callee = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    bytes Data = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    uint64 Value = 4;
    uint64 Gas = 5;
}

src:./names.proto


syntax = 'proto3';

package names;

option go_package = "github.com/hyperledger/burrow/execution/names";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

option (gogoproto.stable_marshaler_all) = true;
// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

// NameReg provides a global key value store based on Name, Data pairs that are subject to expiry and ownership by an
// account.
message Entry {
    option (gogoproto.goproto_stringer) = false;
    // registered name for the entry
    string Name = 1;
    // address that created the entry
    bytes Owner = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    // data to store under this name
    string Data = 3;
    // block at which this entry expires
    uint64 Expires = 4;
}


src:./encoding.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/encoding";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

package encoding;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

// For testing
message TestMessage {
    option (gogoproto.goproto_stringer) = false;
    uint32 Type = 1;
    uint64 Amount = 2;
}

src:./validator.proto


syntax = 'proto3';

package validator;

option go_package = "github.com/hyperledger/burrow/acm/validator";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "crypto.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message Validator {
    option (gogoproto.goproto_stringer) = false;
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
    crypto.PublicKey PublicKey = 2 [(gogoproto.nullable) = false];
    uint64 Power = 3;
}

src:./txs.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/txs";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "crypto.proto";

package txs;

// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

// An envelope contains both the signable Tx and the signatures for each input (in signatories)
message Envelope {
    option (gogoproto.goproto_stringer) = false;
    repeated Signatory Signatories = 1 [(gogoproto.nullable) = false];
    // Canonical bytes of the Tx ready to be signed
    bytes Tx = 2 [(gogoproto.customtype) = "Tx"];
}

// Signatory contains signature and one or both of Address and PublicKey to identify the signer
message Signatory {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
    crypto.PublicKey PublicKey = 2;
    crypto.Signature Signature = 4;
}

// BroadcastTx or Transaction receipt
message Receipt {
    // Transaction type
    uint32 TxType = 1[(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"];
    // The hash of the transaction that caused this event to be generated
    bytes TxHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // Whether the transaction creates a contract
    bool CreatesContract = 3;
    // The address of the contract being called
    bytes ContractAddress = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
}

src:./rpctransact.proto


syntax = 'proto3';

package rpctransact;

option go_package = "github.com/hyperledger/burrow/rpc/rpctransact";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/duration.proto";

import "exec.proto";
import "payload.proto";
import "txs.proto";

// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

// Transaction Service Definition
service Transact {
    // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side
    // and wait for it to be included in block
    rpc BroadcastTxSync (TxEnvelopeParam) returns (exec.TxExecution);
    // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side
    rpc BroadcastTxAsync (TxEnvelopeParam) returns (txs.Receipt);

    // Sign transaction server-side
    rpc SignTx (TxEnvelopeParam) returns (TxEnvelope);
    // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign
    rpc FormulateTx (payload.Any) returns (TxEnvelope);

    // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response
    rpc CallTxSync (payload.CallTx) returns (exec.TxExecution);
    // Formulate and sign a CallTx transaction signed server-side
    rpc CallTxAsync (payload.CallTx) returns (txs.Receipt);
    // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved
    // and wait for the transaction to be included in a block
    rpc CallTxSim (payload.CallTx) returns (exec.TxExecution);
    // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved
    rpc CallCodeSim (CallCodeParam) returns (exec.TxExecution);

    // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response
    rpc SendTxSync (payload.SendTx) returns (exec.TxExecution);
    // Formulate and  SendTx transaction signed server-side
    rpc SendTxAsync (payload.SendTx) returns (txs.Receipt);

    // Formualte a NameTx signed server-side and wait for it to be included in a block returning the registered name
    rpc NameTxSync (payload.NameTx) returns (exec.TxExecution);
    // Formulate a NameTx signed server-side
    rpc NameTxAsync (payload.NameTx) returns (txs.Receipt);
}

message CallCodeParam {
    bytes FromAddress = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    bytes Code = 2;
    bytes Data = 3;
}

message TxEnvelope {
    txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"];
}

message TxEnvelopeParam {
    // An existing Envelope - either signed or unsigned - if the latter will be signed server-side
    txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"];
    // If no Envelope provided then one will be generated from the provided payload and signed server-side
    payload.Any Payload = 2;
    // The amount of time to wait for the transaction to be committed and the TxExecution to be returned (server-side).
    // If zero there wait is unbounded. Timed out transactions return SyncInfo state that may be helpful debugging
    // non-committed transactions - this timeout must be less than client timeout to see such information!
    google.protobuf.Duration Timeout = 3 [(gogoproto.nullable) = false, (gogoproto.stdduration) = true];
}


src:./github.com/tendermint/tendermint/abci/types/types.proto


syntax = "proto3";
package types;

// For more information on gogo.proto, see:
// https://github.com/gogo/protobuf/blob/master/extensions.md
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
import "github.com/tendermint/tendermint/libs/common/types.proto";

// This file is copied from http://github.com/tendermint/abci
// NOTE: When using custom types, mind the warnings.
// https://github.com/gogo/protobuf/blob/master/custom_types.md#warnings-and-issues

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
// Generate tests
option (gogoproto.populate_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;

//----------------------------------------
// Request types

message Request {
  oneof value {
    RequestEcho echo = 2;
    RequestFlush flush = 3;
    RequestInfo info = 4;
    RequestSetOption set_option = 5;
    RequestInitChain init_chain = 6;
    RequestQuery query = 7;
    RequestBeginBlock begin_block = 8;
    RequestCheckTx check_tx = 9;
    RequestDeliverTx deliver_tx = 19;
    RequestEndBlock end_block = 11;
    RequestCommit commit = 12;
  }
}

message RequestEcho {
  string message = 1;
}

message RequestFlush {
}

message RequestInfo {
  string version = 1;
}

// nondeterministic
message RequestSetOption {
  string key = 1;
  string value = 2;
}

message RequestInitChain {
  google.protobuf.Timestamp time = 1  [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
  string chain_id = 2;
  ConsensusParams consensus_params = 3;
  repeated ValidatorUpdate validators = 4  [(gogoproto.nullable)=false];
  bytes app_state_bytes = 5;
}

message RequestQuery {
  bytes data = 1;
  string path = 2;
  int64 height = 3;
  bool prove = 4;
}

// NOTE: validators here have empty pubkeys.
message RequestBeginBlock {
  bytes hash = 1;
  Header header = 2 [(gogoproto.nullable)=false];
  LastCommitInfo last_commit_info = 3 [(gogoproto.nullable)=false];
  repeated Evidence byzantine_validators = 4 [(gogoproto.nullable)=false];
}

message RequestCheckTx {
  bytes tx = 1;
}

message RequestDeliverTx {
  bytes tx = 1;
}

message RequestEndBlock {
  int64 height = 1;
}

message RequestCommit {
}

//----------------------------------------
// Response types

message Response {
  oneof value {
    ResponseException exception = 1;
    ResponseEcho echo = 2;
    ResponseFlush flush = 3;
    ResponseInfo info = 4;
    ResponseSetOption set_option = 5;
    ResponseInitChain init_chain = 6;
    ResponseQuery query = 7;
    ResponseBeginBlock begin_block = 8;
    ResponseCheckTx check_tx = 9;
    ResponseDeliverTx deliver_tx = 10;
    ResponseEndBlock end_block = 11;
    ResponseCommit commit = 12;
  }
}

// nondeterministic
message ResponseException {
  string error = 1;
}

message ResponseEcho {
  string message = 1;
}

message ResponseFlush {
}

message ResponseInfo {
  string data = 1;
  string version = 2;
  int64 last_block_height = 3;
  bytes last_block_app_hash = 4;
}

// nondeterministic
message ResponseSetOption {
  uint32 code = 1;
  // bytes data = 2;
  string log = 3;
  string info = 4;
}

message ResponseInitChain {
  ConsensusParams consensus_params = 1;
  repeated ValidatorUpdate validators = 2 [(gogoproto.nullable)=false];
}

message ResponseQuery {
  uint32 code = 1;
  // bytes data = 2; // use "value" instead.
  string log = 3; // nondeterministic
  string info = 4; // nondeterministic
  int64 index = 5;
  bytes key = 6;
  bytes value = 7;
  bytes proof = 8;
  int64 height = 9;
}

message ResponseBeginBlock {
  repeated common.KVPair tags = 1 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"];
}

message ResponseCheckTx {
  uint32 code = 1;
  bytes data = 2;
  string log = 3; // nondeterministic
  string info = 4; // nondeterministic
  int64 gas_wanted  = 5;
  int64 gas_used = 6;
  repeated common.KVPair tags = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"];
}

message ResponseDeliverTx {
  uint32 code = 1;
  bytes data = 2;
  string log = 3; // nondeterministic
  string info = 4; // nondeterministic
  int64 gas_wanted = 5;
  int64 gas_used = 6;
  repeated common.KVPair tags = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"];
}

message ResponseEndBlock {
  repeated ValidatorUpdate validator_updates = 1 [(gogoproto.nullable)=false];
  ConsensusParams consensus_param_updates = 2;
  repeated common.KVPair tags = 3 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"];
}

message ResponseCommit {
  // reserve 1
  bytes data = 2;
}

//----------------------------------------
// Misc.

// ConsensusParams contains all consensus-relevant parameters
// that can be adjusted by the abci app
message ConsensusParams {
  BlockSize block_size = 1;
  TxSize tx_size = 2;
  BlockGossip block_gossip = 3;
}

// BlockSize contains limits on the block size.
message BlockSize {
  int32 max_bytes = 1;
  int64 max_gas = 2;
}

// TxSize contains limits on the tx size.
message TxSize {
  int32 max_bytes = 1;
  int64 max_gas = 2;
}

// BlockGossip determine consensus critical
// elements of how blocks are gossiped
message BlockGossip {
  // Note: must not be 0
  int32 block_part_size_bytes = 1;
}

message LastCommitInfo {
  int32 round = 1;
  repeated VoteInfo votes = 2 [(gogoproto.nullable)=false];
}

//----------------------------------------
// Blockchain Types

message Header {
  // basic block info
  string chain_id = 1 [(gogoproto.customname)="ChainID"];
  int64 height = 2;
  google.protobuf.Timestamp time = 3 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
  int64 num_txs = 4;
  int64 total_txs = 5;

  // prev block info
  BlockID last_block_id = 6 [(gogoproto.nullable)=false];

  // hashes of block data
  bytes last_commit_hash = 7; // commit from validators from the last block
  bytes data_hash = 8;        // transactions

  // hashes from the app output from the prev block
  bytes validators_hash = 9;   // validators for the current block
  bytes next_validators_hash = 10;   // validators for the next block
  bytes consensus_hash = 11;   // consensus params for current block
  bytes app_hash = 12;         // state after txs from the previous block
  bytes last_results_hash = 13;// root hash of all results from the txs from the previous block

  // consensus info
  bytes evidence_hash = 14;    // evidence included in the block
  bytes proposer_address = 15; // original proposer of the block
}

message BlockID {
  bytes hash = 1;
  PartSetHeader parts_header = 2 [(gogoproto.nullable)=false];
}

message PartSetHeader {
  int32 total = 1;
  bytes hash = 2;
}

// Validator
message Validator {
  bytes address = 1;
  //PubKey pub_key = 2 [(gogoproto.nullable)=false];
  int64 power = 3;
}

// ValidatorUpdate
message ValidatorUpdate {
  PubKey pub_key = 1 [(gogoproto.nullable)=false];
  int64 power = 2;
}

// VoteInfo
message VoteInfo {
  Validator validator = 1 [(gogoproto.nullable)=false];
  bool signed_last_block = 2;
}

message PubKey {
  string type = 1;
  bytes  data = 2;
}

message Evidence {
  string type = 1;
  Validator validator = 2 [(gogoproto.nullable)=false];
  int64 height = 3;
  google.protobuf.Timestamp time = 4 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
  int64 total_voting_power = 5;
}

//----------------------------------------
// Service Definition

service ABCIApplication {
  rpc Echo(RequestEcho) returns (ResponseEcho) ;
  rpc Flush(RequestFlush) returns (ResponseFlush);
  rpc Info(RequestInfo) returns (ResponseInfo);
  rpc SetOption(RequestSetOption) returns (ResponseSetOption);
  rpc DeliverTx(RequestDeliverTx) returns (ResponseDeliverTx);
  rpc CheckTx(RequestCheckTx) returns (ResponseCheckTx);
  rpc Query(RequestQuery) returns (ResponseQuery);
  rpc Commit(RequestCommit) returns (ResponseCommit);
  rpc InitChain(RequestInitChain) returns (ResponseInitChain);
  rpc BeginBlock(RequestBeginBlock) returns (ResponseBeginBlock);
  rpc EndBlock(RequestEndBlock) returns (ResponseEndBlock);
}

src:./github.com/tendermint/tendermint/libs/common/types.proto


syntax = "proto3";
package common;

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
// Generate tests
option (gogoproto.populate_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;

//----------------------------------------
// Abstract types

// Define these here for compatibility but use tmlibs/common.KVPair.
message KVPair {
  bytes key = 1;
  bytes value = 2;
}

// Define these here for compatibility but use tmlibs/common.KI64Pair.
message KI64Pair {
  bytes key = 1;
  int64 value = 2;
}

src:./permission.proto


syntax = 'proto2';

package permission;

option go_package = "github.com/hyperledger/burrow/permission";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

message AccountPermissions {
    optional BasePermissions Base = 1 [(gogoproto.nullable) = false];
    option (gogoproto.goproto_sizecache) = false;
    option (gogoproto.goproto_unkeyed) = false;

    repeated string Roles = 2;
}

message BasePermissions {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_sizecache) = false;
    option (gogoproto.goproto_unkeyed) = false;
    optional uint64 Perms = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false];
    optional uint64 SetBit = 2 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false];
}

message PermArgs {
    option (gogoproto.goproto_unrecognized) = false;
    option (gogoproto.goproto_stringer) = false;
    // The permission function
    optional uint64 Action = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false];
    // The target of the action
    optional bytes Target = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
    // Possible arguments
    optional uint64 Permission = 3 [(gogoproto.casttype) = "PermFlag"];
    optional string Role = 4;
    optional bool Value = 5;
}

src:./acm.proto


syntax = 'proto3';

package acm;

option go_package = "github.com/hyperledger/burrow/acm";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "permission.proto";
import "crypto.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message Account {
    option (gogoproto.goproto_stringer) = false;
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    crypto.PublicKey PublicKey = 2 [(gogoproto.nullable) = false];
    uint64 Sequence = 3;
    uint64 Balance = 4;
    bytes EVMCode = 5 [(gogoproto.customtype) = "Bytecode", (gogoproto.nullable) = false];
    permission.AccountPermissions Permissions = 6 [(gogoproto.nullable) = false];
    bytes WASMCode = 7 [(gogoproto.customtype) = "Bytecode", (gogoproto.jsontag) = ",omitempty", (gogoproto.nullable) = false];
    bytes CodeHash = 8 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false, (gogoproto.jsontag) = "-"];
    repeated ContractMeta ContractMeta = 9;
    // The metadata is stored in the deployed account. When the deployed account creates new account (from Solidity/EVM), they point to the original deployed
    // account where the metadata is stored. This original account is called the forebear.
    bytes Forebear = 10 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
}

message ContractMeta {
    bytes CodeHash = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    bytes MetadataHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // In the dump format we would like the ABI rather than its hash
    string Metadata = 3;
}

src:./rpcquery.proto


syntax = 'proto3';

package rpcquery;

option go_package = "github.com/hyperledger/burrow/rpc/rpcquery";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "github.com/tendermint/tendermint/abci/types/types.proto";

import "names.proto";
import "acm.proto";
import "validator.proto";
import "rpc.proto";
import "payload.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

service Query {
    rpc Status (StatusParam) returns (rpc.ResultStatus);
    rpc GetAccount (GetAccountParam) returns (acm.Account);
    rpc GetMetadata (GetMetadataParam) returns (MetadataResult);
    rpc GetStorage (GetStorageParam) returns (StorageValue);

    rpc ListAccounts (ListAccountsParam) returns (stream acm.Account);

    rpc GetName (GetNameParam) returns (names.Entry);
    rpc ListNames (ListNamesParam) returns (stream names.Entry);

    rpc GetValidatorSet (GetValidatorSetParam) returns (ValidatorSet);
    rpc GetValidatorSetHistory (GetValidatorSetHistoryParam) returns (ValidatorSetHistory);

    rpc GetProposal(GetProposalParam) returns (payload.Ballot);
    rpc ListProposals(ListProposalsParam) returns (stream ProposalResult);

    rpc GetStats(GetStatsParam) returns (Stats);

    rpc GetBlockHeader(GetBlockParam) returns (types.Header);
}

message StatusParam {
    string BlockTimeWithin = 1;
    string BlockSeenTimeWithin = 2;
}

message GetAccountParam {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
}

message GetMetadataParam {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
    bytes MetadataHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes"];
}

message MetadataResult {
    string Metadata = 1;
}

message GetStorageParam {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    bytes Key = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.Word256", (gogoproto.nullable) = false];
}

message StorageValue {
    bytes Value = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

message ListAccountsParam {
    string Query = 1;
}

message GetNameParam {
    string Name = 1;
}

message ListNamesParam {
    string Query = 1;
}

message GetValidatorSetParam {

}

message GetValidatorSetHistoryParam {
    // Use -1 for all available history
    int64 IncludePrevious = 1;
}

message ValidatorSetHistory {
    repeated ValidatorSet History = 1;
}

message ValidatorSet {
    uint64 height = 1;
    repeated validator.Validator Set = 2;
}

message GetProposalParam {
    bytes Hash = 1;
}

message ListProposalsParam {
    bool Proposed = 1;
}

message ProposalResult {
    bytes Hash = 1;
    payload.Ballot Ballot = 2;
}

message GetStatsParam {

}

message Stats {
    uint64 AccountsWithCode = 1;
    uint64 AccountsWithoutCode = 2;
}

message GetBlockParam {
    uint64 Height = 1;
}

src:./tendermint.proto


// Needed to proto2 rather than proto3 to get pointer field for PermArg
syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/consensus/tendermint";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

package tendermint;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message NodeInfo {
    bytes ID = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    string ListenAddress = 2;
    string Network = 3;
    string Version = 4;
    bytes Channels = 5 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    string Moniker = 6;
    string RPCAddress = 7;
    string TxIndex = 8;
}

src:./crypto.proto


syntax = 'proto3';

package crypto;

option go_package = "github.com/hyperledger/burrow/crypto";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message PublicKey {
    option (gogoproto.goproto_stringer) = false;
    uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"];
    bytes PublicKey = 2[(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

message PrivateKey {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;
    uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"];
    // Note may need initialisation
    bytes PublicKey = 2;
    bytes PrivateKey = 3;
}

message Signature {
    option (gogoproto.goproto_stringer) = false;
    uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"];
    bytes Signature = 2;
}

src:./storage.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/storage";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

package storage;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

// This is the object that is stored in the leaves of the commitsTree - it captures the sub-tree hashes so that the
// commitsTree's hash becomes a mixture of the hashes of all the sub-trees.
message CommitID {
    option (gogoproto.goproto_stringer) = false;
    int64 Version = 1;
    bytes Hash = 2;
}

src:./payload.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/txs/payload";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "permission.proto";
import "spec.proto";

package payload;

// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

message Any {
    option (gogoproto.onlyone) = true;

    CallTx CallTx = 1;
    SendTx SendTx = 2;
    NameTx NameTx = 3;
    PermsTx PermsTx = 4;
    GovTx GovTx = 5;
    BondTx BondTx = 6;
    UnbondTx UnbondTx = 7;
    BatchTx BatchTx = 8;
    ProposalTx ProposalTx = 9;
}

// An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than
// that associated with the account at Address at the time of being received
message TxInput {
    option (gogoproto.goproto_stringer) = false;
    // The address from which this input flows
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    // The amount of native token to transfer from the input address
    uint64 Amount = 2;
    // The sequence number that this transaction will induce (i.e. one greater than the input account's current sequence)
    uint64 Sequence = 3;
}

// An output from a transaction that may carry an amount as a charge
message TxOutput {
    option (gogoproto.goproto_stringer) = false;
    // The address to which this output flows
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    // The amount of native token to transfer to the output address
    uint64 Amount = 2;
}

// A instruction to run smart contract code in the EVM
message CallTx {
    option (gogoproto.goproto_stringer) = false;
    // The caller's input
    TxInput Input = 1;
    // The contract address to call or nil if we are creating a contract
    bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"];
    // The upper bound on the amount of gas (and therefore EVM execution steps) this CallTx may generate
    uint64 GasLimit = 3;
    // Fee to offer validators for processing transaction
    uint64 Fee = 4;
    // EVM bytecode
    bytes Data = 5 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // WASM bytecode
    bytes WASM = 6 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false, (gogoproto.jsontag)="tags,omitempty"];
    // Set of contracts this code will deploy
    repeated ContractMeta ContractMeta = 7;
}

message ContractMeta {
    bytes CodeHash = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    string Meta = 2;
}

// A payment between two sets of parties
message SendTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;
    // The payers
    repeated TxInput Inputs = 1;
    // The payees
    repeated TxOutput Outputs = 2;
}

// An update to the on-chain permissions
message PermsTx {
    option (gogoproto.goproto_stringer) = false;
    // The permission moderator
    TxInput Input = 1;
    // The modified permissions
    permission.PermArgs PermArgs = 2 [(gogoproto.nullable) = false];
}

// A request to claim a globally unique name across the entire chain with some optional data storage leased for a fee
message NameTx {
    option (gogoproto.goproto_stringer) = false;
    // The name updater
    TxInput Input = 1;
    // The name to update or create
    string Name = 2;
    // The data to store against the name
    string Data = 3;
    // The fee to provide that will determine the length of the name lease
    uint64 Fee = 4;
}

message BondTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    // Input must be the validator that desires to bond
    TxInput Input = 1;
}

message UnbondTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    TxInput Input = 1;
    // Account to unbond
    TxOutput Output = 2;
}

message GovTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    repeated TxInput Inputs = 1;
    repeated spec.TemplateAccount AccountUpdates = 2 [(gogoproto.nullable) = true];
}

message ProposalTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    TxInput Input = 1;
    int64 VotingWeight = 2;
    bytes ProposalHash = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes"];
    Proposal Proposal = 4;
}

message BatchTx {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    repeated TxInput Inputs = 1;
    repeated Any Txs = 2;
}

message Vote {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    int64 VotingWeight = 2;
}

message Proposal {
    option (gogoproto.goproto_stringer) = false;
    option (gogoproto.goproto_getters) = false;

    string Name = 1;
    string Description = 2;
    BatchTx BatchTx = 3;
}

message Ballot {
    Proposal Proposal = 1;
    bytes FinalizingTx = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes"];
    enum ProposalState {
        // PROPOSED might be expired, if sequence number of any of the input accounts are out of date
        PROPOSED = 0;
        EXECUTED = 1;
        FAILED = 2;
    }
    ProposalState proposalState = 4;
    repeated Vote Votes = 5;
}

src:./dump.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/dump";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";

import "acm.proto";
import "exec.proto";
import "names.proto";

package dump;

option (gogoproto.stable_marshaler_all) = true;
// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

message Storage {
    bytes Key = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.Word256", (gogoproto.nullable) = false];
    bytes Value = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

message AccountStorage {
    bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false];
    repeated Storage Storage = 2;
}

message EVMEvent {
    // The original ChainID from for this event
    string ChainID = 1;
    // The original index for this event
    uint64 Index = 4;
    // The original block time for this transaction
    google.protobuf.Timestamp Time = 2 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
    // The event itself
    exec.LogEvent Event = 3;
}

message Dump {
    uint64 Height = 1;

    acm.Account Account = 2;
    AccountStorage AccountStorage = 3;
    EVMEvent EVMEvent = 4;
    names.Entry Name = 5;
}

src:./rpcdump.proto


syntax = 'proto3';

package rpcdump;

option go_package = "github.com/hyperledger/burrow/rpc/rpcdump";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "dump.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

service Dump {
    rpc GetDump(GetDumpParam) returns (stream dump.Dump);
}

message GetDumpParam {
    uint64 height = 1;
}

src:./keys.proto


syntax = "proto3";

option go_package = "github.com/hyperledger/burrow/keys";

package keys;

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "crypto.proto";

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

service Keys {
    rpc GenerateKey(GenRequest) returns (GenResponse);
    rpc PublicKey(PubRequest) returns (PubResponse);
    rpc Sign(SignRequest) returns (SignResponse);
    rpc Verify(VerifyRequest) returns (VerifyResponse);
    rpc Import(ImportRequest) returns (ImportResponse);
    rpc ImportJSON(ImportJSONRequest) returns (ImportResponse);
    rpc Export(ExportRequest) returns (ExportResponse);
    rpc Hash(HashRequest) returns (HashResponse);
    rpc RemoveName(RemoveNameRequest) returns (RemoveNameResponse);
    rpc List(ListRequest) returns (ListResponse);
    rpc AddName(AddNameRequest) returns (AddNameResponse);
}

// Some empty types we may define later

message ListRequest {
    string KeyName = 1;
}

message VerifyResponse {

}

message RemoveNameResponse {

}

message AddNameResponse {

}

message RemoveNameRequest {
    string KeyName = 1;
}


message GenRequest {
    string Passphrase = 1;
    string CurveType = 2;
    string KeyName = 3;
}

message GenResponse {
    string Address = 1;
}

message PubRequest {
    string Address = 1;
    string Name = 2;
}

message PubResponse {
    bytes PublicKey = 1;
    string CurveType = 2;
}

message ImportJSONRequest {
    string Passphrase = 1;
    string JSON = 2;
}

message ImportResponse {
    string Address = 1;
}

message ImportRequest {
    string Passphrase = 1;
    string Name = 2;
    string CurveType = 3;
    bytes KeyBytes = 4;
}

message ExportRequest {
    string Passphrase = 1;
    string Name = 2;
    string Address = 3;
}

message ExportResponse {
    bytes Publickey = 1;
    bytes Privatekey = 2;
    bytes Address = 3;
    string CurveType = 4;
}

message SignRequest {
    string Passphrase = 1;
    string Address = 2;
    string Name = 3;
    bytes Message = 4;
}

message SignResponse {
    crypto.Signature Signature = 3;
}

message VerifyRequest {
    bytes PublicKey = 2;
    bytes Message = 3;
    crypto.Signature Signature = 5;
}

message HashRequest {
    string Hashtype = 1;
    bytes Message = 2;
}

message HashResponse {
    string Hash = 1;
}

message KeyID {
    string Address = 1;
    repeated string KeyName = 2;
}

message ListResponse {
    repeated KeyID key = 1;
}

message AddNameRequest {
    string Keyname = 1;
    string Address = 2;
}

src:./errors.proto


syntax = "proto3";

package errors;

option go_package = "github.com/hyperledger/burrow/execution/errors";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

option (gogoproto.stable_marshaler_all) = true;
// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

message Exception {
    option (gogoproto.goproto_stringer) = false;
    uint32 Code = 1 [(gogoproto.casttype) = "Code"];
    string Exception = 2;
}

src:./rpc.proto


// Needed to proto2 rather than proto3 to get pointer field for PermArg
syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/rpc";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "tendermint.proto";
import "validator.proto";
import "bcm.proto";

package rpc;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message ResultStatus {
    string ChainID = 1;
    string RunID = 2;
    string BurrowVersion = 3;
    bytes GenesisHash = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    tendermint.NodeInfo NodeInfo = 5;
    bcm.SyncInfo SyncInfo = 6;
    // When catching up in fast sync
    bool CatchingUp = 8 [(gogoproto.jsontag) = ""];
    validator.Validator ValidatorInfo = 7;
}

src:./rpcevents.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/rpc/rpcevents";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "exec.proto";

package rpcevents;

// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;

//--------------------------------------------------
// Execution events
service ExecutionEvents {
    // Get StreamEvents (including transactions) for a range of block heights
    rpc Stream (BlocksRequest) returns (stream exec.StreamEvent);
    // Get a particular TxExecution by hash
    rpc Tx (TxRequest) returns (exec.TxExecution);
    // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block
    // are guaranteed to be delivered in each GetEventsResponse
    rpc Events (BlocksRequest) returns (stream EventsResponse);
}

message GetBlockRequest {
    // Height of block required
    uint64 Height = 1;
    // Whether to wait for the block to become available
    bool Wait = 2;
}

message TxRequest {
    // Height of block required
    bytes TxHash = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // Whether to wait for the block to become available
    bool Wait = 2;
}

message BlocksRequest {
    BlockRange BlockRange = 1;
    // Specify a query on which to match the tags of events.
    // Tag        | Match type | Values
    // -----------------------------------------
    //   All events
    // -----------------------------------------
    // TxType       | String     | "UnknownTx", "SendTx", "CallTx", "NameTx", "BondTx", "UnbondTx", "PermissionsTx", "GovernanceTx"
    // TxHash       | String     | bytes
    // EventType    | String     | "CallEvent", "LogEvent", "AccountInputEvent", "AccountOutputEvent"
    // EventID      | String     | string
    // Height       | Integer    | uint64
    // Index        | Integer    | uint64
    // MessageType  | String     | Go type name
    // -----------------------------------------
    //   Log event
    // -----------------------------------------
    // Address      | String     | Address (hex)
    // Log<0-4>     | String     | Word256 (hex)
    // Log<0-4>Text | String     | string (trimmed)
    // -----------------------------------------
    //   Call event
    // -----------------------------------------
    // Origin       | String     | Address (hex)
    // Callee       | String     | Address (hex)
    // Caller       | String     | Address (hex)
    // Value        | Integer    | uint64
    // Gas          | Integer    | uint64
    // StackDepth   | Integer    | uint64
    // Exception    | String     | string
    // -----------------------------------------
    //   Tx event (input/output)
    // -----------------------------------------
    // Exception  | String     | string
    //
    // For example:
    // EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF'
    string Query = 2;
}

message EventsResponse {
    uint64 Height = 1;
    repeated exec.Event Events = 2;
}

message GetTxsRequest {
    uint64 StartHeight = 1;
    uint64 EndHeight = 2;
    string Query = 3;
}

message GetTxsResponse {
    uint64 Height = 1;
    repeated exec.TxExecution TxExecutions = 2;
}

message Bound {
    BoundType Type = 1;
    uint64 Index = 2;
    enum BoundType {
        // Index is absolute index of an item
        ABSOLUTE = 0;
        // Index is an offset relative to last item
        RELATIVE = 1;
        // The first block
        FIRST = 2;
        // Ignore provided index and evaluate to latest index
        LATEST = 3;
        // Ignore provided index and stream new objects as they are generated
        STREAM = 4;
    }
}

// An inclusive range of blocks to include in output
message BlockRange {
    // Bounds can be set to:
    // absolute: block height
    // relative: block height counting back from latest
    // latest: latest block when call is processed
    // stream: for End keep sending new blocks, for start same as latest
    Bound Start = 1;
    Bound End = 2;
}


src:./bcm.proto


// Needed to proto2 rather than proto3 to get pointer field for PermArg
syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/bcm";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";

package bcm;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message SyncInfo {
    uint64 LatestBlockHeight = 1 [(gogoproto.jsontag) = ""];
    bytes LatestBlockHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    bytes LatestAppHash = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    // Timestamp of block as set by the block proposer
    google.protobuf.Timestamp LatestBlockTime = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
    // Time at which we committed the last block
    google.protobuf.Timestamp LatestBlockSeenTime = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
    // Time elapsed since last commit
    google.protobuf.Duration LatestBlockDuration = 6 [(gogoproto.nullable) = false, (gogoproto.stdduration) = true];
}

message PersistedState {
    bytes AppHashAfterLastBlock = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
    google.protobuf.Timestamp LastBlockTime = 2 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
    uint64 LastBlockHeight = 3;
    bytes GenesisHash = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false];
}

src:./spec.proto


syntax = 'proto3';

option go_package = "github.com/hyperledger/burrow/genesis/spec";

import "github.com/gogo/protobuf/gogoproto/gogo.proto";

import "crypto.proto";
import "balance.proto";

package spec;

option (gogoproto.stable_marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;

message TemplateAccount {
    option (gogoproto.goproto_sizecache) = false;
    option (gogoproto.goproto_unkeyed) = false;

    string Name = 1;
    bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""];
    crypto.PublicKey PublicKey = 3 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""];
    repeated balance.Balance Amounts = 4 [(gogoproto.nullable) = false, (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""];
    repeated string Permissions = 5 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""];
    repeated string Roles = 6 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""];
    bytes Code = 7 [(gogoproto.nullable) = true, (gogoproto.customtype) = "github.com/hyperledger/burrow/acm.Bytecode"];
}


HyperLedger Besu

TOC

Hyperledger Besu

實做完整的 Java 版節點與客戶端進入 Ethereum 生態圈,與慣見的以太坊節點與客戶端軟體較大差異在於文件中 How To 的兩個章節 Limit Access to Node 與 Use Privacy Features,以及出廠標配的監控 Prometheus 與 Grafana 設置。

執行檔 besu/pantheon

可參閱之前的 pegasyseng/pantheon

$ docker run -it --rm --entrypoint=bash pegasyseng/pantheon -c 'ls -al bin'
total 24
drwxr-xr-x 2 root root 4096 Aug  1 20:58 .
drwxr-xr-x 4 root root 4096 Aug  1 20:58 ..
-rwxr-xr-x 1 root root 9226 Aug  1 20:58 pantheon
-rwxr-xr-x 1 root root 3021 Aug  1 20:58 pantheon.bat

$ docker run -it --rm --entrypoint=bash pegasyseng/pantheon -c 'cat bin/pantheon'
#!/usr/bin/env sh

#
# Copyright 2015 the original author or authors.
#
# 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.
#

##############################################################################
##
##  pantheon start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/.." >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="pantheon"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and PANTHEON_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Dvertx.disableFileCPResolving=true" "-Dpantheon.home=$APP_HOME" "-Dlog4j.shutdownHookEnabled=false" "--add-opens" "java.base/sun.security.provider=ALL-UNNAMED"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    echo "$*"
}

die () {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

CLASSPATH=$APP_HOME/lib/pantheon-1.2.0.jar:$APP_HOME/lib/pantheon-1.2.0.jar:$APP_HOME/lib/pantheon-clique-1.2.0.jar:$APP_HOME/lib/pantheon-ibftlegacy-1.2.0.jar:$APP_HOME/lib/pantheon-ibft-1.2.0.jar:$APP_HOME/lib/pantheon-consensus-common-1.2.0.jar:$APP_HOME/lib/pantheon-json-rpc-1.2.0.jar:$APP_HOME/lib/pantheon-graphql-1.2.0.jar:$APP_HOME/lib/pantheon-blockcreation-1.2.0.jar:$APP_HOME/lib/pantheon-eth-1.2.0.jar:$APP_HOME/lib/pantheon-permissioning-1.2.0.jar:$APP_HOME/lib/pantheon-p2p-1.2.0.jar:$APP_HOME/lib/pantheon-core-1.2.0.jar:$APP_HOME/lib/pantheon-config-1.2.0.jar:$APP_HOME/lib/pantheon-trie-1.2.0.jar:$APP_HOME/lib/pantheon-crypto-1.2.0.jar:$APP_HOME/lib/enclave-1.2.0.jar:$APP_HOME/lib/pantheon-ethereum-rlp-1.2.0.jar:$APP_HOME/lib/pantheon-kvstore-1.2.0.jar:$APP_HOME/lib/pantheon-pipeline-1.2.0.jar:$APP_HOME/lib/pantheon-tasks-1.2.0.jar:$APP_HOME/lib/pantheon-metrics-rocksdb-1.2.0.jar:$APP_HOME/lib/services-util-1.2.0.jar:$APP_HOME/lib/pantheon-metrics-core-1.2.0.jar:$APP_HOME/lib/pantheon-nat-1.2.0.jar:$APP_HOME/lib/graphql-java-12.0.jar:$APP_HOME/lib/pantheon-util-1.2.0.jar:$APP_HOME/lib/guava-28.0-jre.jar:$APP_HOME/lib/picocli-3.9.6.jar:$APP_HOME/lib/vertx-web-3.7.1.jar:$APP_HOME/lib/vertx-auth-jwt-3.7.1.jar:$APP_HOME/lib/vertx-web-common-3.7.1.jar:$APP_HOME/lib/vertx-auth-common-3.7.1.jar:$APP_HOME/lib/vertx-jwt-3.7.1.jar:$APP_HOME/lib/vertx-core-3.7.1.jar:$APP_HOME/lib/cava-toml-0.5.0.jar:$APP_HOME/lib/log4j-slf4j-impl-2.12.0.jar:$APP_HOME/lib/log4j-core-2.12.0.jar:$APP_HOME/lib/log4j-api-2.12.0.jar:$APP_HOME/lib/spring-security-crypto-5.1.5.RELEASE.jar:$APP_HOME/lib/plugin-api-1.1.3.jar:$APP_HOME/lib/jackson-databind-2.9.9.1.jar:$APP_HOME/lib/bcprov-jdk15on-1.62.jar:$APP_HOME/lib/okhttp-3.14.2.jar:$APP_HOME/lib/simpleclient_pushgateway-0.6.0.jar:$APP_HOME/lib/simpleclient_common-0.6.0.jar:$APP_HOME/lib/simpleclient_hotspot-0.6.0.jar:$APP_HOME/lib/simpleclient-0.6.0.jar:$APP_HOME/lib/snappy-java-1.1.7.3.jar:$APP_HOME/lib/org.jupnp-2.5.2.jar:$APP_HOME/lib/org.jupnp.support-2.5.2.jar:$APP_HOME/lib/rocksdbjni-5.15.10.jar:$APP_HOME/lib/antlr4-runtime-4.7.2.jar:$APP_HOME/lib/slf4j-api-1.7.25.jar:$APP_HOME/lib/java-dataloader-2.1.1.jar:$APP_HOME/lib/reactive-streams-1.0.2.jar:$APP_HOME/lib/failureaccess-1.0.1.jar:$APP_HOME/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar:$APP_HOME/lib/jsr305-3.0.2.jar:$APP_HOME/lib/checker-qual-2.8.1.jar:$APP_HOME/lib/error_prone_annotations-2.3.2.jar:$APP_HOME/lib/j2objc-annotations-1.3.jar:$APP_HOME/lib/animal-sniffer-annotations-1.17.jar:$APP_HOME/lib/netty-handler-proxy-4.1.34.Final.jar:$APP_HOME/lib/netty-codec-http2-4.1.34.Final.jar:$APP_HOME/lib/netty-codec-http-4.1.34.Final.jar:$APP_HOME/lib/netty-handler-4.1.34.Final.jar:$APP_HOME/lib/netty-resolver-dns-4.1.34.Final.jar:$APP_HOME/lib/netty-codec-socks-4.1.34.Final.jar:$APP_HOME/lib/netty-codec-dns-4.1.34.Final.jar:$APP_HOME/lib/netty-codec-4.1.34.Final.jar:$APP_HOME/lib/netty-transport-4.1.34.Final.jar:$APP_HOME/lib/netty-buffer-4.1.34.Final.jar:$APP_HOME/lib/netty-resolver-4.1.34.Final.jar:$APP_HOME/lib/netty-common-4.1.34.Final.jar:$APP_HOME/lib/jackson-core-2.9.9.jar:$APP_HOME/lib/vertx-bridge-common-3.7.1.jar:$APP_HOME/lib/jackson-annotations-2.9.0.jar:$APP_HOME/lib/okio-1.17.2.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $PANTHEON_OPTS -classpath "\"$CLASSPATH\"" tech.pegasys.pantheon.Pantheon "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
  cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"

TODO

HyperLedger Avalon

Introducing Hyperledger Avalon – Hyperledger

There are a couple of key challenges with blockchain that probably don’t surprise any reader of this blog: scalability and confidentiality. One approach to both of these limitations is to perform some operations “off-chain.” In a traditional view of a blockchain, the data and validation logic for every transaction takes place on every node of the blockchain network or “on-chain.” It’s this redundancy and transparency that provides a network with its integrity but also comes at the cost of performance and confidentiality. By offloading some work, participants can trade off resiliency and integrity for performance and confidentiality. Of course, everyone wants to have their cake and eat it too, and so the use of the use of “trusted computing” is intended to maintain resiliency and integrity guarantees as much as possible while affording the additional performance and confidentiality. Trusted computing includes a variety of techniques to ensure that computation was done correctly and secretly. Hyperledger Avalon will realize these as different Worker types and include TEE (Trusted Execution Environments like Intel® SGX), MPC (multi-party compute), and ZK (zero-knowledge proofs).

Polkadot

TOC

United Networks of State Machines

Polkdot 官網的標語

Polkadot is a platform with low barriers to entry for flexible, autonomous economies acting together within Polkadot’s shared security umbrella. Polkadot is a revolution, not just in blockchain technology but also towards enabling fairer peer-to-peer digital jurisdictions.

tpl-state-machine-replication-v1.svg

Kusama Network

創建類似 kusama 需要更改的設定在 polkadot-service crate,主要是創世 kusama.json 與 chain_spec.rs。

Polkdot Parathreads

Parathreads - Polkadot Wiki

For some applications, being a parathread simply makes more sense than being a parachain. Namely, these are applications that do not have frequent state updates. Take a domain name service, for example. Read requests come in large numbers, but it would be normal to update the registry on an hourly basis. DNS has no need of Polkadot’s six-second block time. Oracles also make sense as parathreads, say a daily weather or Bitcoin block oracle.

寫入不高的應用如域名 DNS 與預言機 Oracle,成本類似現有 bitcoin, ethereum 的動態手續費,會隨著擁擠而拉高,這點與 Parachain 標租後進塊時間固定等同吃到飽不太一樣。

Polkdot Resources

Initial Parachain Offering (IPCO) ?

Preparing for Your First Parachain Auction - LongHash incubator - Medium

Libra

Facebook releases plan for its Libra cryptocurrency to 'meet the daily financial needs of billions of people' - The Block

"The challenge is that as of today we do not believe that there is a proven solution that can deliver the scale, stability, and security needed to support billions of people and transactions across the globe through a permissionless network," the whitepaper notes, conservatively quoting a throughput capacity of 1,000 transactions per second and a 10-second finality upon launch.

TOC

隨想

選 ProtoBuf 型正言順

引用 区块链安全问题剖析与 Libra 安全点评

单一性依赖问题:Libra 如果完全依赖 RUST 语言实现,那么会存在单一依赖问题,如果 RUST 语言出现安全问题,则会波及整个 Libra 系统,这一点可能需要时间来解决。

關於單一依賴的解決速度可能會比其他專案快一點,因 Libra 選型用的是 Google Protocol Buffers (Protobuf) 格式,從 immutability-io/vault-libra: A Vault plugin for Libra 專案出現的時間點可知整合這類已有 Protobuf 規格的專案相對時間會快上許多,除了格式一致讓 Golang 對接 Rust 應用程式較簡易之外,後續要 Java Python Nodejs 要對接或實作也會方便許多。

說到對接方便這件事除了開發,其實也牽涉到運轉處理事件的效率,如 The Site Reliability Workbook Chapter 2 - Implementing SLOs 建議初始的 SLOs Pipeline 管道區,管區裡會接多長與多少段其實開發階段並不一定清楚,平台運轉後遇到事件時可能會有動態的管路配置,如管裡流的是 Protobuf,對於處理事件的 SRE 來說一來上手容易二來工具也多,處理上更有效率。

tpl-sre-slos-v1.svg

就公鏈來說每個小型獨立節點一般無設置管路區的必要,有設置管路區需求的是較大型服務商,在收發訊息之間加上各種處理來提供服務。聯盟鏈來說對接的同盟可能都會配管,這時如遇到 hyperledger/fabric-protos 類似的專案,進管前處理與進管後的管道開發管理都會省下不少功夫,可提高整本帳的可靠度。

TODO

Move Token Example - etoken-libra

Protobuf

生成 Google Protocol Buffers 文件

libra/types/src/proto at master · libra/libra

git clone https://github.com/libra/libra.git /tmp/src/libra
bash tc.sh --gen-proto-doc /tmp/src/libra/types/src/proto /tmp/output.md

Protobuf Doc 2019-09-11T17:25:25+08:00

Table of Contents

Top

transaction.proto

AccountState

Account state as a whole. After execution, updates to accounts are passed in this form to storage for persistence.

FieldTypeLabelDescription
addressbytesAccount address
blobbytesAccount state blob

SignedTransaction

A generic structure that represents signed RawTransaction

FieldTypeLabelDescription
signed_txnbytesLCS byte code representation of a SignedTransaction

SignedTransactionWithProof

FieldTypeLabelDescription
versionuint64The version of the returned signed transaction.
signed_transactionSignedTransactionThe transaction itself.
proofSignedTransactionProofThe proof authenticating the signed transaction.
eventsEventsListThe events yielded by executing the transaction, if requested.

SignedTransactionsBlock

A generic structure that represents a block of transactions originated from a particular validator instance.

FieldTypeLabelDescription
transactionsSignedTransactionrepeatedSet of Signed Transactions
validator_public_keybytesPublic key of the validator that created this block
validator_signaturebytesSignature of the validator that created this block

TransactionArgument

An argument to the transaction if the transaction takes arguments

TransactionListWithProof

A list of consecutive transactions with proof. This is mainly used for state synchronization when a validator would request a list of transactions from a peer, verify the proof, execute the transactions and persist them. Note that the transactions are supposed to belong to the same epoch E, otherwise verification will fail.

FieldTypeLabelDescription
transactionsSignedTransactionrepeatedThe list of transactions.
infosTransactionInforepeatedThe list of corresponding TransactionInfo objects.
events_for_versionsEventsForVersionsThe list of corresponding Event objects (only present if fetch_events was set to true in req)
first_transaction_versiongoogle.protobuf.UInt64ValueIf the list is not empty, the version of the first transaction.
proof_of_first_transactionAccumulatorProofThe proofs of the first and last transaction in this chunk. When this is used for state synchronization, the validator who requests the transactions will provide a version in the request and the proofs will be relative to the given version. When this is returned in GetTransactionsResponse, the proofs will be relative to the ledger info returned in UpdateToLatestLedgerResponse.
proof_of_last_transactionAccumulatorProof

TransactionToCommit

Transaction struct to commit to storage

FieldTypeLabelDescription
signed_txnSignedTransactionThe signed transaction which was executed
account_statesAccountStaterepeatedState db updates
eventsEventrepeatedEvents yielded by the transaction.
gas_useduint64The amount of gas used.

TransactionArgument.ArgType

NameNumberDescription
U640
ADDRESS1
STRING2
BYTEARRAY3

Top

transaction_info.proto

TransactionInfo

TransactionInfo is the object we store in the transaction accumulator. It consists of the transaction as well as the execution result of this transaction. This are later returned to the client so that a client can validate the tree

FieldTypeLabelDescription
signed_transaction_hashbytesHash of the signed transaction that is stored
state_root_hashbytesThe root hash of Sparse Merkle Tree describing the world state at the end of this transaction
event_root_hashbytesThe root hash of Merkle Accumulator storing all events emitted during this transaction.
gas_useduint64The amount of gas used by this transaction.

Top

account_state_blob.proto

AccountStateBlob

FieldTypeLabelDescription
blobbytes

AccountStateWithProof

FieldTypeLabelDescription
versionuint64
blobAccountStateBlob
proofAccountStateProof

Top

events.proto

Event

An event emitted from a smart contract

FieldTypeLabelDescription
keybytes
sequence_numberuint64
event_databytes

EventWithProof

An event along with the proof for the event

FieldTypeLabelDescription
transaction_versionuint64
event_indexuint64
eventEvent
proofEventProof

EventsForVersions

A list of EventList's, each representing all events for a transaction.

FieldTypeLabelDescription
events_for_versionEventsListrepeated

EventsList

A list of events.

FieldTypeLabelDescription
eventsEventrepeated

Top

validator_public_keys.proto

ValidatorPublicKeys

Protobuf definition for the Rust struct ValidatorPublicKeys

FieldTypeLabelDescription
account_addressbytesValidator account address
consensus_public_keybytesConsensus public key
network_signing_public_keybytesNetwork signing publick key
network_identity_public_keybytesNetwork identity publick key

Top

vm_errors.proto

VMStatus

The statuses and errors produced by the VM can be categorized into a couple different types:

  1. Validation Statuses: all the errors that can (/should) be the result of executing the prologue -- these are primarily used by the vm validator and AC.
  2. Verification Errors: errors that are the result of performing bytecode verification (happens at the time of publishing).
  3. VM Invariant Errors: errors that arise from an internal invariant of the VM being violated. These signify a problem with either the VM or bytecode verifier.
  4. Binary Errors: errors that can occur during the process of deserialization of a transaction.
  5. Runtime Statuses: errors that can arise from the execution of a transaction (assuming the prologue executes without error). These are errors that can occur during execution due to things such as division by zero, running out of gas, etc. These do not signify an issue with the VM.
FieldTypeLabelDescription
major_statusuint64e.g. assertion violation, out of gas
has_sub_statusboolAny substatus code. e.g. assertion error number
sub_statusuint64
has_messagebool
messagestring

Top

validator_change.proto

ValidatorChangeEventWithProof

This is used to prove validator changes. When a validator is changing, it triggers an event on /validator_change_account/events/sent. To tell the client about validator changes, we query /validator_change_account/events/sent to get all versions that contain validator changes after the version that we are trying to update from. For each of these versions, the old validator set would have signed the ledger info at that version. The client needs this as well as the event results + proof. The client can then verify that these events were under the current tree and that the changes were signed by the old validators (and that the events correctly show which validators are the new validators).

This message represents a single validator change event and the proof that corresponds to it

FieldTypeLabelDescription
ledger_info_with_sigsLedgerInfoWithSignatures
event_with_proofEventWithProof

Top

language_storage.proto

ModuleId

The unique identifier for a module on the chain.

FieldTypeLabelDescription
addressbytes
namestring

Top

validator_set.proto

ValidatorSet

Protobuf definition for the Rust struct ValidatorSet.

FieldTypeLabelDescription
validator_public_keysValidatorPublicKeysrepeated

Top

ledger_info.proto

LedgerInfo

Even though we don't always need all hashes, we pass them in and return them / always so that we keep them in sync on the client and don't make the client / worry about which one(s) to pass in which cases / / This structure serves a dual purpose. / / First, if this structure is signed by 2f+1 validators it signifies the state / of the ledger at version version -- it contains the transaction / accumulator at that version which commits to all historical transactions. / This structure may be expanded to include other information that is derived / from that accumulator (e.g. the current time according to the time contract) / to reduce the number of proofs a client must get. / / Second, the structure contains a consensus_data_hash value. This is the / hash of an internal data structure that represents a block that is voted on / by consensus. / / Combining these two concepts when the consensus algorithm votes on a block B / it votes for a LedgerInfo with the version being the latest version that / will be committed if B gets 2f+1 votes. It sets consensus_data_hash to / represent B so that if those 2f+1 votes are gathered, the block is valid to / commit

FieldTypeLabelDescription
versionuint64Current latest version of the system
transaction_accumulator_hashbytesRoot hash of transaction accumulator at this version
consensus_data_hashbytesHash of consensus-specific data that is opaque to all parts of the system other than consensus. This is needed to verify signatures because consensus signing includes this hash
consensus_block_idbytesThe block id of the last committed block corresponding to this ledger info. This field is not particularly interesting to the clients, but can be used by the validators for synchronization.
epoch_numuint64Epoch number corresponds to the set of validators that are active for this ledger info. The main motivation for keeping the epoch number in the LedgerInfo is to ensure that the client has enough information to verify that the signatures for this info are coming from the validators that indeed form a quorum. Without epoch number a potential attack could reuse the signatures from the validators in one epoch in order to sign the wrong info belonging to another epoch, in which these validators do not form a quorum. The very first epoch number is 0.
timestamp_usecsuint64Timestamp that represents the microseconds since the epoch (unix time) that is generated by the proposer of the block. This is strictly increasing with every block. If a client reads a timestamp > the one they specified for transaction expiration time, they can be certain that their transaction will never be included in a block in the future (assuming that their transaction has not yet been included)
next_validator_setValidatorSetAn optional field with the validator set for the next epoch in case it's the last ledger info in the current epoch.

LedgerInfoWithSignatures

The validator node returns this structure which includes signatures / from each validator to confirm the state. The client needs to only pass / back the LedgerInfo element since the validator node doesn't need to know / the signatures again when the client performs a query, those are only there / for the client to be able to verify the state

FieldTypeLabelDescription
signaturesValidatorSignaturerepeatedSignatures of the root node from each validator
ledger_infoLedgerInfo

ValidatorSignature

FieldTypeLabelDescription
validator_idbytesThe account address of the validator, which can be used for retrieving its public key during the given epoch.
signaturebytes

Top

proof.proto

AccountStateProof

The complete proof used to authenticate an account state.

FieldTypeLabelDescription
ledger_info_to_transaction_info_proofAccumulatorProof
transaction_infoTransactionInfo
transaction_info_to_account_proofSparseMerkleProof

AccumulatorConsistencyProof

FieldTypeLabelDescription
frozen_subtree_rootsbytesrepeatedThe root hashes of the frozen subtrees that form the small accumulator. Note that none of these hashes should be default hash.
num_siblingsuint32The total number of siblings.
non_default_siblingsbytesrepeatedThe non-default siblings. Note that the entire list of siblings always start of zero or more non-default siblings, followed by zero of more default siblings. So given the total number of siblings and the non-default siblings we should be able to construct the entire sibling list.

AccumulatorProof

FieldTypeLabelDescription
bitmapuint64The bitmap indicating which siblings are default. 1 means non-default and 0 means default. The LSB corresponds to the sibling at the bottom of the accumulator. The leftmost 1-bit corresponds to the sibling at the level just below root level in the accumulator, since this one is always non-default.
non_default_siblingsbytesrepeatedThe non-default siblings. The ones near the root are at the beginning of the list.

EventProof

The complete proof used to authenticate an event.

FieldTypeLabelDescription
ledger_info_to_transaction_info_proofAccumulatorProof
transaction_infoTransactionInfo
transaction_info_to_event_proofAccumulatorProof

SignedTransactionProof

The complete proof used to authenticate a signed transaction.

FieldTypeLabelDescription
ledger_info_to_transaction_info_proofAccumulatorProof
transaction_infoTransactionInfo

SparseMerkleProof

FieldTypeLabelDescription
leafbytesThis proof can be used to authenticate whether a given leaf exists in the tree or not. In Rust: - If this is Some(HashValue, HashValue) - If the first HashValue equals requested key, this is an inclusion proof and the second HashValue equals the hash of the corresponding account blob. - Otherwise this is a non-inclusion proof. The first HashValue is the only key that exists in the subtree and the second HashValue equals the hash of the corresponding account blob. - If this is None, this is also a non-inclusion proof which indicates the subtree is empty.

In protobuf, this leaf field should either be - empty, which corresponds to None in the Rust structure. - exactly 64 bytes, which corresponds to Some<(HashValue, HashValue)> in the Rust structure. | | bitmap | bytes | | The bitmap indicating which siblings are default. 1 means non-default and 0 means default. The MSB of the first byte corresponds to the sibling at the top of the Sparse Merkle Tree. The rightmost 1-bit of the last byte corresponds to the sibling at the bottom, since this one is always non-default. | | non_default_siblings | bytes | repeated | The non-default siblings. The ones near the root are at the beginning of the list. |

Top

get_with_proof.proto

How to verify the response as a client: (Note that every response comes in the form of GetWithProofResponse which wraps the inner response elements that correspond to the specific request types. Below we will assume a single request/response type. The verification can be extended as needed for multiple types. Also note that we will use the following notation: resp = GetWithProofResponse and req = GetWithProofRequest). Also note that the following will be considered equivalent for brevity: req.requested_items.get_account_state_request == req.get_account_state_request And, resp.values.get_account_state_response == resp.get_account_state_response

GetAccountStateResponse:

  • let state_req = req.requested_items.get_account_state_request;
  • let state_resp = resp.values.get_account_state_response;
  • Verify that:
    • state_req.access_path == state_resp.access_path
      • This ensures that the server is responding with the correct access path
  • let state_data_hash = Hash(state_resp.value);
  • let state_proof = resp.values.proof.state_proof_value.sparse_merkle_proof;
  • Validate state_proof using state_data_hash as the leaf
    • When verifying the state tree, use: state_root_hash = resp.values.transaction_info.state_root_hash
  • Validate accumulator using resp.values.transaction_info as the leaf
    • When verifying the accumulator, use: root_hash = resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
  • Validate that the transaction root hash submitted in req.known_value.node_value.txn_root_hash exists in the proof for accumulator and that the proof is valid with this hash
  • Validate ledger info
    • let ledger_info_hash = Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
    • Verify signatures from resp.ledger_info_with_sigs.signatures are signing ledger_info_hash and that there are >2/3 nodes signing this correctly
    • Validate that the timestamp is relatively recent in resp.ledger_info_with_sigs.ledger_info.timestamp

GetAccountTransactionBySequenceNumberResponse:

  • Note that other than type completed_transaction, there will be no proof returned since the transaction has not yet been committed. To ensure that a validator is telling the truth about it not being committed yet, a client should query for their account state and verify that their current sequence number is less than what they are searching for with GetAccountTransactionBySequenceNumberResponse
  • let txn = resp.get_account_transaction_by_sequence_number_response.transaction.committed_transaction;
  • let txn_hash = Hash(txn);
  • Verify that resp.proof.transaction_info.signed_transaction_hash == txn_hash
  • Validate accumulator using resp.proof.transaction_info as the leaf
    • When verifying the accumulator, use: root_hash = resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
  • Validate that the transaction root hash submitted in req.known_value.node_value.txn_root_hash exists in the proof for accumulator and that the proof is valid with this hash
  • Validate ledger info
    • let ledger_info_hash = Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
    • Verify signatures from resp.ledger_info_with_sigs.signatures are signing ledger_info_hash and that there are >2/3 nodes signing this correctly
    • Validate that the timestamp is relatively recent in resp.ledger_info_with_sigs.ledger_info.timestamp

GetTransactionsResponse:

  • for txn in resp.get_transactions_response.transactions:
    • let txn = txn.committed_transaction;
    • let txn_hash = Hash(txn);
    • Verify that txn.proof.transaction_info.signed_transaction_hash == txn_hash
    • Validate accumulator using txn.proof.transaction_info as the leaf
    • When verifying the accumulator, use: root_hash = resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
    • Verify that transactions are sequential and none are missing
  • Validate ledger info
    • let ledger_info_hash = Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
    • Verify signatures from resp.ledger_info_with_sigs.signatures are signing ledger_info_hash and that there are >2/3 nodes signing this correctly
    • Validate that the timestamp is relatively recent in resp.ledger_info_with_sigs.ledger_info.timestamp
  • If the number of transactions returned is less than limit for an ascending query or if the requested offset > current version for a descending query, the client should verify that the timestamp in ledger info is relatively recent to determine if it is likely that all transactions available were returned

GetAccountStateRequest

Gets latest state for an account.

FieldTypeLabelDescription
addressbytesAccount for which we are fetching the state.

GetAccountStateResponse

State information returned by a get account state query.

FieldTypeLabelDescription
account_state_with_proofAccountStateWithProofBlob value representing the account state together with proof the client can utilize to verify it.

GetAccountTransactionBySequenceNumberRequest


---------------- Get single transaction by account + sequence number

Get transactions that altered an account - this includes both sent and received. A user of this should check that the data returned matches what they expect. As an example, a potential attack vector would be something like the following: Alice is buying an apple from Bob. Alice's phone signs a transaction X with sequence number N that pays coins to Bob. Alice transmits this signature to Bob's payment terminal which then submits the transaction and checks its status to see if Alice can be given the apple. However, as Bob is doing this Alice constructs a second transaction X' also with sequence number N. Alice gets that transaction inserted in the blockchain. If Bob isn't thoughtful about how he uses this API he may assume that if he asks for the N'th transaction on Alice's account that when the API returns that this means the transaction has gone through. The point here is that one should be careful in reading too much into "transaction X is on the chain" and focus on the logs, which tell you what the transaction did.

If a client submitted a transaction, they should also verify that the hash of the returned transaction matches what they submitted. As an example, if a client has two wallets that share the same account, they may both submit a transaction at the same sequence number and only one will be committed. A client should never assume that if they receive the response that this transaction was included that it means that this is definitely the transaction that was submitted. They should check that the hash matches what they sent

FieldTypeLabelDescription
accountbytesAccount for which to query transactions
sequence_numberuint64
fetch_eventsboolSet to true to fetch events for the transaction at this version

GetAccountTransactionBySequenceNumberResponse

Transaction information for transactions requested by GetAccountTransactionsRequest

FieldTypeLabelDescription
signed_transaction_with_proofSignedTransactionWithProofWhen the transaction requested is committed, return the committed transaction with proof.
proof_of_current_sequence_numberAccountStateWithProofWhen the transaction requested is not committed, we give a proof that shows the current sequence number is smaller than what would have been if the transaction was committed.

GetEventsByEventAccessPathRequest

Get events that exist on an event access path. In the current world, a user may specify events that were received, events that were sent, or any event that modifies their account

FieldTypeLabelDescription
access_pathAccessPath
start_event_seq_numuint64The sequence number of the event to start with for this query. Use a sequence number of MAX_INT to represent the latest.
ascendingboolIf ascending is true this query will return up to limit events that were emitted after start_event_seq_num. Otherwise it will return up to limit events before the offset. Both cases are inclusive.
limituint64Limit number of results

GetEventsByEventAccessPathResponse

FieldTypeLabelDescription
events_with_proofEventWithProofrepeatedReturns an event and proof of each of the events in the request. The first element of proofs will be the closest to start_event_seq_num.
proof_of_latest_eventAccountStateWithProofIf the number of events returned is less than limit for an ascending query or if start_event_seq_num > the latest seq_num for a descending query, returns the state of the account containing the given access path in the latest state. This allows the client to verify that there are in fact no extra events.

The LedgerInfoWithSignatures which is on the main UpdateToLatestLedgerResponse can be used to validate this. |

GetTransactionsRequest

Get up to limit transactions starting from start_version.

FieldTypeLabelDescription
start_versionuint64The version of the transaction to start with for this query. Use a version of MAX_INT to represent the latest.
limituint64Limit number of results
fetch_eventsboolSet to true to fetch events for the transaction at each version

GetTransactionsResponse

FieldTypeLabelDescription
txn_list_with_proofTransactionListWithProof

RequestItem

FieldTypeLabelDescription
get_account_state_requestGetAccountStateRequest
get_account_transaction_by_sequence_number_requestGetAccountTransactionBySequenceNumberRequest
get_events_by_event_access_path_requestGetEventsByEventAccessPathRequest
get_transactions_requestGetTransactionsRequest

ResponseItem

Individual response items to the queries posed by the requests

FieldTypeLabelDescription
get_account_state_responseGetAccountStateResponse
get_account_transaction_by_sequence_number_responseGetAccountTransactionBySequenceNumberResponse
get_events_by_event_access_path_responseGetEventsByEventAccessPathResponse
get_transactions_responseGetTransactionsResponse

UpdateToLatestLedgerRequest

This API is used to update the client to the latest ledger version and optionally also request 1..n other pieces of data. This allows for batch queries. All queries return proofs that a client should check to validate the data.

Note that if a client only wishes to update to the latest LedgerInfo and receive the proof that this latest ledger extends the client_known_version ledger the client had, they can simply set the requested_items to an empty list.

FieldTypeLabelDescription
client_known_versionuint64This is the version the client already trusts. Usually the client should set this to the version it obtained the last time it synced with the chain. If this is the first time ever the client sends a request, it must use the waypoint hard-coded in its software.
requested_itemsRequestItemrepeatedThe items for which we are requesting data in this API call.

UpdateToLatestLedgerResponse

Response from getting latest ledger

FieldTypeLabelDescription
response_itemsResponseItemrepeatedResponses to the queries posed by the requests. The proofs generated will be relative to the version of the latest ledger provided below.
ledger_info_with_sigsLedgerInfoWithSignaturesThe latest ledger info this node has. It will come with at least 2f+1 validator signatures as well as a proof that shows the latest ledger extends the old ledger the client had.
validator_change_eventsValidatorChangeEventWithProofrepeatedValidator change events from what the client last knew. This is used to inform the client of validator changes from the client's last known version until the current version

Top

access_path.proto

AccessPath

FieldTypeLabelDescription
addressbytes
pathbytes

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── access_path.proto
├── account_state_blob.proto
├── events.proto
├── get_with_proof.proto
├── language_storage.proto
├── ledger_info.proto
├── proof.proto
├── transaction_info.proto
├── transaction.proto
├── validator_change.proto
├── validator_public_keys.proto
├── validator_set.proto
└── vm_errors.proto

0 directories, 13 files

Protobuf sources

src:./transaction.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "access_path.proto";
import "events.proto";
import "proof.proto";
import "transaction_info.proto";
import "google/protobuf/wrappers.proto";

// An argument to the transaction if the transaction takes arguments
message TransactionArgument {
    enum ArgType {
        U64 = 0;
        ADDRESS = 1;
        STRING = 2;
        BYTEARRAY = 3;
    }
}

// A generic structure that represents signed RawTransaction
message SignedTransaction {
    // LCS byte code representation of a SignedTransaction
    bytes signed_txn = 5;
}

message SignedTransactionWithProof {
    // The version of the returned signed transaction.
    uint64 version = 1;

    // The transaction itself.
    SignedTransaction signed_transaction = 2;

    // The proof authenticating the signed transaction.
    SignedTransactionProof proof = 3;

    // The events yielded by executing the transaction, if requested.
    EventsList events = 4;
}

// A generic structure that represents a block of transactions originated from a
// particular validator instance.
message SignedTransactionsBlock {
    // Set of Signed Transactions
    repeated SignedTransaction transactions = 1;
    // Public key of the validator that created this block
    bytes validator_public_key = 2;
    // Signature of the validator that created this block
    bytes validator_signature = 3;
}

// Account state as a whole.
// After execution, updates to accounts are passed in this form to storage for
// persistence.
message AccountState {
    // Account address
    bytes address = 1;
    // Account state blob
    bytes blob = 2;
}

// Transaction struct to commit to storage
message TransactionToCommit {
    // The signed transaction which was executed
    SignedTransaction signed_txn = 1;
    // State db updates
    repeated AccountState account_states = 2;
    // Events yielded by the transaction.
    repeated Event events = 3;
    // The amount of gas used.
    uint64 gas_used = 4;
}

// A list of consecutive transactions with proof. This is mainly used for state
// synchronization when a validator would request a list of transactions from a
// peer, verify the proof, execute the transactions and persist them. Note that
// the transactions are supposed to belong to the same epoch E, otherwise
// verification will fail.
message TransactionListWithProof {
    // The list of transactions.
    repeated SignedTransaction transactions = 1;

    // The list of corresponding TransactionInfo objects.
    repeated TransactionInfo infos = 2;

    // The list of corresponding Event objects (only present if fetch_events was set to true in req)
    EventsForVersions events_for_versions = 3;

    // If the list is not empty, the version of the first transaction.
    google.protobuf.UInt64Value first_transaction_version = 4;

    // The proofs of the first and last transaction in this chunk. When this is
    // used for state synchronization, the validator who requests the transactions
    // will provide a version in the request and the proofs will be relative to
    // the given version. When this is returned in GetTransactionsResponse, the
    // proofs will be relative to the ledger info returned in
    // UpdateToLatestLedgerResponse.
    AccumulatorProof proof_of_first_transaction = 5;
    AccumulatorProof proof_of_last_transaction = 6;
}

src:./transaction_info.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

// `TransactionInfo` is the object we store in the transaction accumulator. It
// consists of the transaction as well as the execution result of this
// transaction. This are later returned to the client so that a client can
// validate the tree
message TransactionInfo {
  // Hash of the signed transaction that is stored
  bytes signed_transaction_hash = 1;

  // The root hash of Sparse Merkle Tree describing the world state at the end
  // of this transaction
  bytes state_root_hash = 2;

  // The root hash of Merkle Accumulator storing all events emitted during this
  // transaction.
  bytes event_root_hash = 3;

  // The amount of gas used by this transaction.
  uint64 gas_used = 4;
}

src:./account_state_blob.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "proof.proto";

message AccountStateBlob { bytes blob = 1; }

message AccountStateWithProof {
  uint64 version = 1;
  AccountStateBlob blob = 2;
  AccountStateProof proof = 3;
}

src:./events.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

// This file contains proto definitions related to events.  Events are emitted
// by smart contract execution.  These could include events such as received
// transactions, sent transactions, etc.

syntax = "proto3";

package types;

import "access_path.proto";
import "proof.proto";

// An event emitted from a smart contract
message Event {
    bytes key = 1;
    uint64 sequence_number = 2;
    bytes event_data = 3;
}

// An event along with the proof for the event
message EventWithProof {
  uint64 transaction_version = 1;
  uint64 event_index = 2;
  Event event = 3;
  EventProof proof = 4;
}

// A list of events.
message EventsList {
  repeated Event events = 1;
}

// A list of EventList's, each representing all events for a transaction.
message EventsForVersions {
    repeated EventsList events_for_version = 1;
}

src:./validator_public_keys.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

// Protobuf definition for the Rust struct ValidatorPublicKeys
message ValidatorPublicKeys {
  // Validator account address
  bytes account_address = 1;
  // Consensus public key
  bytes consensus_public_key = 2;
  // Network signing publick key
  bytes network_signing_public_key = 3;
  /// Network identity publick key
  bytes network_identity_public_key = 4;
}

src:./vm_errors.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "language_storage.proto";

// The statuses and errors produced by the VM can be categorized into a
// couple different types:
// 1. Validation Statuses: all the errors that can (/should) be
//    the result of executing the prologue -- these are primarily used by
//    the vm validator and AC.
// 2. Verification Errors: errors that are the result of performing
//    bytecode verification (happens at the time of publishing).
// 3. VM Invariant Errors: errors that arise from an internal invariant of
//    the VM being violated. These signify a problem with either the VM or
//    bytecode verifier.
// 4. Binary Errors: errors that can occur during the process of
//    deserialization of a transaction.
// 5. Runtime Statuses: errors that can arise from the execution of a
//    transaction (assuming the prologue executes without error). These are
//    errors that can occur during execution due to things such as division
//    by zero, running out of gas, etc. These do not signify an issue with
//    the VM.
message VMStatus {
    // e.g. assertion violation, out of gas
    uint64 major_status = 1;
    // Any substatus code. e.g. assertion error number
    bool has_sub_status = 2;
    uint64 sub_status = 3;
    bool has_message = 4;
    string message = 5;
}

src:./validator_change.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "events.proto";
import "ledger_info.proto";

// This is used to prove validator changes.  When a validator is changing, it
// triggers an event on /validator_change_account/events/sent.  To tell the
// client about validator changes, we query
// /validator_change_account/events/sent to get all versions that contain
// validator changes after the version that we are trying to update from. For
// each of these versions, the old validator set would have signed the ledger
// info at that version.  The client needs this as well as the event results +
// proof.  The client can then verify that these events were under the current
// tree and that the changes were signed by the old validators (and that the
// events correctly show which validators are the new validators).
//
// This message represents a single validator change event and the proof that
// corresponds to it
message ValidatorChangeEventWithProof {
  LedgerInfoWithSignatures ledger_info_with_sigs = 1;
  EventWithProof event_with_proof = 2;
}

src:./language_storage.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

/// The unique identifier for a module on the chain.
message ModuleId {
    bytes address = 1;
    string name = 2;
}

src:./validator_set.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "validator_public_keys.proto";

// Protobuf definition for the Rust struct ValidatorSet.
message ValidatorSet {
  repeated ValidatorPublicKeys validator_public_keys = 1;
}

src:./ledger_info.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "validator_set.proto";

/// Even though we don't always need all hashes, we pass them in and return them
/// always so that we keep them in sync on the client and don't make the client
/// worry about which one(s) to pass in which cases
///
/// This structure serves a dual purpose.
///
/// First, if this structure is signed by 2f+1 validators it signifies the state
/// of the ledger at version `version` -- it contains the transaction
/// accumulator at that version which commits to all historical transactions.
/// This structure may be expanded to include other information that is derived
/// from that accumulator (e.g. the current time according to the time contract)
/// to reduce the number of proofs a client must get.
///
/// Second, the structure contains a `consensus_data_hash` value. This is the
/// hash of an internal data structure that represents a block that is voted on
/// by consensus.
///
/// Combining these two concepts when the consensus algorithm votes on a block B
/// it votes for a LedgerInfo with the `version` being the latest version that
/// will be committed if B gets 2f+1 votes. It sets `consensus_data_hash` to
/// represent B so that if those 2f+1 votes are gathered, the block is valid to
/// commit
message LedgerInfo {
  // Current latest version of the system
  uint64 version = 1;

  // Root hash of transaction accumulator at this version
  bytes transaction_accumulator_hash = 2;

  // Hash of consensus-specific data that is opaque to all parts of the system
  // other than consensus.  This is needed to verify signatures because
  // consensus signing includes this hash
  bytes consensus_data_hash = 3;

  // The block id of the last committed block corresponding to this ledger info.
  // This field is not particularly interesting to the clients, but can be used
  // by the validators for synchronization.
  bytes consensus_block_id = 4;

  // Epoch number corresponds to the set of validators that are active for this
  // ledger info. The main motivation for keeping the epoch number in the
  // LedgerInfo is to ensure that the client has enough information to verify
  // that the signatures for this info are coming from the validators that
  // indeed form a quorum. Without epoch number a potential attack could reuse
  // the signatures from the validators in one epoch in order to sign the wrong
  // info belonging to another epoch, in which these validators do not form a
  // quorum. The very first epoch number is 0.
  uint64 epoch_num = 5;

  // Timestamp that represents the microseconds since the epoch (unix time) that is
  // generated by the proposer of the block.  This is strictly increasing with every block.
  // If a client reads a timestamp > the one they specified for transaction expiration time,
  // they can be certain that their transaction will never be included in a block in the future
  // (assuming that their transaction has not yet been included)
  uint64 timestamp_usecs = 6;

  // An optional field with the validator set for the next epoch in case it's the last
  // ledger info in the current epoch.
  ValidatorSet next_validator_set = 7;
}

/// The validator node returns this structure which includes signatures
/// from each validator to confirm the state.  The client needs to only pass
/// back the LedgerInfo element since the validator node doesn't need to know
/// the signatures again when the client performs a query, those are only there
/// for the client to be able to verify the state
message LedgerInfoWithSignatures {
  // Signatures of the root node from each validator
  repeated ValidatorSignature signatures = 1;

  LedgerInfo ledger_info = 2;
}

message ValidatorSignature {
  // The account address of the validator, which can be used for retrieving its
  // public key during the given epoch.
  bytes validator_id = 1;
  bytes signature = 2;
}

src:./proof.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

import "transaction_info.proto";

message AccumulatorProof {
  // The bitmap indicating which siblings are default. 1 means non-default and
  // 0 means default. The LSB corresponds to the sibling at the bottom of the
  // accumulator. The leftmost 1-bit corresponds to the sibling at the level
  // just below root level in the accumulator, since this one is always
  // non-default.
  uint64 bitmap = 1;

  // The non-default siblings. The ones near the root are at the beginning of
  // the list.
  repeated bytes non_default_siblings = 2;
}

message SparseMerkleProof {
  // This proof can be used to authenticate whether a given leaf exists in the
  // tree or not. In Rust:
  //   - If this is `Some(HashValue, HashValue)`
  //     - If the first `HashValue` equals requested key, this is an inclusion
  //       proof and the second `HashValue` equals the hash of the
  //       corresponding account blob.
  //     - Otherwise this is a non-inclusion proof. The first `HashValue` is
  //       the only key that exists in the subtree and the second `HashValue`
  //       equals the hash of the corresponding account blob.
  //   - If this is `None`, this is also a non-inclusion proof which indicates
  //     the subtree is empty.
  //
  // In protobuf, this leaf field should either be
  //   - empty, which corresponds to None in the Rust structure.
  //   - exactly 64 bytes, which corresponds to Some<(HashValue, HashValue)>
  //     in the Rust structure.
  bytes leaf = 1;

  // The bitmap indicating which siblings are default. 1 means non-default and
  // 0 means default. The MSB of the first byte corresponds to the sibling at
  // the top of the Sparse Merkle Tree. The rightmost 1-bit of the last byte
  // corresponds to the sibling at the bottom, since this one is always
  // non-default.
  bytes bitmap = 2;

  // The non-default siblings. The ones near the root are at the beginning of
  // the list.
  repeated bytes non_default_siblings = 3;
}

message AccumulatorConsistencyProof {
  // The root hashes of the frozen subtrees that form the small accumulator.
  // Note that none of these hashes should be default hash.
  repeated bytes frozen_subtree_roots = 1;

  // The total number of siblings.
  uint32 num_siblings = 2;

  // The non-default siblings. Note that the entire list of siblings always
  // start of zero or more non-default siblings, followed by zero of more
  // default siblings. So given the total number of siblings and the non-default
  // siblings we should be able to construct the entire sibling list.
  repeated bytes non_default_siblings = 3;
}

// The complete proof used to authenticate a signed transaction.
message SignedTransactionProof {
  AccumulatorProof ledger_info_to_transaction_info_proof = 1;
  TransactionInfo transaction_info = 2;
}

// The complete proof used to authenticate an account state.
message AccountStateProof {
  AccumulatorProof ledger_info_to_transaction_info_proof = 1;
  TransactionInfo transaction_info = 2;
  SparseMerkleProof transaction_info_to_account_proof = 3;
}

// The complete proof used to authenticate an event.
message EventProof {
  AccumulatorProof ledger_info_to_transaction_info_proof = 1;
  TransactionInfo transaction_info = 2;
  AccumulatorProof transaction_info_to_event_proof = 3;
}

src:./get_with_proof.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

// This file contains proto definitions for performing queries and getting back
// results with proofs.  This is the interface for a client to query data from
// the system. Every query result must include proof so that a client can be
// certain that the data returned is valid.  A client must verify this proof to
// ensure that a node isn't lying to them.

// How to verify the response as a client:
// (Note that every response comes in the form of GetWithProofResponse which
// wraps the inner response elements that correspond to the specific request
// types.  Below we will assume a single request/response type.  The
// verification can be extended as needed for multiple types. Also note that we
// will use the following notation: resp = GetWithProofResponse and req =
// GetWithProofRequest). Also note that the following will be considered
// equivalent for brevity: req.requested_items.get_account_state_request ==
// req.get_account_state_request And, resp.values.get_account_state_response ==
// resp.get_account_state_response
//
// GetAccountStateResponse:
// - let state_req = req.requested_items.get_account_state_request;
// - let state_resp = resp.values.get_account_state_response;
// - Verify that:
//      - state_req.access_path == state_resp.access_path
//          - This ensures that the server is responding with the correct access
//          path
// - let state_data_hash = Hash(state_resp.value);
// - let state_proof = resp.values.proof.state_proof_value.sparse_merkle_proof;
// - Validate state_proof using state_data_hash as the leaf
//      - When verifying the state tree, use:
//          state_root_hash = resp.values.transaction_info.state_root_hash
// - Validate accumulator using resp.values.transaction_info as the leaf
//      - When verifying the accumulator, use:
//          root_hash =
//          resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
// - Validate that the transaction root hash submitted in
// req.known_value.node_value.txn_root_hash
//      exists in the proof for accumulator and that the proof is valid with
//      this hash
// - Validate ledger info
//      - let ledger_info_hash =
//      Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
//      - Verify signatures from resp.ledger_info_with_sigs.signatures are
//      signing
//          ledger_info_hash and that there are >2/3 nodes signing this
//          correctly
//      - Validate that the timestamp is relatively recent in
//          resp.ledger_info_with_sigs.ledger_info.timestamp
//
//
// GetAccountTransactionBySequenceNumberResponse:
// - Note that other than type completed_transaction, there will be no proof
// returned
//      since the transaction has not yet been committed.  To ensure that a
//      validator is telling the truth about it not being committed yet, a
//      client should query for their account state and verify that their
//      current sequence number is less than what they are searching for with
//      GetAccountTransactionBySequenceNumberResponse
// - let txn =
//      resp.get_account_transaction_by_sequence_number_response.transaction.committed_transaction;
// - let txn_hash = Hash(txn);
// - Verify that resp.proof.transaction_info.signed_transaction_hash == txn_hash
// - Validate accumulator using resp.proof.transaction_info as the leaf
//      - When verifying the accumulator, use:
//          root_hash =
//          resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
// - Validate that the transaction root hash submitted in
// req.known_value.node_value.txn_root_hash
//      exists in the proof for accumulator and that the proof is valid with
//      this hash
// - Validate ledger info
//      - let ledger_info_hash =
//      Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
//      - Verify signatures from resp.ledger_info_with_sigs.signatures are
//      signing
//          ledger_info_hash and that there are >2/3 nodes signing this
//          correctly
//      - Validate that the timestamp is relatively recent in
//          resp.ledger_info_with_sigs.ledger_info.timestamp
//
//
// GetTransactionsResponse:
// - for txn in resp.get_transactions_response.transactions:
//      - let txn = txn.committed_transaction;
//      - let txn_hash = Hash(txn);
//      - Verify that txn.proof.transaction_info.signed_transaction_hash ==
//      txn_hash
//      - Validate accumulator using txn.proof.transaction_info as the leaf
//      - When verifying the accumulator, use:
//          root_hash =
//          resp.ledger_info_with_sigs.ledger_info.ledger_info.txn_root_hash;
//      - Verify that transactions are sequential and none are missing
// - Validate ledger info
//      - let ledger_info_hash =
//      Hash(resp.ledger_info_with_sigs.ledger_info.ledger_info);
//      - Verify signatures from resp.ledger_info_with_sigs.signatures are
//      signing
//          ledger_info_hash and that there are >2/3 nodes signing this
//          correctly
//      - Validate that the timestamp is relatively recent in
//          resp.ledger_info_with_sigs.ledger_info.timestamp
// - If the number of transactions returned is less than limit for an ascending
// query
//      or if the requested offset > current version for a descending query,
//      the client should verify that the timestamp in ledger info is relatively
//      recent to determine if it is likely that all transactions available were
//      returned
syntax = "proto3";

package types;

import "access_path.proto";
import "account_state_blob.proto";
import "events.proto";
import "ledger_info.proto";
import "transaction.proto";
import "validator_change.proto";

// -----------------------------------------------------------------------------
// ---------------- Update to latest ledger request
// -----------------------------------------------------------------------------

// This API is used to update the client to the latest ledger version and
// optionally also request 1..n other pieces of data.  This allows for batch
// queries.  All queries return proofs that a client should check to validate
// the data.
//
// Note that if a client only wishes to update to the latest LedgerInfo and
// receive the proof that this latest ledger extends the client_known_version
// ledger the client had, they can simply set the requested_items to an empty
// list.
message UpdateToLatestLedgerRequest {
    // This is the version the client already trusts. Usually the client should
    // set this to the version it obtained the last time it synced with the
    // chain. If this is the first time ever the client sends a request, it must
    // use the waypoint hard-coded in its software.
    uint64 client_known_version = 1;

    // The items for which we are requesting data in this API call.
    repeated RequestItem requested_items = 2;
}

message RequestItem {
    oneof requested_items {
        GetAccountStateRequest get_account_state_request = 1;
        GetAccountTransactionBySequenceNumberRequest
        get_account_transaction_by_sequence_number_request = 2;
        GetEventsByEventAccessPathRequest get_events_by_event_access_path_request =
        3;
        GetTransactionsRequest get_transactions_request = 4;
    }
}

// -----------------------------------------------------------------------------
// ---------------- Update to latest ledger response
// -----------------------------------------------------------------------------

// Response from getting latest ledger
message UpdateToLatestLedgerResponse {
    // Responses to the queries posed by the requests. The proofs generated will
    // be relative to the version of the latest ledger provided below.
    repeated ResponseItem response_items = 1;

    // The latest ledger info this node has. It will come with at least 2f+1
    // validator signatures as well as a proof that shows the latest ledger
    // extends the old ledger the client had.
    LedgerInfoWithSignatures ledger_info_with_sigs = 2;

    // Validator change events from what the client last knew.  This is used to
    // inform the client of validator changes from the client's last known version
    // until the current version
    repeated ValidatorChangeEventWithProof validator_change_events = 3;
}

// Individual response items to the queries posed by the requests
message ResponseItem {
    oneof response_items {
        GetAccountStateResponse get_account_state_response = 3;
        GetAccountTransactionBySequenceNumberResponse
            get_account_transaction_by_sequence_number_response = 4;
        GetEventsByEventAccessPathResponse get_events_by_event_access_path_response = 5;
        GetTransactionsResponse get_transactions_response = 6;
    }
}

// -----------------------------------------------------------------------------
// ---------------- Get account state (balance, sequence number, etc.)
// -----------------------------------------------------------------------------

// Gets latest state for an account.
message GetAccountStateRequest {
    // Account for which we are fetching the state.
    bytes address = 1;
}

// State information returned by a get account state query.
message GetAccountStateResponse {
    // Blob value representing the account state together with proof the client
    // can utilize to verify it.
    AccountStateWithProof account_state_with_proof = 1;
}

// -----------------------------------------------------------------------------
// ---------------- Get single transaction by account + sequence number
// -----------------------------------------------------------------------------
// Get transactions that altered an account - this includes both sent and
// received. A user of this should check that the data returned matches what
// they expect.  As an example, a potential attack vector would be something
// like the following: Alice is buying an apple from Bob. Alice's phone signs a
// transaction X with sequence number N that pays coins to Bob. Alice transmits
// this signature to Bob's payment terminal which then submits the transaction
// and checks its status to see if Alice can be given the apple. However, as Bob
// is doing this Alice constructs a second transaction X' also with sequence
// number N. Alice gets that transaction inserted in the blockchain. If Bob
// isn't thoughtful about how he uses this API he may assume that if he asks for
// the N'th transaction on Alice's account that when the API returns that this
// means the transaction has gone through. The point here is that one should be
// careful in reading too much into "transaction X is on the chain" and focus on
// the logs, which tell you what the transaction did.
//
// If a client submitted a transaction, they should also verify that the hash of
// the returned transaction matches what they submitted.  As an example, if a
// client has two wallets that share the same account, they may both submit a
// transaction at the same sequence number and only one will be committed.  A
// client should never assume that if they receive the response that this
// transaction was included that it means that this is definitely the
// transaction that was submitted.  They should check that the hash matches what
// they sent
message GetAccountTransactionBySequenceNumberRequest {
    // Account for which to query transactions
    bytes account = 1;

    uint64 sequence_number = 2;

    // Set to true to fetch events for the transaction at this version
    bool fetch_events = 3;
}

// Transaction information for transactions requested by
// GetAccountTransactionsRequest
message GetAccountTransactionBySequenceNumberResponse {
  // When the transaction requested is committed, return the committed
  // transaction with proof.
  SignedTransactionWithProof signed_transaction_with_proof = 2;
  // When the transaction requested is not committed, we give a proof that
  // shows the current sequence number is smaller than what would have been if
  // the transaction was committed.
  AccountStateWithProof proof_of_current_sequence_number = 3;
}

// -----------------------------------------------------------------------------
// ---------------- Get events by event access path
// -----------------------------------------------------------------------------

// Get events that exist on an event access path.  In the current world,
// a user may specify events that were received, events that were sent, or any
// event that modifies their account
message GetEventsByEventAccessPathRequest {
    AccessPath access_path = 1;

    // The sequence number of the event to start with for this query. Use a
    // sequence number of MAX_INT to represent the latest.
    uint64 start_event_seq_num = 2;

    // If ascending is true this query will return up to `limit` events that were
    // emitted after `start_event_seq_num`. Otherwise it will return up to `limit`
    // events before the offset. Both cases are inclusive.
    bool ascending = 3;

    // Limit number of results
    uint64 limit = 4;
}

message GetEventsByEventAccessPathResponse {
    // Returns an event and proof of each of the events in the request. The first
    // element of proofs will be the closest to `start_event_seq_num`.
    repeated EventWithProof events_with_proof = 1;

    // If the number of events returned is less than `limit` for an ascending
    // query or if start_event_seq_num > the latest seq_num for a descending
    // query,  returns the state of the account containing the given access path
    // in the latest state. This allows the client to verify that there are in
    // fact no extra events.
    //
    // The LedgerInfoWithSignatures which is on the main
    // UpdateToLatestLedgerResponse can be used to validate this.
    AccountStateWithProof proof_of_latest_event = 2;
}

// -----------------------------------------------------------------------------
// ---------------- Get transactions
// -----------------------------------------------------------------------------

// Get up to limit transactions starting from start_version.
message GetTransactionsRequest {
    // The version of the transaction to start with for this query.  Use a version
    // of MAX_INT to represent the latest.
    uint64 start_version = 1;

    // Limit number of results
    uint64 limit = 2;

    // Set to true to fetch events for the transaction at each version
    bool fetch_events = 3;
}

message GetTransactionsResponse {
    TransactionListWithProof txn_list_with_proof = 1;
}

src:./access_path.proto


// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

syntax = "proto3";

package types;

message AccessPath {
  bytes address = 1;
  bytes path = 2;
}

lightning network 閃電網路

TOC

生成 Google Protocol Buffers 文件

lnd/lnrpc at master · lightningnetwork/lnd

git clone https://github.com/lightningnetwork/lnd.git /tmp/src/lnd
bash tc.sh --gen-proto-doc /tmp/src/lnd/lnrpc /tmp/output.md

Generated Date:2019-09-12T13:49:08+08:00

Protocol Documentation

Table of Contents

Top

chainrpc/chainnotifier.proto

BlockEpoch

FieldTypeLabelDescription
hashbytesThe hash of the block.
heightuint32The height of the block.

ConfDetails

FieldTypeLabelDescription
raw_txbytesThe raw bytes of the confirmed transaction.
block_hashbytesThe hash of the block in which the confirmed transaction was included in.
block_heightuint32The height of the block in which the confirmed transaction was included in.
tx_indexuint32The index of the confirmed transaction within the transaction.

ConfEvent

FieldTypeLabelDescription
confConfDetailsAn event that includes the confirmation details of the request (txid/ouput script).
reorgReorgAn event send when the transaction of the request is reorged out of the chain.

ConfRequest

FieldTypeLabelDescription
txidbytesThe transaction hash for which we should request a confirmation notification for. If set to a hash of all zeros, then the confirmation notification will be requested for the script instead.
scriptbytesAn output script within a transaction with the hash above which will be used by light clients to match block filters. If the transaction hash is set to a hash of all zeros, then a confirmation notification will be requested for this script instead.
num_confsuint32The number of desired confirmations the transaction/output script should reach before dispatching a confirmation notification.
height_hintuint32The earliest height in the chain for which the transaction/output script could have been included in a block. This should in most cases be set to the broadcast height of the transaction/output script.

Outpoint

FieldTypeLabelDescription
hashbytesThe hash of the transaction.
indexuint32The index of the output within the transaction.

Reorg

TODO(wilmer): need to know how the client will use this first.

SpendDetails

FieldTypeLabelDescription
spending_outpointOutpointThe outpoint was that spent.
raw_spending_txbytesThe raw bytes of the spending transaction.
spending_tx_hashbytesThe hash of the spending transaction.
spending_input_indexuint32The input of the spending transaction that fulfilled the spend request.
spending_heightuint32The height at which the spending transaction was included in a block.

SpendEvent

FieldTypeLabelDescription
spendSpendDetailsAn event that includes the details of the spending transaction of the request (outpoint/output script).
reorgReorgAn event sent when the spending transaction of the request was reorged out of the chain.

SpendRequest

FieldTypeLabelDescription
outpointOutpointThe outpoint for which we should request a spend notification for. If set to a zero outpoint, then the spend notification will be requested for the script instead.
scriptbytesThe output script for the outpoint above. This will be used by light clients to match block filters. If the outpoint is set to a zero outpoint, then a spend notification will be requested for this script instead.
height_hintuint32The earliest height in the chain for which the outpoint/output script could have been spent. This should in most cases be set to the broadcast height of the outpoint/output script.

ChainNotifier

Method NameRequest TypeResponse TypeDescription
RegisterConfirmationsNtfnConfRequestConfEvent streamRegisterConfirmationsNtfn is a synchronous response-streaming RPC that registers an intent for a client to be notified once a confirmation request has reached its required number of confirmations on-chain.

A client can specify whether the confirmation request should be for a particular transaction by its hash or for an output script by specifying a zero hash. | | RegisterSpendNtfn | SpendRequest | SpendEvent stream | RegisterSpendNtfn is a synchronous response-streaming RPC that registers an intent for a client to be notification once a spend request has been spent by a transaction that has confirmed on-chain.

A client can specify whether the spend request should be for a particular outpoint or for an output script by specifying a zero outpoint. | | RegisterBlockEpochNtfn | BlockEpoch | BlockEpoch stream | RegisterBlockEpochNtfn is a synchronous response-streaming RPC that registers an intent for a client to be notified of blocks in the chain. The stream will return a hash and height tuple of a block for each new/stale block in the chain. It is the client's responsibility to determine whether the tuple returned is for a new or stale block in the chain.

A client can also request a historical backlog of blocks from a particular point. This allows clients to be idempotent by ensuring that they do not missing processing a single block within the chain. |

Top

walletrpc/walletkit.proto

AddrRequest

No fields, as we always give out a p2wkh address.

AddrResponse

FieldTypeLabelDescription
addrstringThe address encoded using a bech32 format.

BumpFeeRequest

FieldTypeLabelDescription
outpointlnrpc.OutPointThe input we're attempting to bump the fee of.
target_confuint32The target number of blocks that the input should be spent within.
sat_per_byteuint32The fee rate, expressed in sat/byte, that should be used to spend the input with.

BumpFeeResponse

EstimateFeeRequest

FieldTypeLabelDescription
conf_targetint32The number of confirmations to shoot for when estimating the fee.

EstimateFeeResponse

FieldTypeLabelDescription
sat_per_kwint64The amount of satoshis per kw that should be used in order to reach the confirmation target in the request.

KeyReq

FieldTypeLabelDescription
key_finger_printint32Is the key finger print of the root pubkey that this request is targeting. This allows the WalletKit to possibly serve out keys for multiple HD chains via public derivation.
key_familyint32The target key family to derive a key from. In other contexts, this is known as the "account".

PendingSweep

FieldTypeLabelDescription
outpointlnrpc.OutPointThe outpoint of the output we're attempting to sweep.
witness_typeWitnessTypeThe witness type of the output we're attempting to sweep.
amount_satuint32The value of the output we're attempting to sweep.
sat_per_byteuint32The fee rate we'll use to sweep the output. The fee rate is only determined once a sweeping transaction for the output is created, so it's possible for this to be 0 before this.
broadcast_attemptsuint32The number of broadcast attempts we've made to sweep the output.
next_broadcast_heightuint32The next height of the chain at which we'll attempt to broadcast the sweep transaction of the output.

PendingSweepsRequest

PendingSweepsResponse

FieldTypeLabelDescription
pending_sweepsPendingSweeprepeatedThe set of outputs currently being swept by lnd's central batching engine.

PublishResponse

FieldTypeLabelDescription
publish_errorstringIf blank, then no error occurred and the transaction was successfully published. If not the empty string, then a string representation of the broadcast error.

TODO(roasbeef): map to a proper enum type |

SendOutputsRequest

FieldTypeLabelDescription
sat_per_kwint64The number of satoshis per kilo weight that should be used when crafting this transaction.
outputssignrpc.TxOutrepeatedA slice of the outputs that should be created in the transaction produced.

SendOutputsResponse

FieldTypeLabelDescription
raw_txbytesThe serialized transaction sent out on the network.

Transaction

FieldTypeLabelDescription
tx_hexbytesThe raw serialized transaction.

WitnessType

NameNumberDescription
UNKNOWN_WITNESS0
COMMITMENT_TIME_LOCK1A witness that allows us to spend the output of a commitment transaction after a relative lock-time lockout.
COMMITMENT_NO_DELAY2A witness that allows us to spend a settled no-delay output immediately on a counterparty's commitment transaction.
COMMITMENT_REVOKE3A witness that allows us to sweep the settled output of a malicious counterparty's who broadcasts a revoked commitment transaction.
HTLC_OFFERED_REVOKE4A witness that allows us to sweep an HTLC which we offered to the remote party in the case that they broadcast a revoked commitment state.
HTLC_ACCEPTED_REVOKE5A witness that allows us to sweep an HTLC output sent to us in the case that the remote party broadcasts a revoked commitment state.
HTLC_OFFERED_TIMEOUT_SECOND_LEVEL6A witness that allows us to sweep an HTLC output that we extended to a party, but was never fulfilled. This HTLC output isn't directly on the commitment transaction, but is the result of a confirmed second-level HTLC transaction. As a result, we can only spend this after a CSV delay.
HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL7A witness that allows us to sweep an HTLC output that was offered to us, and for which we have a payment preimage. This HTLC output isn't directly on our commitment transaction, but is the result of confirmed second-level HTLC transaction. As a result, we can only spend this after a CSV delay.
HTLC_OFFERED_REMOTE_TIMEOUT8A witness that allows us to sweep an HTLC that we offered to the remote party which lies in the commitment transaction of the remote party. We can spend this output after the absolute CLTV timeout of the HTLC as passed.
HTLC_ACCEPTED_REMOTE_SUCCESS9A witness that allows us to sweep an HTLC that was offered to us by the remote party. We use this witness in the case that the remote party goes to chain, and we know the pre-image to the HTLC. We can sweep this without any additional timeout.
HTLC_SECOND_LEVEL_REVOKE10A witness that allows us to sweep an HTLC from the remote party's commitment transaction in the case that the broadcast a revoked commitment, but then also immediately attempt to go to the second level to claim the HTLC.
WITNESS_KEY_HASH11A witness type that allows us to spend a regular p2wkh output that's sent to an output which is under complete control of the backing wallet.
NESTED_WITNESS_KEY_HASH12A witness type that allows us to sweep an output that sends to a nested P2SH script that pays to a key solely under our control.

WalletKit

Method NameRequest TypeResponse TypeDescription
DeriveNextKeyKeyReq.signrpc.KeyDescriptorDeriveNextKey attempts to derive the next key within the key family (account in BIP43) specified. This method should return the next external child within this branch.
DeriveKey.signrpc.KeyLocator.signrpc.KeyDescriptorDeriveKey attempts to derive an arbitrary key specified by the passed KeyLocator.
NextAddrAddrRequestAddrResponseNextAddr returns the next unused address within the wallet.
PublishTransactionTransactionPublishResponsePublishTransaction attempts to publish the passed transaction to the network. Once this returns without an error, the wallet will continually attempt to re-broadcast the transaction on start up, until it enters the chain.
SendOutputsSendOutputsRequestSendOutputsResponseSendOutputs is similar to the existing sendmany call in Bitcoind, and allows the caller to create a transaction that sends to several outputs at once. This is ideal when wanting to batch create a set of transactions.
EstimateFeeEstimateFeeRequestEstimateFeeResponseEstimateFee attempts to query the internal fee estimator of the wallet to determine the fee (in sat/kw) to attach to a transaction in order to achieve the confirmation target.
PendingSweepsPendingSweepsRequestPendingSweepsResponsePendingSweeps returns lists of on-chain outputs that lnd is currently attempting to sweep within its central batching engine. Outputs with similar fee rates are batched together in order to sweep them within a single transaction.

NOTE: Some of the fields within PendingSweepsRequest are not guaranteed to remain supported. This is an advanced API that depends on the internals of the UtxoSweeper, so things may change. | | BumpFee | BumpFeeRequest | BumpFeeResponse | BumpFee bumps the fee of an arbitrary input within a transaction. This RPC takes a different approach than bitcoind's bumpfee command. lnd has a central batching engine in which inputs with similar fee rates are batched together to save on transaction fees. Due to this, we cannot rely on bumping the fee on a specific transaction, since transactions can change at any point with the addition of new inputs. The list of inputs that currently exist within lnd's central batching engine can be retrieved through the PendingSweeps RPC.

When bumping the fee of an input that currently exists within lnd's central batching engine, a higher fee transaction will be created that replaces the lower fee transaction through the Replace-By-Fee (RBF) policy. If it

This RPC also serves useful when wanting to perform a Child-Pays-For-Parent (CPFP), where the child transaction pays for its parent's fee. This can be done by specifying an outpoint within the low fee transaction that is under the control of the wallet.

The fee preference can be expressed either as a specific fee rate or a delta of blocks in which the output should be swept on-chain within. If a fee preference is not explicitly specified, then an error is returned.

Note that this RPC currently doesn't perform any validation checks on the fee preference being provided. For now, the responsibility of ensuring that the new fee preference is sufficient is delegated to the user. |

Top

autopilotrpc/autopilot.proto

ModifyStatusRequest

FieldTypeLabelDescription
enableboolWhether the autopilot agent should be enabled or not.

ModifyStatusResponse

QueryScoresRequest

FieldTypeLabelDescription
pubkeysstringrepeated
ignore_local_stateboolIf set, we will ignore the local channel state when calculating scores.

QueryScoresResponse

FieldTypeLabelDescription
resultsQueryScoresResponse.HeuristicResultrepeated

QueryScoresResponse.HeuristicResult

FieldTypeLabelDescription
heuristicstring
scoresQueryScoresResponse.HeuristicResult.ScoresEntryrepeated

QueryScoresResponse.HeuristicResult.ScoresEntry

FieldTypeLabelDescription
keystring
valuedouble

SetScoresRequest

FieldTypeLabelDescription
heuristicstringThe name of the heuristic to provide scores to.
scoresSetScoresRequest.ScoresEntryrepeatedA map from hex-encoded public keys to scores. Scores must be in the range [0.0, 1.0].

SetScoresRequest.ScoresEntry

FieldTypeLabelDescription
keystring
valuedouble

SetScoresResponse

StatusRequest

StatusResponse

FieldTypeLabelDescription
activeboolIndicates whether the autopilot is active or not.

Autopilot

Autopilot is a service that can be used to get information about the current state of the daemon's autopilot agent, and also supply it with information that can be used when deciding where to open channels.

Method NameRequest TypeResponse TypeDescription
StatusStatusRequestStatusResponseStatus returns whether the daemon's autopilot agent is active.
ModifyStatusModifyStatusRequestModifyStatusResponseModifyStatus is used to modify the status of the autopilot agent, like enabling or disabling it.
QueryScoresQueryScoresRequestQueryScoresResponseQueryScores queries all available autopilot heuristics, in addition to any active combination of these heruristics, for the scores they would give to the given nodes.
SetScoresSetScoresRequestSetScoresResponseSetScores attempts to set the scores used by the running autopilot agent, if the external scoring heuristic is enabled.

Top

invoicesrpc/invoices.proto

AddHoldInvoiceRequest

FieldTypeLabelDescription
memostringAn optional memo to attach along with the invoice. Used for record keeping purposes for the invoice's creator, and will also be set in the description field of the encoded payment request if the description_hash field is not being used.
hashbytesThe hash of the preimage
valueint64The value of this invoice in satoshis
description_hashbytesHash (SHA-256) of a description of the payment. Used if the description of payment (memo) is too long to naturally fit within the description field of an encoded payment request.
expiryint64Payment request expiry time in seconds. Default is 3600 (1 hour).
fallback_addrstringFallback on-chain address.
cltv_expiryuint64Delta to use for the time-lock of the CLTV extended to the final hop.
route_hintslnrpc.RouteHintrepeatedRoute hints that can each be individually used to assist in reaching the invoice's destination.
privateboolWhether this invoice should include routing hints for private channels.

AddHoldInvoiceResp

FieldTypeLabelDescription
payment_requeststringA bare-bones invoice for a payment within the Lightning Network. With the details of the invoice, the sender has all the data necessary to send a payment to the recipient.

CancelInvoiceMsg

FieldTypeLabelDescription
payment_hashbytesHash corresponding to the (hold) invoice to cancel.

CancelInvoiceResp

SettleInvoiceMsg

FieldTypeLabelDescription
preimagebytesExternally discovered pre-image that should be used to settle the hold invoice.

SettleInvoiceResp

SubscribeSingleInvoiceRequest

FieldTypeLabelDescription
r_hashbytesHash corresponding to the (hold) invoice to subscribe to.

Invoices

Invoices is a service that can be used to create, accept, settle and cancel invoices.

Method NameRequest TypeResponse TypeDescription
SubscribeSingleInvoiceSubscribeSingleInvoiceRequest.lnrpc.Invoice streamSubscribeSingleInvoice returns a uni-directional stream (server -> client) to notify the client of state transitions of the specified invoice. Initially the current invoice state is always sent out.
CancelInvoiceCancelInvoiceMsgCancelInvoiceRespCancelInvoice cancels a currently open invoice. If the invoice is already canceled, this call will succeed. If the invoice is already settled, it will fail.
AddHoldInvoiceAddHoldInvoiceRequestAddHoldInvoiceRespAddHoldInvoice creates a hold invoice. It ties the invoice to the hash supplied in the request.
SettleInvoiceSettleInvoiceMsgSettleInvoiceRespSettleInvoice settles an accepted invoice. If the invoice is already settled, this call will succeed.

Top

rpc.proto

AbandonChannelRequest

FieldTypeLabelDescription
channel_pointChannelPoint

AbandonChannelResponse

AddInvoiceResponse

FieldTypeLabelDescription
r_hashbytes
payment_requeststringA bare-bones invoice for a payment within the Lightning Network. With the details of the invoice, the sender has all the data necessary to send a payment to the recipient.
add_indexuint64The "add" index of this invoice. Each newly created invoice will increment this index making it monotonically increasing. Callers to the SubscribeInvoices call can use this to instantly get notified of all added invoices with an add_index greater than this one.

Chain

FieldTypeLabelDescription
chainstringThe blockchain the node is on (eg bitcoin, litecoin)
networkstringThe network the node is on (eg regtest, testnet, mainnet)

ChanBackupExportRequest

ChanBackupSnapshot

FieldTypeLabelDescription
single_chan_backupsChannelBackupsThe set of new channels that have been added since the last channel backup snapshot was requested.
multi_chan_backupMultiChanBackupA multi-channel backup that covers all open channels currently known to lnd.

ChanInfoRequest

FieldTypeLabelDescription
chan_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.

ChangePasswordRequest

FieldTypeLabelDescription
current_passwordbytescurrent_password should be the current valid passphrase used to unlock the daemon.
new_passwordbytesnew_password should be the new passphrase that will be needed to unlock the daemon.

ChangePasswordResponse

Channel

FieldTypeLabelDescription
activeboolWhether this channel is active or not
remote_pubkeystringThe identity pubkey of the remote node
channel_pointstringThe outpoint (txid:index) of the funding transaction. With this value, Bob will be able to generate a signature for Alice's version of the commitment transaction.
chan_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.
capacityint64The total amount of funds held in this channel
local_balanceint64This node's current balance in this channel
remote_balanceint64The counterparty's current balance in this channel
commit_feeint64The amount calculated to be paid in fees for the current set of commitment transactions. The fee amount is persisted with the channel in order to allow the fee amount to be removed and recalculated with each channel state update, including updates that happen after a system restart.
commit_weightint64The weight of the commitment transaction
fee_per_kwint64The required number of satoshis per kilo-weight that the requester will pay at all times, for both the funding transaction and commitment transaction. This value can later be updated once the channel is open.
unsettled_balanceint64The unsettled balance in this channel
total_satoshis_sentint64The total number of satoshis we've sent within this channel.
total_satoshis_receivedint64The total number of satoshis we've received within this channel.
num_updatesuint64The total number of updates conducted within this channel.
pending_htlcsHTLCrepeatedThe list of active, uncleared HTLCs currently pending within the channel.
csv_delayuint32The CSV delay expressed in relative blocks. If the channel is force closed, we will need to wait for this many blocks before we can regain our funds.
privateboolWhether this channel is advertised to the network or not.
initiatorboolTrue if we were the ones that created the channel.
chan_status_flagsstringA set of flags showing the current state of the channel.
local_chan_reserve_satint64The minimum satoshis this node is required to reserve in its balance.
remote_chan_reserve_satint64The minimum satoshis the other node is required to reserve in its balance.

ChannelBackup

FieldTypeLabelDescription
chan_pointChannelPointIdentifies the channel that this backup belongs to.
chan_backupbytesIs an encrypted single-chan backup. this can be passed to RestoreChannelBackups, or the WalletUnlocker Init and Unlock methods in order to trigger the recovery protocol.

ChannelBackupSubscription

ChannelBackups

FieldTypeLabelDescription
chan_backupsChannelBackuprepeatedA set of single-chan static channel backups.

ChannelBalanceRequest

ChannelBalanceResponse

FieldTypeLabelDescription
balanceint64Sum of channels balances denominated in satoshis
pending_open_balanceint64Sum of channels pending balances denominated in satoshis

ChannelCloseSummary

FieldTypeLabelDescription
channel_pointstringThe outpoint (txid:index) of the funding transaction.
chan_iduint64The unique channel ID for the channel.
chain_hashstringThe hash of the genesis block that this channel resides within.
closing_tx_hashstringThe txid of the transaction which ultimately closed this channel.
remote_pubkeystringPublic key of the remote peer that we formerly had a channel with.
capacityint64Total capacity of the channel.
close_heightuint32Height at which the funding transaction was spent.
settled_balanceint64Settled balance at the time of channel closure
time_locked_balanceint64The sum of all the time-locked outputs at the time of channel closure
close_typeChannelCloseSummary.ClosureTypeDetails on how the channel was closed.

ChannelCloseUpdate

FieldTypeLabelDescription
closing_txidbytes
successbool

ChannelEdge

A fully authenticated channel along with all its unique attributes. Once an authenticated channel announcement has been processed on the network, then an instance of ChannelEdgeInfo encapsulating the channels attributes is stored. The other portions relevant to routing policy of a channel are stored within a ChannelEdgePolicy for each direction of the channel.

FieldTypeLabelDescription
channel_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.
chan_pointstring
last_updateuint32
node1_pubstring
node2_pubstring
capacityint64
node1_policyRoutingPolicy
node2_policyRoutingPolicy

ChannelEdgeUpdate

FieldTypeLabelDescription
chan_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.
chan_pointChannelPoint
capacityint64
routing_policyRoutingPolicy
advertising_nodestring
connecting_nodestring

ChannelEventSubscription

ChannelEventUpdate

FieldTypeLabelDescription
open_channelChannel
closed_channelChannelCloseSummary
active_channelChannelPoint
inactive_channelChannelPoint
typeChannelEventUpdate.UpdateType

ChannelFeeReport

FieldTypeLabelDescription
chan_pointstringThe channel that this fee report belongs to.
base_fee_msatint64The base fee charged regardless of the number of milli-satoshis sent.
fee_per_milint64The amount charged per milli-satoshis transferred expressed in millionths of a satoshi.
fee_ratedoubleThe effective fee rate in milli-satoshis. Computed by dividing the fee_per_mil value by 1 million.

ChannelGraph

Returns a new instance of the directed channel graph.

FieldTypeLabelDescription
nodesLightningNoderepeatedThe list of LightningNodes in this channel graph
edgesChannelEdgerepeatedThe list of ChannelEdges in this channel graph

ChannelGraphRequest

FieldTypeLabelDescription
include_unannouncedboolWhether unannounced channels are included in the response or not. If set, unannounced channels are included. Unannounced channels are both private channels, and public channels that are not yet announced to the network.

ChannelOpenUpdate

FieldTypeLabelDescription
channel_pointChannelPoint

ChannelPoint

FieldTypeLabelDescription
funding_txid_bytesbytesTxid of the funding transaction
funding_txid_strstringHex-encoded string representing the funding transaction
output_indexuint32The index of the output of the funding transaction

CloseChannelRequest

FieldTypeLabelDescription
channel_pointChannelPointThe outpoint (txid:index) of the funding transaction. With this value, Bob will be able to generate a signature for Alice's version of the commitment transaction.
forceboolIf true, then the channel will be closed forcibly. This means the current commitment transaction will be signed and broadcast.
target_confint32The target number of blocks that the closure transaction should be confirmed by.
sat_per_byteint64A manual fee rate set in sat/byte that should be used when crafting the closure transaction.

CloseStatusUpdate

FieldTypeLabelDescription
close_pendingPendingUpdate
chan_closeChannelCloseUpdate

ClosedChannelUpdate

FieldTypeLabelDescription
chan_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.
capacityint64
closed_heightuint32
chan_pointChannelPoint

ClosedChannelsRequest

FieldTypeLabelDescription
cooperativebool
local_forcebool
remote_forcebool
breachbool
funding_canceledbool
abandonedbool

ClosedChannelsResponse

FieldTypeLabelDescription
channelsChannelCloseSummaryrepeated

ConfirmationUpdate

FieldTypeLabelDescription
block_shabytes
block_heightint32
num_confs_leftuint32

ConnectPeerRequest

FieldTypeLabelDescription
addrLightningAddressLightning address of the peer, in the format &lt;pubkey&gt;@host
permboolIf set, the daemon will attempt to persistently connect to the target peer. Otherwise, the call will be synchronous.

ConnectPeerResponse

DebugLevelRequest

FieldTypeLabelDescription
showbool
level_specstring

DebugLevelResponse

FieldTypeLabelDescription
sub_systemsstring

DeleteAllPaymentsRequest

DeleteAllPaymentsResponse

DisconnectPeerRequest

FieldTypeLabelDescription
pub_keystringThe pubkey of the node to disconnect from

DisconnectPeerResponse

EdgeLocator

FieldTypeLabelDescription
channel_iduint64The short channel id of this edge.
direction_reverseboolThe direction of this edge. If direction_reverse is false, the direction of this edge is from the channel endpoint with the lexicographically smaller pub key to the endpoint with the larger pub key. If direction_reverse is is true, the edge goes the other way.

EstimateFeeRequest

FieldTypeLabelDescription
AddrToAmountEstimateFeeRequest.AddrToAmountEntryrepeatedThe map from addresses to amounts for the transaction.
target_confint32The target number of blocks that this transaction should be confirmed by.

EstimateFeeRequest.AddrToAmountEntry

FieldTypeLabelDescription
keystring
valueint64

EstimateFeeResponse

FieldTypeLabelDescription
fee_satint64The total fee in satoshis.
feerate_sat_per_byteint64The fee rate in satoshi/byte.

ExportChannelBackupRequest

FieldTypeLabelDescription
chan_pointChannelPointThe target channel point to obtain a back up for.

FeeLimit

FieldTypeLabelDescription
fixedint64The fee limit expressed as a fixed amount of satoshis.
percentint64The fee limit expressed as a percentage of the payment amount.

FeeReportRequest

FeeReportResponse

FieldTypeLabelDescription
channel_feesChannelFeeReportrepeatedAn array of channel fee reports which describes the current fee schedule for each channel.
day_fee_sumuint64The total amount of fee revenue (in satoshis) the switch has collected over the past 24 hrs.
week_fee_sumuint64The total amount of fee revenue (in satoshis) the switch has collected over the past 1 week.
month_fee_sumuint64The total amount of fee revenue (in satoshis) the switch has collected over the past 1 month.

ForwardingEvent

FieldTypeLabelDescription
timestampuint64Timestamp is the time (unix epoch offset) that this circuit was completed.
chan_id_inuint64The incoming channel ID that carried the HTLC that created the circuit.
chan_id_outuint64The outgoing channel ID that carried the preimage that completed the circuit.
amt_inuint64The total amount (in satoshis) of the incoming HTLC that created half the circuit.
amt_outuint64The total amount (in satoshis) of the outgoing HTLC that created the second half of the circuit.
feeuint64The total fee (in satoshis) that this payment circuit carried.
fee_msatuint64The total fee (in milli-satoshis) that this payment circuit carried.

ForwardingHistoryRequest

FieldTypeLabelDescription
start_timeuint64Start time is the starting point of the forwarding history request. All records beyond this point will be included, respecting the end time, and the index offset.
end_timeuint64End time is the end point of the forwarding history request. The response will carry at most 50k records between the start time and the end time. The index offset can be used to implement pagination.
index_offsetuint32Index offset is the offset in the time series to start at. As each response can only contain 50k records, callers can use this to skip around within a packed time series.
num_max_eventsuint32The max number of events to return in the response to this query.

ForwardingHistoryResponse

FieldTypeLabelDescription
forwarding_eventsForwardingEventrepeatedA list of forwarding events from the time slice of the time series specified in the request.
last_offset_indexuint32The index of the last time in the set of returned forwarding events. Can be used to seek further, pagination style.

GenSeedRequest

FieldTypeLabelDescription
aezeed_passphrasebytesaezeed_passphrase is an optional user provided passphrase that will be used to encrypt the generated aezeed cipher seed.
seed_entropybytesseed_entropy is an optional 16-bytes generated via CSPRNG. If not specified, then a fresh set of randomness will be used to create the seed.

GenSeedResponse

FieldTypeLabelDescription
cipher_seed_mnemonicstringrepeatedcipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed cipher seed obtained by the user. This field is optional, as if not provided, then the daemon will generate a new cipher seed for the user. Otherwise, then the daemon will attempt to recover the wallet state linked to this cipher seed.
enciphered_seedbytesenciphered_seed are the raw aezeed cipher seed bytes. This is the raw cipher text before run through our mnemonic encoding scheme.

GetInfoRequest

GetInfoResponse

FieldTypeLabelDescription
identity_pubkeystringThe identity pubkey of the current node.
aliasstringIf applicable, the alias of the current node, e.g. "bob"
num_pending_channelsuint32Number of pending channels
num_active_channelsuint32Number of active channels
num_peersuint32Number of peers
block_heightuint32The node's current view of the height of the best block
block_hashstringThe node's current view of the hash of the best block
synced_to_chainboolWhether the wallet's view is synced to the main chain
testnetboolWhether the current node is connected to testnet. This field is deprecated and the network field should be used instead
urisstringrepeatedThe URIs of the current node.
best_header_timestampint64Timestamp of the block best known to the wallet
versionstringThe version of the LND software that the node is running.
num_inactive_channelsuint32Number of inactive channels
chainsChainrepeatedA list of active chains the node is connected to
colorstringThe color of the current node in hex code format
synced_to_graphboolWhether we consider ourselves synced with the public channel graph.

GetTransactionsRequest

GraphTopologySubscription

GraphTopologyUpdate

FieldTypeLabelDescription
node_updatesNodeUpdaterepeated
channel_updatesChannelEdgeUpdaterepeated
closed_chansClosedChannelUpdaterepeated

HTLC

FieldTypeLabelDescription
incomingbool
amountint64
hash_lockbytes
expiration_heightuint32

Hop

FieldTypeLabelDescription
chan_iduint64The unique channel ID for the channel. The first 3 bytes are the block height, the next 3 the index within the block, and the last 2 bytes are the output index for the channel.
chan_capacityint64
amt_to_forwardint64
feeint64
expiryuint32
amt_to_forward_msatint64
fee_msatint64
pub_keystringAn optional public key of the hop. If the public key is given, the payment can be executed without relying on a copy of the channel graph.
tlv_payloadboolIf set to true, then this hop will be encoded using the new variable length TLV format. Note that if any custom tlv_records below are specified, then this field MUST be set to true for them to be encoded properly.
tlv_recordsHop.TlvRecordsEntryrepeatedAn optional set of key-value TLV records. This is useful within the context of the SendToRoute call as it allows callers to specify arbitrary K-V pairs to drop off at each hop within the onion.

Hop.TlvRecordsEntry

FieldTypeLabelDescription
keyuint64
valuebytes

HopHint

FieldTypeLabelDescription
node_idstringThe public key of the node at the start of the channel.
chan_iduint64The unique identifier of the channel.
fee_base_msatuint32The base fee of the channel denominated in millisatoshis.
fee_proportional_millionthsuint32The fee rate of the channel for sending one satoshi across it denominated in millionths of a satoshi.
cltv_expiry_deltauint32The time-lock delta of the channel.

InitWalletRequest

FieldTypeLabelDescription
wallet_passwordbyteswallet_password is the passphrase that should be used to encrypt the wallet. This MUST be at least 8 chars in length. After creation, this password is required to unlock the daemon.
cipher_seed_mnemonicstringrepeatedcipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed cipher seed obtained by the user. This may have been generated by the GenSeed method, or be an existing seed.
aezeed_passphrasebytesaezeed_passphrase is an optional user provided passphrase that will be used to encrypt the generated aezeed cipher seed.
recovery_windowint32recovery_window is an optional argument specifying the address lookahead when restoring a wallet seed. The recovery window applies to each individual branch of the BIP44 derivation paths. Supplying a recovery window of zero indicates that no addresses should be recovered, such after the first initialization of the wallet.
channel_backupsChanBackupSnapshotchannel_backups is an optional argument that allows clients to recover the settled funds within a set of channels. This should be populated if the user was unable to close out all channels and sweep funds before partial or total data loss occurred. If specified, then after on-chain recovery of funds, lnd begin to carry out the data loss recovery protocol in order to recover the funds in each channel from a remote force closed transaction.

InitWalletResponse

Invoice

FieldTypeLabelDescription
memostringAn optional memo to attach along with the invoice. Used for record keeping purposes for the invoice's creator, and will also be set in the description field of the encoded payment request if the description_hash field is not being used.
receiptbytesDeprecated. An optional cryptographic receipt of payment which is not implemented.
r_preimagebytesThe hex-encoded preimage (32 byte) which will allow settling an incoming HTLC payable to this preimage
r_hashbytesThe hash of the preimage
valueint64The value of this invoice in satoshis
settledboolWhether this invoice has been fulfilled
creation_dateint64When this invoice was created
settle_dateint64When this invoice was settled
payment_requeststringA bare-bones invoice for a payment within the Lightning Network. With the details of the invoice, the sender has all the data necessary to send a payment to the recipient.
description_hashbytesHash (SHA-256) of a description of the payment. Used if the description of payment (memo) is too long to naturally fit within the description field of an encoded payment request.
expiryint64Payment request expiry time in seconds. Default is 3600 (1 hour).
fallback_addrstringFallback on-chain address.
cltv_expiryuint64Delta to use for the time-lock of the CLTV extended to the final hop.
route_hintsRouteHintrepeatedRoute hints that can each be individually used to assist in reaching the invoice's destination.
privateboolWhether this invoice should include routing hints for private channels.
add_indexuint64The "add" index of this invoice. Each newly created invoice will increment this index making it monotonically increasing. Callers to the SubscribeInvoices call can use this to instantly get notified of all added invoices with an add_index greater than this one.
settle_indexuint64The "settle" index of this invoice. Each newly settled invoice will increment this index making it monotonically increasing. Callers to the SubscribeInvoices call can use this to instantly get notified of all settled invoices with an settle_index greater than this one.
amt_paidint64Deprecated, use amt_paid_sat or amt_paid_msat.
amt_paid_satint64The amount that was accepted for this invoice, in satoshis. This will ONLY be set if this invoice has been settled. We provide this field as if the invoice was created with a zero value, then we need to record what amount was ultimately accepted. Additionally, it's possible that the sender paid MORE that was specified in the original invoice. So we'll record that here as well.
amt_paid_msatint64The amount that was accepted for this invoice, in millisatoshis. This will ONLY be set if this invoice has been settled. We provide this field as if the invoice was created with a zero value, then we need to record what amount was ultimately accepted. Additionally, it's possible that the sender paid MORE that was specified in the original invoice. So we'll record that here as well.
stateInvoice.InvoiceStateThe state the invoice is in.
htlcsInvoiceHTLCrepeatedList of HTLCs paying to this invoice [EXPERIMENTAL].

InvoiceHTLC

Details of an HTLC that paid to an invoice

FieldTypeLabelDescription
chan_iduint64Short channel id over which the htlc was received.
htlc_indexuint64Index identifying the htlc on the channel.
amt_msatuint64The amount of the htlc in msat.
accept_heightint32Block height at which this htlc was accepted.
accept_timeint64Time at which this htlc was accepted.
resolve_timeint64Time at which this htlc was settled or cancelled.
expiry_heightint32Block height at which this htlc expires.
stateInvoiceHTLCStateCurrent state the htlc is in.

InvoiceSubscription

FieldTypeLabelDescription
add_indexuint64If specified (non-zero), then we'll first start by sending out notifications for all added indexes with an add_index greater than this value. This allows callers to catch up on any events they missed while they weren't connected to the streaming RPC.
settle_indexuint64If specified (non-zero), then we'll first start by sending out notifications for all settled indexes with an settle_index greater than this value. This allows callers to catch up on any events they missed while they weren't connected to the streaming RPC.

LightningAddress

FieldTypeLabelDescription
pubkeystringThe identity pubkey of the Lightning node
hoststringThe network location of the lightning node, e.g. 69.69.69.69:1337 or localhost:10011

LightningNode

An individual vertex/node within the channel graph. A node is connected to other nodes by one or more channel edges emanating from it. As the graph is directed, a node will also have an incoming edge attached to it for each outgoing edge.

FieldTypeLabelDescription
last_updateuint32
pub_keystring
aliasstring
addressesNodeAddressrepeated
colorstring

ListChannelsRequest

FieldTypeLabelDescription
active_onlybool
inactive_onlybool
public_onlybool
private_onlybool

ListChannelsResponse

FieldTypeLabelDescription
channelsChannelrepeatedThe list of active channels

ListInvoiceRequest

FieldTypeLabelDescription
pending_onlyboolIf set, only unsettled invoices will be returned in the response.
index_offsetuint64The index of an invoice that will be used as either the start or end of a query to determine which invoices should be returned in the response.
num_max_invoicesuint64The max number of invoices to return in the response to this query.
reversedboolIf set, the invoices returned will result from seeking backwards from the specified index offset. This can be used to paginate backwards.

ListInvoiceResponse

FieldTypeLabelDescription
invoicesInvoicerepeatedA list of invoices from the time slice of the time series specified in the request.
last_index_offsetuint64The index of the last item in the set of returned invoices. This can be used to seek further, pagination style.
first_index_offsetuint64The index of the last item in the set of returned invoices. This can be used to seek backwards, pagination style.

ListPaymentsRequest

FieldTypeLabelDescription
include_incompleteboolIf true, then return payments that have not yet fully completed. This means that pending payments, as well as failed payments will show up if this field is set to True.

ListPaymentsResponse

FieldTypeLabelDescription
paymentsPaymentrepeatedThe list of payments

ListPeersRequest

ListPeersResponse

FieldTypeLabelDescription
peersPeerrepeatedThe list of currently connected peers

ListUnspentRequest

FieldTypeLabelDescription
min_confsint32The minimum number of confirmations to be included.
max_confsint32The maximum number of confirmations to be included.

ListUnspentResponse

FieldTypeLabelDescription
utxosUtxorepeatedA list of utxos

MultiChanBackup

FieldTypeLabelDescription
chan_pointsChannelPointrepeatedIs the set of all channels that are included in this multi-channel backup.
multi_chan_backupbytesA single encrypted blob containing all the static channel backups of the channel listed above. This can be stored as a single file or blob, and safely be replaced with any prior/future versions.

NetworkInfo

FieldTypeLabelDescription
graph_diameteruint32
avg_out_degreedouble
max_out_degreeuint32
num_nodesuint32
num_channelsuint32
total_network_capacityint64
avg_channel_sizedouble
min_channel_sizeint64
max_channel_sizeint64
median_channel_size_satint64
num_zombie_chansuint64The number of edges marked as zombies.

NetworkInfoRequest

NewAddressRequest

FieldTypeLabelDescription
typeAddressTypeThe address type

NewAddressResponse

FieldTypeLabelDescription
addressstringThe newly generated wallet address

NodeAddress

FieldTypeLabelDescription
networkstring
addrstring

NodeInfo

FieldTypeLabelDescription
nodeLightningNodeAn individual vertex/node within the channel graph. A node is connected to other nodes by one or more channel edges emanating from it. As the graph is directed, a node will also have an incoming edge attached to it for each outgoing edge.
num_channelsuint32The total number of channels for the node.
total_capacityint64The sum of all channels capacity for the node, denominated in satoshis.
channelsChannelEdgerepeatedA list of all public channels for the node.

NodeInfoRequest

FieldTypeLabelDescription
pub_keystringThe 33-byte hex-encoded compressed public of the target node
include_channelsboolIf true, will include all known channels associated with the node.

NodePair

FieldTypeLabelDescription
frombytesThe sending node of the pair.
tobytesThe receiving node of the pair.

NodeUpdate

FieldTypeLabelDescription
addressesstringrepeated
identity_keystring
global_featuresbytes
aliasstring
colorstring

OpenChannelRequest

FieldTypeLabelDescription
node_pubkeybytesThe pubkey of the node to open a channel with
node_pubkey_stringstringThe hex encoded pubkey of the node to open a channel with
local_funding_amountint64The number of satoshis the wallet should commit to the channel
push_satint64The number of satoshis to push to the remote side as part of the initial commitment state
target_confint32The target number of blocks that the funding transaction should be confirmed by.
sat_per_byteint64A manual fee rate set in sat/byte that should be used when crafting the funding transaction.
privateboolWhether this channel should be private, not announced to the greater network.
min_htlc_msatint64The minimum value in millisatoshi we will require for incoming HTLCs on the channel.
remote_csv_delayuint32The delay we require on the remote's commitment transaction. If this is not set, it will be scaled automatically with the channel size.
min_confsint32The minimum number of confirmations each one of your outputs used for the funding transaction must satisfy.
spend_unconfirmedboolWhether unconfirmed outputs should be used as inputs for the funding transaction.

OpenStatusUpdate

FieldTypeLabelDescription
chan_pendingPendingUpdate
chan_openChannelOpenUpdate

OutPoint

FieldTypeLabelDescription
txid_bytesbytesRaw bytes representing the transaction id.
txid_strstringReversed, hex-encoded string representing the transaction id.
output_indexuint32The index of the output on the transaction.

PayReq

FieldTypeLabelDescription
destinationstring
payment_hashstring
num_satoshisint64
timestampint64
expiryint64
descriptionstring
description_hashstring
fallback_addrstring
cltv_expiryint64
route_hintsRouteHintrepeated

PayReqString

FieldTypeLabelDescription
pay_reqstringThe payment request string to be decoded

Payment

FieldTypeLabelDescription
payment_hashstringThe payment hash
valueint64Deprecated, use value_sat or value_msat.
creation_dateint64The date of this payment
pathstringrepeatedThe path this payment took
feeint64Deprecated, use fee_sat or fee_msat.
payment_preimagestringThe payment preimage
value_satint64The value of the payment in satoshis
value_msatint64The value of the payment in milli-satoshis
payment_requeststringThe optional payment request being fulfilled.
statusPayment.PaymentStatusThe status of the payment.
fee_satint64The fee paid for this payment in satoshis
fee_msatint64The fee paid for this payment in milli-satoshis

PaymentHash

FieldTypeLabelDescription
r_hash_strstringThe hex-encoded payment hash of the invoice to be looked up. The passed payment hash must be exactly 32 bytes, otherwise an error is returned.
r_hashbytesThe payment hash of the invoice to be looked up.

Peer

FieldTypeLabelDescription
pub_keystringThe identity pubkey of the peer
addressstringNetwork address of the peer; eg 127.0.0.1:10011
bytes_sentuint64Bytes of data transmitted to this peer
bytes_recvuint64Bytes of data transmitted from this peer
sat_sentint64Satoshis sent to this peer
sat_recvint64Satoshis received from this peer
inboundboolA channel is inbound if the counterparty initiated the channel
ping_timeint64Ping time to this peer
sync_typePeer.SyncTypeThe type of sync we are currently performing with this peer.

PendingChannelsRequest

PendingChannelsResponse

FieldTypeLabelDescription
total_limbo_balanceint64The balance in satoshis encumbered in pending channels
pending_open_channelsPendingChannelsResponse.PendingOpenChannelrepeatedChannels pending opening
pending_closing_channelsPendingChannelsResponse.ClosedChannelrepeatedChannels pending closing
pending_force_closing_channelsPendingChannelsResponse.ForceClosedChannelrepeatedChannels pending force closing
waiting_close_channelsPendingChannelsResponse.WaitingCloseChannelrepeatedChannels waiting for closing tx to confirm

PendingChannelsResponse.ClosedChannel

FieldTypeLabelDescription
channelPendingChannelsResponse.PendingChannelThe pending channel to be closed
closing_txidstringThe transaction id of the closing transaction

PendingChannelsResponse.ForceClosedChannel

FieldTypeLabelDescription
channelPendingChannelsResponse.PendingChannelThe pending channel to be force closed
closing_txidstringThe transaction id of the closing transaction
limbo_balanceint64The balance in satoshis encumbered in this pending channel
maturity_heightuint32The height at which funds can be swept into the wallet
blocks_til_maturityint32Remaining # of blocks until the commitment output can be swept. Negative values indicate how many blocks have passed since becoming mature.
recovered_balanceint64The total value of funds successfully recovered from this channel
pending_htlcsPendingHTLCrepeated

PendingChannelsResponse.PendingChannel

FieldTypeLabelDescription
remote_node_pubstring
channel_pointstring
capacityint64
local_balanceint64
remote_balanceint64
local_chan_reserve_satint64The minimum satoshis this node is required to reserve in its balance.
remote_chan_reserve_satint64The minimum satoshis the other node is required to reserve in its balance.

PendingChannelsResponse.PendingOpenChannel

FieldTypeLabelDescription
channelPendingChannelsResponse.PendingChannelThe pending channel
confirmation_heightuint32The height at which this channel will be confirmed
commit_feeint64The amount calculated to be paid in fees for the current set of commitment transactions. The fee amount is persisted with the channel in order to allow the fee amount to be removed and recalculated with each channel state update, including updates that happen after a system restart.
commit_weightint64The weight of the commitment transaction
fee_per_kwint64The required number of satoshis per kilo-weight that the requester will pay at all times, for both the funding transaction and commitment transaction. This value can later be updated once the channel is open.

PendingChannelsResponse.WaitingCloseChannel

FieldTypeLabelDescription
channelPendingChannelsResponse.PendingChannelThe pending channel waiting for closing tx to confirm
limbo_balanceint64The balance in satoshis encumbered in this channel

PendingHTLC

FieldTypeLabelDescription
incomingboolThe direction within the channel that the htlc was sent
amountint64The total value of the htlc
outpointstringThe final output to be swept back to the user's wallet
maturity_heightuint32The next block height at which we can spend the current stage
blocks_til_maturityint32The number of blocks remaining until the current stage can be swept. Negative values indicate how many blocks have passed since becoming mature.
stageuint32Indicates whether the htlc is in its first or second stage of recovery

PendingUpdate

FieldTypeLabelDescription
txidbytes
output_indexuint32

PolicyUpdateRequest

FieldTypeLabelDescription
globalboolIf set, then this update applies to all currently active channels.
chan_pointChannelPointIf set, this update will target a specific channel.
base_fee_msatint64The base fee charged regardless of the number of milli-satoshis sent.
fee_ratedoubleThe effective fee rate in milli-satoshis. The precision of this value goes up to 6 decimal places, so 1e-6.
time_lock_deltauint32The required timelock delta for HTLCs forwarded over the channel.

PolicyUpdateResponse

QueryRoutesRequest

FieldTypeLabelDescription
pub_keystringThe 33-byte hex-encoded public key for the payment destination
amtint64The amount to send expressed in satoshis
final_cltv_deltaint32An optional CLTV delta from the current height that should be used for the timelock of the final hop
fee_limitFeeLimitThe maximum number of satoshis that will be paid as a fee of the payment. This value can be represented either as a percentage of the amount being sent, or as a fixed amount of the maximum fee the user is willing the pay to send the payment.
ignored_nodesbytesrepeatedA list of nodes to ignore during path finding.
ignored_edgesEdgeLocatorrepeatedDeprecated. A list of edges to ignore during path finding.
source_pub_keystringThe source node where the request route should originated from. If empty, self is assumed.
use_mission_controlboolIf set to true, edge probabilities from mission control will be used to get the optimal route.
ignored_pairsNodePairrepeatedA list of directed node pairs that will be ignored during path finding.
dest_tlvQueryRoutesRequest.DestTlvEntryrepeatedAn optional field that can be used to pass an arbitrary set of TLV records to a peer which understands the new records. This can be used to pass application specific data during the payment attempt. If the destination does not support the specified recrods, and error will be returned.

QueryRoutesRequest.DestTlvEntry

FieldTypeLabelDescription
keyuint64
valuebytes

QueryRoutesResponse

FieldTypeLabelDescription
routesRouterepeatedThe route that results from the path finding operation. This is still a repeated field to retain backwards compatibility.
success_probdoubleThe success probability of the returned route based on the current mission control state. [EXPERIMENTAL]

RestoreBackupResponse

RestoreChanBackupRequest

FieldTypeLabelDescription
chan_backupsChannelBackups
multi_chan_backupbytes

Route

A path through the channel graph which runs over one or more channels in succession. This struct carries all the information required to craft the Sphinx onion packet, and send the payment along the first hop in the path. A route is only selected as valid if all the channels have sufficient capacity to carry the initial payment amount after fees are accounted for.

FieldTypeLabelDescription
total_time_lockuint32The cumulative (final) time lock across the entire route. This is the CLTV value that should be extended to the first hop in the route. All other hops will decrement the time-lock as advertised, leaving enough time for all hops to wait for or present the payment preimage to complete the payment.
total_feesint64The sum of the fees paid at each hop within the final route. In the case of a one-hop payment, this value will be zero as we don't need to pay a fee to ourselves.
total_amtint64The total amount of funds required to complete a payment over this route. This value includes the cumulative fees at each hop. As a result, the HTLC extended to the first-hop in the route will need to have at least this many satoshis, otherwise the route will fail at an intermediate node due to an insufficient amount of fees.
hopsHoprepeatedContains details concerning the specific forwarding details at each hop.
total_fees_msatint64The total fees in millisatoshis.
total_amt_msatint64The total amount in millisatoshis.

RouteHint

FieldTypeLabelDescription
hop_hintsHopHintrepeatedA list of hop hints that when chained together can assist in reaching a specific destination.

RoutingPolicy

FieldTypeLabelDescription
time_lock_deltauint32
min_htlcint64
fee_base_msatint64
fee_rate_milli_msatint64
disabledbool
max_htlc_msatuint64
last_updateuint32

SendCoinsRequest

FieldTypeLabelDescription
addrstringThe address to send coins to
amountint64The amount in satoshis to send
target_confint32The target number of blocks that this transaction should be confirmed by.
sat_per_byteint64A manual fee rate set in sat/byte that should be used when crafting the transaction.
send_allboolIf set, then the amount field will be ignored, and lnd will attempt to send all the coins under control of the internal wallet to the specified address.

SendCoinsResponse

FieldTypeLabelDescription
txidstringThe transaction ID of the transaction

SendManyRequest

FieldTypeLabelDescription
AddrToAmountSendManyRequest.AddrToAmountEntryrepeatedThe map from addresses to amounts
target_confint32The target number of blocks that this transaction should be confirmed by.
sat_per_byteint64A manual fee rate set in sat/byte that should be used when crafting the transaction.

SendManyRequest.AddrToAmountEntry

FieldTypeLabelDescription
keystring
valueint64

SendManyResponse

FieldTypeLabelDescription
txidstringThe id of the transaction

SendRequest

FieldTypeLabelDescription
destbytesThe identity pubkey of the payment recipient
dest_stringstringThe hex-encoded identity pubkey of the payment recipient
amtint64Number of satoshis to send.
payment_hashbytesThe hash to use within the payment's HTLC
payment_hash_stringstringThe hex-encoded hash to use within the payment's HTLC
payment_requeststringA bare-bones invoice for a payment within the Lightning Network. With the details of the invoice, the sender has all the data necessary to send a payment to the recipient.
final_cltv_deltaint32The CLTV delta from the current height that should be used to set the timelock for the final hop.
fee_limitFeeLimitThe maximum number of satoshis that will be paid as a fee of the payment. This value can be represented either as a percentage of the amount being sent, or as a fixed amount of the maximum fee the user is willing the pay to send the payment.
outgoing_chan_iduint64The channel id of the channel that must be taken to the first hop. If zero, any channel may be used.
cltv_limituint32An optional maximum total time lock for the route. If zero, there is no maximum enforced.
dest_tlvSendRequest.DestTlvEntryrepeatedAn optional field that can be used to pass an arbitrary set of TLV records to a peer which understands the new records. This can be used to pass application specific data during the payment attempt.

SendRequest.DestTlvEntry

FieldTypeLabelDescription
keyuint64
valuebytes

SendResponse

FieldTypeLabelDescription
payment_errorstring
payment_preimagebytes
payment_routeRoute
payment_hashbytes

SendToRouteRequest

FieldTypeLabelDescription
payment_hashbytesThe payment hash to use for the HTLC.
payment_hash_stringstringAn optional hex-encoded payment hash to be used for the HTLC.
routeRouteRoute that should be used to attempt to complete the payment.

SignMessageRequest

FieldTypeLabelDescription
msgbytesThe message to be signed

SignMessageResponse

FieldTypeLabelDescription
signaturestringThe signature for the given message

StopRequest

StopResponse

Transaction

FieldTypeLabelDescription
tx_hashstringThe transaction hash
amountint64The transaction amount, denominated in satoshis
num_confirmationsint32The number of confirmations
block_hashstringThe hash of the block this transaction was included in
block_heightint32The height of the block this transaction was included in
time_stampint64Timestamp of this transaction
total_feesint64Fees paid for this transaction
dest_addressesstringrepeatedAddresses that received funds for this transaction
raw_tx_hexstringThe raw transaction hex.

TransactionDetails

FieldTypeLabelDescription
transactionsTransactionrepeatedThe list of transactions relevant to the wallet.

UnlockWalletRequest

FieldTypeLabelDescription
wallet_passwordbyteswallet_password should be the current valid passphrase for the daemon. This will be required to decrypt on-disk material that the daemon requires to function properly.
recovery_windowint32recovery_window is an optional argument specifying the address lookahead when restoring a wallet seed. The recovery window applies to each individual branch of the BIP44 derivation paths. Supplying a recovery window of zero indicates that no addresses should be recovered, such after the first initialization of the wallet.
channel_backupsChanBackupSnapshotchannel_backups is an optional argument that allows clients to recover the settled funds within a set of channels. This should be populated if the user was unable to close out all channels and sweep funds before partial or total data loss occurred. If specified, then after on-chain recovery of funds, lnd begin to carry out the data loss recovery protocol in order to recover the funds in each channel from a remote force closed transaction.

UnlockWalletResponse

Utxo

FieldTypeLabelDescription
typeAddressTypeThe type of address
addressstringThe address
amount_satint64The value of the unspent coin in satoshis
pk_scriptstringThe pkscript in hex
outpointOutPointThe outpoint in format txid:n
confirmationsint64The number of confirmations for the Utxo

VerifyChanBackupResponse

VerifyMessageRequest

FieldTypeLabelDescription
msgbytesThe message over which the signature is to be verified
signaturestringThe signature to be verified over the given message

VerifyMessageResponse

FieldTypeLabelDescription
validboolWhether the signature was valid over the given message
pubkeystringThe pubkey recovered from the signature

WalletBalanceRequest

WalletBalanceResponse

FieldTypeLabelDescription
total_balanceint64The balance of the wallet
confirmed_balanceint64The confirmed balance of a wallet(with >= 1 confirmations)
unconfirmed_balanceint64The unconfirmed balance of a wallet(with 0 confirmations)

AddressType

AddressType has to be one of:

  • p2wkh: Pay to witness key hash (WITNESS_PUBKEY_HASH = 0)
  • np2wkh: Pay to nested witness key hash (NESTED_PUBKEY_HASH = 1)
NameNumberDescription
WITNESS_PUBKEY_HASH0
NESTED_PUBKEY_HASH1
UNUSED_WITNESS_PUBKEY_HASH2
UNUSED_NESTED_PUBKEY_HASH3

ChannelCloseSummary.ClosureType

NameNumberDescription
COOPERATIVE_CLOSE0
LOCAL_FORCE_CLOSE1
REMOTE_FORCE_CLOSE2
BREACH_CLOSE3
FUNDING_CANCELED4
ABANDONED5

ChannelEventUpdate.UpdateType

NameNumberDescription
OPEN_CHANNEL0
CLOSED_CHANNEL1
ACTIVE_CHANNEL2
INACTIVE_CHANNEL3

Invoice.InvoiceState

NameNumberDescription
OPEN0
SETTLED1
CANCELED2
ACCEPTED3

InvoiceHTLCState

NameNumberDescription
ACCEPTED0
SETTLED1
CANCELLED2

Payment.PaymentStatus

NameNumberDescription
UNKNOWN0
IN_FLIGHT1
SUCCEEDED2
FAILED3

Peer.SyncType

NameNumberDescription
UNKNOWN_SYNC0Denotes that we cannot determine the peer's current sync type.
ACTIVE_SYNC1Denotes that we are actively receiving new graph updates from the peer.
PASSIVE_SYNC2Denotes that we are not receiving new graph updates from the peer.

Lightning

Method NameRequest TypeResponse TypeDescription
WalletBalanceWalletBalanceRequestWalletBalanceResponselncli: walletbalance WalletBalance returns total unspent outputs(confirmed and unconfirmed), all confirmed unspent outputs and all unconfirmed unspent outputs under control of the wallet.
ChannelBalanceChannelBalanceRequestChannelBalanceResponselncli: channelbalance ChannelBalance returns the total funds available across all open channels in satoshis.
GetTransactionsGetTransactionsRequestTransactionDetailslncli: listchaintxns GetTransactions returns a list describing all the known transactions relevant to the wallet.
EstimateFeeEstimateFeeRequestEstimateFeeResponselncli: estimatefee EstimateFee asks the chain backend to estimate the fee rate and total fees for a transaction that pays to multiple specified outputs.
SendCoinsSendCoinsRequestSendCoinsResponselncli: sendcoins SendCoins executes a request to send coins to a particular address. Unlike SendMany, this RPC call only allows creating a single output at a time. If neither target_conf, or sat_per_byte are set, then the internal wallet will consult its fee model to determine a fee for the default confirmation target.
ListUnspentListUnspentRequestListUnspentResponselncli: listunspent ListUnspent returns a list of all utxos spendable by the wallet with a number of confirmations between the specified minimum and maximum.
SubscribeTransactionsGetTransactionsRequestTransaction streamSubscribeTransactions creates a uni-directional stream from the server to the client in which any newly discovered transactions relevant to the wallet are sent over.
SendManySendManyRequestSendManyResponselncli: sendmany SendMany handles a request for a transaction that creates multiple specified outputs in parallel. If neither target_conf, or sat_per_byte are set, then the internal wallet will consult its fee model to determine a fee for the default confirmation target.
NewAddressNewAddressRequestNewAddressResponselncli: newaddress NewAddress creates a new address under control of the local wallet.
SignMessageSignMessageRequestSignMessageResponselncli: signmessage SignMessage signs a message with this node's private key. The returned signature string is zbase32 encoded and pubkey recoverable, meaning that only the message digest and signature are needed for verification.
VerifyMessageVerifyMessageRequestVerifyMessageResponselncli: verifymessage VerifyMessage verifies a signature over a msg. The signature must be zbase32 encoded and signed by an active node in the resident node's channel database. In addition to returning the validity of the signature, VerifyMessage also returns the recovered pubkey from the signature.
ConnectPeerConnectPeerRequestConnectPeerResponselncli: connect ConnectPeer attempts to establish a connection to a remote peer. This is at the networking level, and is used for communication between nodes. This is distinct from establishing a channel with a peer.
DisconnectPeerDisconnectPeerRequestDisconnectPeerResponselncli: disconnect DisconnectPeer attempts to disconnect one peer from another identified by a given pubKey. In the case that we currently have a pending or active channel with the target peer, then this action will be not be allowed.
ListPeersListPeersRequestListPeersResponselncli: listpeers ListPeers returns a verbose listing of all currently active peers.
GetInfoGetInfoRequestGetInfoResponselncli: getinfo GetInfo returns general information concerning the lightning node including it's identity pubkey, alias, the chains it is connected to, and information concerning the number of open+pending channels.
PendingChannelsPendingChannelsRequestPendingChannelsResponselncli: pendingchannels PendingChannels returns a list of all the channels that are currently considered "pending". A channel is pending if it has finished the funding workflow and is waiting for confirmations for the funding txn, or is in the process of closure, either initiated cooperatively or non-cooperatively.
ListChannelsListChannelsRequestListChannelsResponselncli: listchannels ListChannels returns a description of all the open channels that this node is a participant in.
SubscribeChannelEventsChannelEventSubscriptionChannelEventUpdate streamSubscribeChannelEvents creates a uni-directional stream from the server to the client in which any updates relevant to the state of the channels are sent over. Events include new active channels, inactive channels, and closed channels.
ClosedChannelsClosedChannelsRequestClosedChannelsResponselncli: closedchannels ClosedChannels returns a description of all the closed channels that this node was a participant in.
OpenChannelSyncOpenChannelRequestChannelPointOpenChannelSync is a synchronous version of the OpenChannel RPC call. This call is meant to be consumed by clients to the REST proxy. As with all other sync calls, all byte slices are intended to be populated as hex encoded strings.
OpenChannelOpenChannelRequestOpenStatusUpdate streamlncli: openchannel OpenChannel attempts to open a singly funded channel specified in the request to a remote peer. Users are able to specify a target number of blocks that the funding transaction should be confirmed in, or a manual fee rate to us for the funding transaction. If neither are specified, then a lax block confirmation target is used.
CloseChannelCloseChannelRequestCloseStatusUpdate streamlncli: closechannel CloseChannel attempts to close an active channel identified by its channel outpoint (ChannelPoint). The actions of this method can additionally be augmented to attempt a force close after a timeout period in the case of an inactive peer. If a non-force close (cooperative closure) is requested, then the user can specify either a target number of blocks until the closure transaction is confirmed, or a manual fee rate. If neither are specified, then a default lax, block confirmation target is used.
AbandonChannelAbandonChannelRequestAbandonChannelResponselncli: abandonchannel AbandonChannel removes all channel state from the database except for a close summary. This method can be used to get rid of permanently unusable channels due to bugs fixed in newer versions of lnd. Only available when in debug builds of lnd.
SendPaymentSendRequest streamSendResponse streamlncli: sendpayment SendPayment dispatches a bi-directional streaming RPC for sending payments through the Lightning Network. A single RPC invocation creates a persistent bi-directional stream allowing clients to rapidly send payments through the Lightning Network with a single persistent connection.
SendPaymentSyncSendRequestSendResponseSendPaymentSync is the synchronous non-streaming version of SendPayment. This RPC is intended to be consumed by clients of the REST proxy. Additionally, this RPC expects the destination's public key and the payment hash (if any) to be encoded as hex strings.
SendToRouteSendToRouteRequest streamSendResponse streamlncli: sendtoroute SendToRoute is a bi-directional streaming RPC for sending payment through the Lightning Network. This method differs from SendPayment in that it allows users to specify a full route manually. This can be used for things like rebalancing, and atomic swaps.
SendToRouteSyncSendToRouteRequestSendResponseSendToRouteSync is a synchronous version of SendToRoute. It Will block until the payment either fails or succeeds.
AddInvoiceInvoiceAddInvoiceResponselncli: addinvoice AddInvoice attempts to add a new invoice to the invoice database. Any duplicated invoices are rejected, therefore all invoices must have a unique payment preimage.
ListInvoicesListInvoiceRequestListInvoiceResponselncli: listinvoices ListInvoices returns a list of all the invoices currently stored within the database. Any active debug invoices are ignored. It has full support for paginated responses, allowing users to query for specific invoices through their add_index. This can be done by using either the first_index_offset or last_index_offset fields included in the response as the index_offset of the next request. By default, the first 100 invoices created will be returned. Backwards pagination is also supported through the Reversed flag.
LookupInvoicePaymentHashInvoicelncli: lookupinvoice LookupInvoice attempts to look up an invoice according to its payment hash. The passed payment hash must be exactly 32 bytes, if not, an error is returned.
SubscribeInvoicesInvoiceSubscriptionInvoice streamSubscribeInvoices returns a uni-directional stream (server -> client) for notifying the client of newly added/settled invoices. The caller can optionally specify the add_index and/or the settle_index. If the add_index is specified, then we'll first start by sending add invoice events for all invoices with an add_index greater than the specified value. If the settle_index is specified, the next, we'll send out all settle events for invoices with a settle_index greater than the specified value. One or both of these fields can be set. If no fields are set, then we'll only send out the latest add/settle events.
DecodePayReqPayReqStringPayReqlncli: decodepayreq DecodePayReq takes an encoded payment request string and attempts to decode it, returning a full description of the conditions encoded within the payment request.
ListPaymentsListPaymentsRequestListPaymentsResponselncli: listpayments ListPayments returns a list of all outgoing payments.
DeleteAllPaymentsDeleteAllPaymentsRequestDeleteAllPaymentsResponseDeleteAllPayments deletes all outgoing payments from DB.
DescribeGraphChannelGraphRequestChannelGraphlncli: describegraph DescribeGraph returns a description of the latest graph state from the point of view of the node. The graph information is partitioned into two components: all the nodes/vertexes, and all the edges that connect the vertexes themselves. As this is a directed graph, the edges also contain the node directional specific routing policy which includes: the time lock delta, fee information, etc.
GetChanInfoChanInfoRequestChannelEdgelncli: getchaninfo GetChanInfo returns the latest authenticated network announcement for the given channel identified by its channel ID: an 8-byte integer which uniquely identifies the location of transaction's funding output within the blockchain.
GetNodeInfoNodeInfoRequestNodeInfolncli: getnodeinfo GetNodeInfo returns the latest advertised, aggregated, and authenticated channel information for the specified node identified by its public key.
QueryRoutesQueryRoutesRequestQueryRoutesResponselncli: queryroutes QueryRoutes attempts to query the daemon's Channel Router for a possible route to a target destination capable of carrying a specific amount of satoshis. The returned route contains the full details required to craft and send an HTLC, also including the necessary information that should be present within the Sphinx packet encapsulated within the HTLC.
GetNetworkInfoNetworkInfoRequestNetworkInfolncli: getnetworkinfo GetNetworkInfo returns some basic stats about the known channel graph from the point of view of the node.
StopDaemonStopRequestStopResponselncli: stop StopDaemon will send a shutdown request to the interrupt handler, triggering a graceful shutdown of the daemon.
SubscribeChannelGraphGraphTopologySubscriptionGraphTopologyUpdate streamSubscribeChannelGraph launches a streaming RPC that allows the caller to receive notifications upon any changes to the channel graph topology from the point of view of the responding node. Events notified include: new nodes coming online, nodes updating their authenticated attributes, new channels being advertised, updates in the routing policy for a directional channel edge, and when channels are closed on-chain.
DebugLevelDebugLevelRequestDebugLevelResponselncli: debuglevel DebugLevel allows a caller to programmatically set the logging verbosity of lnd. The logging can be targeted according to a coarse daemon-wide logging level, or in a granular fashion to specify the logging for a target sub-system.
FeeReportFeeReportRequestFeeReportResponselncli: feereport FeeReport allows the caller to obtain a report detailing the current fee schedule enforced by the node globally for each channel.
UpdateChannelPolicyPolicyUpdateRequestPolicyUpdateResponselncli: updatechanpolicy UpdateChannelPolicy allows the caller to update the fee schedule and channel policies for all channels globally, or a particular channel.
ForwardingHistoryForwardingHistoryRequestForwardingHistoryResponselncli: fwdinghistory ForwardingHistory allows the caller to query the htlcswitch for a record of all HTLCs forwarded within the target time range, and integer offset within that time range. If no time-range is specified, then the first chunk of the past 24 hrs of forwarding history are returned.

A list of forwarding events are returned. The size of each forwarding event is 40 bytes, and the max message size able to be returned in gRPC is 4 MiB. As a result each message can only contain 50k entries. Each response has the index offset of the last entry. The index offset can be provided to the request to allow the caller to skip a series of records. | | ExportChannelBackup | ExportChannelBackupRequest | ChannelBackup | lncli: exportchanbackup ExportChannelBackup attempts to return an encrypted static channel backup for the target channel identified by it channel point. The backup is encrypted with a key generated from the aezeed seed of the user. The returned backup can either be restored using the RestoreChannelBackup method once lnd is running, or via the InitWallet and UnlockWallet methods from the WalletUnlocker service. | | ExportAllChannelBackups | ChanBackupExportRequest | ChanBackupSnapshot | ExportAllChannelBackups returns static channel backups for all existing channels known to lnd. A set of regular singular static channel backups for each channel are returned. Additionally, a multi-channel backup is returned as well, which contains a single encrypted blob containing the backups of each channel. | | VerifyChanBackup | ChanBackupSnapshot | VerifyChanBackupResponse | VerifyChanBackup allows a caller to verify the integrity of a channel backup snapshot. This method will accept either a packed Single or a packed Multi. Specifying both will result in an error. | | RestoreChannelBackups | RestoreChanBackupRequest | RestoreBackupResponse | lncli: restorechanbackup RestoreChannelBackups accepts a set of singular channel backups, or a single encrypted multi-chan backup and attempts to recover any funds remaining within the channel. If we are able to unpack the backup, then the new channel will be shown under listchannels, as well as pending channels. | | SubscribeChannelBackups | ChannelBackupSubscription | ChanBackupSnapshot stream | SubscribeChannelBackups allows a client to sub-subscribe to the most up to date information concerning the state of all channel backups. Each time a new channel is added, we return the new set of channels, along with a multi-chan backup containing the backup info for all channels. Each time a channel is closed, we send a new update, which contains new new chan back ups, but the updated set of encrypted multi-chan backups with the closed channel(s) removed. |

WalletUnlocker

The WalletUnlocker service is used to set up a wallet password for lnd at first startup, and unlock a previously set up wallet.

Method NameRequest TypeResponse TypeDescription
GenSeedGenSeedRequestGenSeedResponseGenSeed is the first method that should be used to instantiate a new lnd instance. This method allows a caller to generate a new aezeed cipher seed given an optional passphrase. If provided, the passphrase will be necessary to decrypt the cipherseed to expose the internal wallet seed.

Once the cipherseed is obtained and verified by the user, the InitWallet method should be used to commit the newly generated seed, and create the wallet. | | InitWallet | InitWalletRequest | InitWalletResponse | InitWallet is used when lnd is starting up for the first time to fully initialize the daemon and its internal wallet. At the very least a wallet password must be provided. This will be used to encrypt sensitive material on disk.

In the case of a recovery scenario, the user can also specify their aezeed mnemonic and passphrase. If set, then the daemon will use this prior state to initialize its internal wallet.

Alternatively, this can be used along with the GenSeed RPC to obtain a seed, then present it to the user. Once it has been verified by the user, the seed can be fed into this RPC in order to commit the new wallet. | | UnlockWallet | UnlockWalletRequest | UnlockWalletResponse | lncli: unlock UnlockWallet is used at startup of lnd to provide a password to unlock the wallet database. | | ChangePassword | ChangePasswordRequest | ChangePasswordResponse | lncli: changepassword ChangePassword changes the password of the encrypted wallet. This will automatically unlock the wallet database if successful. |

Top

wtclientrpc/wtclient.proto

AddTowerRequest

FieldTypeLabelDescription
pubkeybytesThe identifying public key of the watchtower to add.
addressstringA network address the watchtower is reachable over.

AddTowerResponse

GetTowerInfoRequest

FieldTypeLabelDescription
pubkeybytesThe identifying public key of the watchtower to retrieve information for.
include_sessionsboolWhether we should include sessions with the watchtower in the response.

ListTowersRequest

FieldTypeLabelDescription
include_sessionsboolWhether we should include sessions with the watchtower in the response.

ListTowersResponse

FieldTypeLabelDescription
towersTowerrepeatedThe list of watchtowers available for new backups.

PolicyRequest

PolicyResponse

FieldTypeLabelDescription
max_updatesuint32The maximum number of updates each session we negotiate with watchtowers should allow.
sweep_sat_per_byteuint32The fee rate, in satoshis per vbyte, that will be used by watchtowers for justice transactions in response to channel breaches.

RemoveTowerRequest

FieldTypeLabelDescription
pubkeybytesThe identifying public key of the watchtower to remove.
addressstringIf set, then the record for this address will be removed, indicating that is is stale. Otherwise, the watchtower will no longer be used for future session negotiations and backups.

RemoveTowerResponse

StatsRequest

StatsResponse

FieldTypeLabelDescription
num_backupsuint32The total number of backups made to all active and exhausted watchtower sessions.
num_pending_backupsuint32The total number of backups that are pending to be acknowledged by all active and exhausted watchtower sessions.
num_failed_backupsuint32The total number of backups that all active and exhausted watchtower sessions have failed to acknowledge.
num_sessions_acquireduint32The total number of new sessions made to watchtowers.
num_sessions_exhausteduint32The total number of watchtower sessions that have been exhausted.

Tower

FieldTypeLabelDescription
pubkeybytesThe identifying public key of the watchtower.
addressesstringrepeatedThe list of addresses the watchtower is reachable over.
active_session_candidateboolWhether the watchtower is currently a candidate for new sessions.
num_sessionsuint32The number of sessions that have been negotiated with the watchtower.
sessionsTowerSessionrepeatedThe list of sessions that have been negotiated with the watchtower.

TowerSession

FieldTypeLabelDescription
num_backupsuint32The total number of successful backups that have been made to the watchtower session.
num_pending_backupsuint32The total number of backups in the session that are currently pending to be acknowledged by the watchtower.
max_backupsuint32The maximum number of backups allowed by the watchtower session.
sweep_sat_per_byteuint32The fee rate, in satoshis per vbyte, that will be used by the watchtower for the justice transaction in the event of a channel breach.

WatchtowerClient

Method NameRequest TypeResponse TypeDescription
AddTowerAddTowerRequestAddTowerResponseAddTower adds a new watchtower reachable at the given address and considers it for new sessions. If the watchtower already exists, then any new addresses included will be considered when dialing it for session negotiations and backups.
RemoveTowerRemoveTowerRequestRemoveTowerResponseRemoveTower removes a watchtower from being considered for future session negotiations and from being used for any subsequent backups until it's added again. If an address is provided, then this RPC only serves as a way of removing the address from the watchtower instead.
ListTowersListTowersRequestListTowersResponseListTowers returns the list of watchtowers registered with the client.
GetTowerInfoGetTowerInfoRequestTowerGetTowerInfo retrieves information for a registered watchtower.
StatsStatsRequestStatsResponseStats returns the in-memory statistics of the client since startup.
PolicyPolicyRequestPolicyResponsePolicy returns the active watchtower client policy configuration.

Top

routerrpc/router.proto

ChannelUpdate

FieldTypeLabelDescription
signaturebytesThe signature that validates the announced data and proves the ownership of node id.
chain_hashbytesThe target chain that this channel was opened within. This value should be the genesis hash of the target chain. Along with the short channel ID, this uniquely identifies the channel globally in a blockchain.
chan_iduint64The unique description of the funding transaction.
timestampuint32A timestamp that allows ordering in the case of multiple announcements. We should ignore the message if timestamp is not greater than the last-received.
message_flagsuint32The bitfield that describes whether optional fields are present in this update. Currently, the least-significant bit must be set to 1 if the optional field MaxHtlc is present.
channel_flagsuint32The bitfield that describes additional meta-data concerning how the update is to be interpreted. Currently, the least-significant bit must be set to 0 if the creating node corresponds to the first node in the previously sent channel announcement and 1 otherwise. If the second bit is set, then the channel is set to be disabled.
time_lock_deltauint32The minimum number of blocks this node requires to be added to the expiry of HTLCs. This is a security parameter determined by the node operator. This value represents the required gap between the time locks of the incoming and outgoing HTLC's set to this node.
htlc_minimum_msatuint64The minimum HTLC value which will be accepted.
base_feeuint32The base fee that must be used for incoming HTLC's to this particular channel. This value will be tacked onto the required for a payment independent of the size of the payment.
fee_rateuint32The fee rate that will be charged per millionth of a satoshi.
htlc_maximum_msatuint64The maximum HTLC value which will be accepted.
extra_opaque_databytesThe set of data that was appended to this message, some of which we may not actually know how to iterate or parse. By holding onto this data, we ensure that we're able to properly validate the set of signatures that cover these new fields, and ensure we're able to make upgrades to the network in a forwards compatible manner.

Failure

FieldTypeLabelDescription
codeFailure.FailureCodeFailure code as defined in the Lightning spec
channel_updateChannelUpdateAn optional channel update message.
htlc_msatuint64A failure type-dependent htlc value.
onion_sha_256bytesThe sha256 sum of the onion payload.
cltv_expiryuint32A failure type-dependent cltv expiry value.
flagsuint32A failure type-dependent flags value.
failure_source_indexuint32The position in the path of the intermediate or final node that generated the failure message. Position zero is the sender node.

NodeHistory

NodeHistory contains the mission control state for a particular node.

FieldTypeLabelDescription
pubkeybytesNode pubkey
last_fail_timeint64Time stamp of last failure. Set to zero if no failure happened yet.
other_success_probfloatEstimation of success probability of forwarding towards peers of this node for which no specific history is available.

PairHistory

PairHistory contains the mission control state for a particular node pair.

FieldTypeLabelDescription
node_frombytesThe source node pubkey of the pair.
node_tobytesThe destination node pubkey of the pair.
timestampint64Time stamp of last result.
min_penalize_amt_satint64Minimum penalization amount (only applies to failed attempts).
success_probfloatEstimation of success probability for this pair.
last_attempt_successfulboolWhether the last payment attempt through this pair was successful.

PaymentStatus

FieldTypeLabelDescription
statePaymentStateCurrent state the payment is in.
preimagebytesThe pre-image of the payment when state is SUCCEEDED.
routelnrpc.RouteThe taken route when state is SUCCEEDED.

QueryMissionControlRequest

QueryMissionControlResponse

QueryMissionControlResponse contains mission control state.

FieldTypeLabelDescription
nodesNodeHistoryrepeatedNode-level mission control state.
pairsPairHistoryrepeatedNode pair-level mission control state.

ResetMissionControlRequest

ResetMissionControlResponse

RouteFeeRequest

FieldTypeLabelDescription
destbytesThe destination once wishes to obtain a routing fee quote to.
amt_satint64The amount one wishes to send to the target destination.

RouteFeeResponse

FieldTypeLabelDescription
routing_fee_msatint64A lower bound of the estimated fee to the target destination within the network, expressed in milli-satoshis.
time_lock_delayint64An estimate of the worst case time delay that can occur. Note that callers will still need to factor in the final CLTV delta of the last hop into this value.

SendPaymentRequest

FieldTypeLabelDescription
destbytesThe identity pubkey of the payment recipient
amtint64Number of satoshis to send.
payment_hashbytesThe hash to use within the payment's HTLC
final_cltv_deltaint32The CLTV delta from the current height that should be used to set the timelock for the final hop.
payment_requeststringA bare-bones invoice for a payment within the Lightning Network. With the details of the invoice, the sender has all the data necessary to send a payment to the recipient. The amount in the payment request may be zero. In that case it is required to set the amt field as well. If no payment request is specified, the following fields are required: dest, amt and payment_hash.
timeout_secondsint32An upper limit on the amount of time we should spend when attempting to fulfill the payment. This is expressed in seconds. If we cannot make a successful payment within this time frame, an error will be returned. This field must be non-zero.
fee_limit_satint64The maximum number of satoshis that will be paid as a fee of the payment. If this field is left to the default value of 0, only zero-fee routes will be considered. This usually means single hop routes connecting directly to the destination. To send the payment without a fee limit, use max int here.
outgoing_chan_iduint64The channel id of the channel that must be taken to the first hop. If zero, any channel may be used.
cltv_limitint32An optional maximum total time lock for the route. If zero, there is no maximum enforced.
route_hintslnrpc.RouteHintrepeatedOptional route hints to reach the destination through private channels.
dest_tlvSendPaymentRequest.DestTlvEntryrepeatedAn optional field that can be used to pass an arbitrary set of TLV records to a peer which understands the new records. This can be used to pass application specific data during the payment attempt.

SendPaymentRequest.DestTlvEntry

FieldTypeLabelDescription
keyuint64
valuebytes

SendToRouteRequest

FieldTypeLabelDescription
payment_hashbytesThe payment hash to use for the HTLC.
routelnrpc.RouteRoute that should be used to attempt to complete the payment.

SendToRouteResponse

FieldTypeLabelDescription
preimagebytesThe preimage obtained by making the payment.
failureFailureThe failure message in case the payment failed.

TrackPaymentRequest

FieldTypeLabelDescription
payment_hashbytesThe hash of the payment to look up.

Failure.FailureCode

NameNumberDescription
RESERVED0The numbers assigned in this enumeration match the failure codes as defined in BOLT #4. Because protobuf 3 requires enums to start with 0, a RESERVED value is added.
INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS1
INCORRECT_PAYMENT_AMOUNT2
FINAL_INCORRECT_CLTV_EXPIRY3
FINAL_INCORRECT_HTLC_AMOUNT4
FINAL_EXPIRY_TOO_SOON5
INVALID_REALM6
EXPIRY_TOO_SOON7
INVALID_ONION_VERSION8
INVALID_ONION_HMAC9
INVALID_ONION_KEY10
AMOUNT_BELOW_MINIMUM11
FEE_INSUFFICIENT12
INCORRECT_CLTV_EXPIRY13
CHANNEL_DISABLED14
TEMPORARY_CHANNEL_FAILURE15
REQUIRED_NODE_FEATURE_MISSING16
REQUIRED_CHANNEL_FEATURE_MISSING17
UNKNOWN_NEXT_PEER18
TEMPORARY_NODE_FAILURE19
PERMANENT_NODE_FAILURE20
PERMANENT_CHANNEL_FAILURE21
UNKNOWN_FAILURE998The error source is known, but the failure itself couldn't be decoded.
UNREADABLE_FAILURE999An unreadable failure result is returned if the received failure message cannot be decrypted. In that case the error source is unknown.

PaymentState

NameNumberDescription
IN_FLIGHT0Payment is still in flight.
SUCCEEDED1Payment completed successfully.
FAILED_TIMEOUT2There are more routes to try, but the payment timeout was exceeded.
FAILED_NO_ROUTE3All possible routes were tried and failed permanently. Or were no routes to the destination at all.
FAILED_ERROR4A non-recoverable error has occured.
FAILED_INCORRECT_PAYMENT_DETAILS5Payment details incorrect (unknown hash, invalid amt or invalid final cltv delta)

Router

Method NameRequest TypeResponse TypeDescription
SendPaymentSendPaymentRequestPaymentStatus streamSendPayment attempts to route a payment described by the passed PaymentRequest to the final destination. The call returns a stream of payment status updates.
TrackPaymentTrackPaymentRequestPaymentStatus streamTrackPayment returns an update stream for the payment identified by the payment hash.
EstimateRouteFeeRouteFeeRequestRouteFeeResponseEstimateRouteFee allows callers to obtain a lower bound w.r.t how much it may cost to send an HTLC to the target end destination.
SendToRouteSendToRouteRequestSendToRouteResponseSendToRoute attempts to make a payment via the specified route. This method differs from SendPayment in that it allows users to specify a full route manually. This can be used for things like rebalancing, and atomic swaps.
ResetMissionControlResetMissionControlRequestResetMissionControlResponseResetMissionControl clears all mission control state and starts with a clean slate.
QueryMissionControlQueryMissionControlRequestQueryMissionControlResponseQueryMissionControl exposes the internal mission control state to callers. It is a development feature.

Top

watchtowerrpc/watchtower.proto

GetInfoRequest

GetInfoResponse

FieldTypeLabelDescription
pubkeybytesThe public key of the watchtower.
listenersstringrepeatedThe listening addresses of the watchtower.
urisstringrepeatedThe URIs of the watchtower.

Watchtower

Method NameRequest TypeResponse TypeDescription
GetInfoGetInfoRequestGetInfoResponselncli: tower info GetInfo returns general information concerning the companion watchtower including it's public key and URIs where the server is currently listening for clients.

Top

signrpc/signer.proto

InputScript

FieldTypeLabelDescription
witnessbytesrepeatedThe serializes witness stack for the specified input.
sig_scriptbytesThe optional sig script for the specified witness that will only be set if the input specified is a nested p2sh witness program.

InputScriptResp

FieldTypeLabelDescription
input_scriptsInputScriptrepeatedThe set of fully valid input scripts requested.

KeyDescriptor

FieldTypeLabelDescription
raw_key_bytesbytesThe raw bytes of the key being identified. Either this or the KeyLocator must be specified.
key_locKeyLocatorThe key locator that identifies which key to use for signing. Either this or the raw bytes of the target key must be specified.

KeyLocator

FieldTypeLabelDescription
key_familyint32The family of key being identified.
key_indexint32The precise index of the key being identified.

SignDescriptor

FieldTypeLabelDescription
key_descKeyDescriptorA descriptor that precisely describes which key to use for signing. This may provide the raw public key directly, or require the Signer to re-derive the key according to the populated derivation path.
single_tweakbytesA scalar value that will be added to the private key corresponding to the above public key to obtain the private key to be used to sign this input. This value is typically derived via the following computation:

derivedKey = privkey + sha256(perCommitmentPoint || pubKey) mod N | | double_tweak | bytes | | A private key that will be used in combination with its corresponding private key to derive the private key that is to be used to sign the target input. Within the Lightning protocol, this value is typically the commitment secret from a previously revoked commitment transaction. This value is in combination with two hash values, and the original private key to derive the private key to be used when signing.

k = (privKeysha256(pubKey || tweakPub) + tweakPrivsha256(tweakPub || pubKey)) mod N | | witness_script | bytes | | The full script required to properly redeem the output. This field will only be populated if a p2wsh or a p2sh output is being signed. | | output | TxOut | | A description of the output being spent. The value and script MUST be provided. | | sighash | uint32 | | The target sighash type that should be used when generating the final sighash, and signature. | | input_index | int32 | | The target input within the transaction that should be signed. |

SignReq

FieldTypeLabelDescription
raw_tx_bytesbytesThe raw bytes of the transaction to be signed.
sign_descsSignDescriptorrepeatedA set of sign descriptors, for each input to be signed.

SignResp

FieldTypeLabelDescription
raw_sigsbytesrepeatedA set of signatures realized in a fixed 64-byte format ordered in ascending input order.

TxOut

FieldTypeLabelDescription
valueint64The value of the output being spent.
pk_scriptbytesThe script of the output being spent.

Signer

Method NameRequest TypeResponse TypeDescription
SignOutputRawSignReqSignRespSignOutputRaw is a method that can be used to generated a signature for a set of inputs/outputs to a transaction. Each request specifies details concerning how the outputs should be signed, which keys they should be signed with, and also any optional tweaks. The return value is a fixed 64-byte signature (the same format as we use on the wire in Lightning).

If we are unable to sign using the specified keys, then an error will be returned. | | ComputeInputScript | SignReq | InputScriptResp | ComputeInputScript generates a complete InputIndex for the passed transaction with the signature as defined within the passed SignDescriptor. This method should be capable of generating the proper input script for both regular p2wkh output and p2wkh outputs nested within a regular p2sh output.

Note that when using this method to sign inputs belonging to the wallet, the only items of the SignDescriptor that need to be populated are pkScript in the TxOut field, the value in that same field, and finally the input index. |

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── autopilotrpc
│   └── autopilot.proto
├── chainrpc
│   └── chainnotifier.proto
├── invoicesrpc
│   └── invoices.proto
├── routerrpc
│   └── router.proto
├── rpc.proto
├── signrpc
│   └── signer.proto
├── walletrpc
│   └── walletkit.proto
├── watchtowerrpc
│   └── watchtower.proto
└── wtclientrpc
    └── wtclient.proto

8 directories, 9 files

Protobuf sources

src:./chainrpc/chainnotifier.proto


syntax = "proto3";

package chainrpc;

message ConfRequest {
    /*
    The transaction hash for which we should request a confirmation notification
    for. If set to a hash of all zeros, then the confirmation notification will
    be requested for the script instead.
    */
    bytes txid = 1;

    /*
    An output script within a transaction with the hash above which will be used
    by light clients to match block filters. If the transaction hash is set to a
    hash of all zeros, then a confirmation notification will be requested for
    this script instead.
    */
    bytes script = 2;

    /*
    The number of desired confirmations the transaction/output script should
    reach before dispatching a confirmation notification.
    */
    uint32 num_confs = 3;

    /*
    The earliest height in the chain for which the transaction/output script
    could have been included in a block. This should in most cases be set to the
    broadcast height of the transaction/output script.
    */
    uint32 height_hint = 4;
}

message ConfDetails {
    // The raw bytes of the confirmed transaction.
    bytes raw_tx = 1;

    // The hash of the block in which the confirmed transaction was included in.
    bytes block_hash = 2;

    // The height of the block in which the confirmed transaction was included in.
    uint32 block_height = 3;

    // The index of the confirmed transaction within the transaction.
    uint32 tx_index = 4;
}

message Reorg {
    // TODO(wilmer): need to know how the client will use this first.
}

message ConfEvent {
    oneof event {
        /*
        An event that includes the confirmation details of the request
        (txid/ouput script).
        */
        ConfDetails conf = 1;

        /*
        An event send when the transaction of the request is reorged out of the
        chain.
        */
        Reorg reorg = 2;
    }
}

message Outpoint {
    // The hash of the transaction.
    bytes hash = 1;

    // The index of the output within the transaction.
    uint32 index = 2;
}

message SpendRequest {
    /*
    The outpoint for which we should request a spend notification for. If set to
    a zero outpoint, then the spend notification will be requested for the
    script instead.
    */
    Outpoint outpoint = 1;

    /*
    The output script for the outpoint above. This will be used by light clients
    to match block filters. If the outpoint is set to a zero outpoint, then a
    spend notification will be requested for this script instead.
    */
    bytes script = 2;

    /*
    The earliest height in the chain for which the outpoint/output script could
    have been spent. This should in most cases be set to the broadcast height of
    the outpoint/output script.
    */
    uint32 height_hint = 3;

    // TODO(wilmer): extend to support num confs on spending tx.
}

message SpendDetails {
    // The outpoint was that spent.
    Outpoint spending_outpoint = 1;

    // The raw bytes of the spending transaction.
    bytes raw_spending_tx = 2;

    // The hash of the spending transaction.
    bytes spending_tx_hash = 3;

    // The input of the spending transaction that fulfilled the spend request.
    uint32 spending_input_index = 4;

    // The height at which the spending transaction was included in a block.
    uint32 spending_height = 5;
}

message SpendEvent {
    oneof event {
        /*
        An event that includes the details of the spending transaction of the
        request (outpoint/output script).
        */
        SpendDetails spend = 1;

        /*
        An event sent when the spending transaction of the request was
        reorged out of the chain.
        */
        Reorg reorg = 2;
    }
}

message BlockEpoch {
    // The hash of the block.
    bytes hash = 1;

    // The height of the block.
    uint32 height = 2;
}

service ChainNotifier {
    /*
    RegisterConfirmationsNtfn is a synchronous response-streaming RPC that
    registers an intent for a client to be notified once a confirmation request
    has reached its required number of confirmations on-chain.

    A client can specify whether the confirmation request should be for a
    particular transaction by its hash or for an output script by specifying a
    zero hash.
    */
    rpc RegisterConfirmationsNtfn(ConfRequest) returns (stream ConfEvent);

    /*
    RegisterSpendNtfn is a synchronous response-streaming RPC that registers an
    intent for a client to be notification once a spend request has been spent
    by a transaction that has confirmed on-chain.

    A client can specify whether the spend request should be for a particular
    outpoint  or for an output script by specifying a zero outpoint.
    */
    rpc RegisterSpendNtfn(SpendRequest) returns (stream SpendEvent);

    /*
    RegisterBlockEpochNtfn is a synchronous response-streaming RPC that
    registers an intent for a client to be notified of blocks in the chain. The
    stream will return a hash and height tuple of a block for each new/stale
    block in the chain. It is the client's responsibility to determine whether
    the tuple returned is for a new or stale block in the chain.

    A client can also request a historical backlog of blocks from a particular
    point. This allows clients to be idempotent by ensuring that they do not
    missing processing a single block within the chain.
    */
    rpc RegisterBlockEpochNtfn(BlockEpoch) returns (stream BlockEpoch);
}

src:./walletrpc/walletkit.proto


syntax = "proto3";

import "rpc.proto";
import "signrpc/signer.proto";

package walletrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/walletrpc";

message KeyReq {
    /**
    Is the key finger print of the root pubkey that this request is targeting.
    This allows the WalletKit to possibly serve out keys for multiple HD chains
    via public derivation.
    */
    int32 key_finger_print = 1;

    /**
    The target key family to derive a key from. In other contexts, this is
    known as the "account".
    */
    int32 key_family = 2;
}

message AddrRequest{
    // No fields, as we always give out a p2wkh address.
}
message AddrResponse {
    /**
    The address encoded using a bech32 format.
    */
    string addr = 1;
}

message Transaction {
    /**
    The raw serialized transaction.
    */
    bytes tx_hex = 1;
}
message PublishResponse {
    /**
    If blank, then no error occurred and the transaction was successfully
    published. If not the empty string, then a string representation of the
    broadcast error.

    TODO(roasbeef): map to a proper enum type
    */
    string publish_error = 1;
}

message SendOutputsRequest {
    /**
    The number of satoshis per kilo weight that should be used when crafting
    this transaction.
    */
    int64 sat_per_kw = 1;

    /**
    A slice of the outputs that should be created in the transaction produced.
    */
    repeated signrpc.TxOut outputs = 2;
}
message SendOutputsResponse {
    /**
    The serialized transaction sent out on the network.
    */
    bytes raw_tx = 1;
}

message EstimateFeeRequest {
    /**
    The number of confirmations to shoot for when estimating the fee.
    */
    int32 conf_target = 1;
}
message EstimateFeeResponse {
    /**
    The amount of satoshis per kw that should be used in order to reach the
    confirmation target in the request.
    */
    int64 sat_per_kw = 1;
}

enum WitnessType {
    UNKNOWN_WITNESS = 0;

    /*
    A witness that allows us to spend the output of a commitment transaction
    after a relative lock-time lockout.
    */
    COMMITMENT_TIME_LOCK = 1;

    /*
    A witness that allows us to spend a settled no-delay output immediately on a
    counterparty's commitment transaction.
    */
    COMMITMENT_NO_DELAY = 2;

    /*
    A witness that allows us to sweep the settled output of a malicious
    counterparty's who broadcasts a revoked commitment transaction.
    */
    COMMITMENT_REVOKE = 3;

    /*
    A witness that allows us to sweep an HTLC which we offered to the remote
    party in the case that they broadcast a revoked commitment state.
    */
    HTLC_OFFERED_REVOKE = 4;

    /*
    A witness that allows us to sweep an HTLC output sent to us in the case that
    the remote party broadcasts a revoked commitment state.
    */
    HTLC_ACCEPTED_REVOKE = 5;

    /*
    A witness that allows us to sweep an HTLC output that we extended to a
    party, but was never fulfilled.  This HTLC output isn't directly on the
    commitment transaction, but is the result of a confirmed second-level HTLC
    transaction. As a result, we can only spend this after a CSV delay.
    */
    HTLC_OFFERED_TIMEOUT_SECOND_LEVEL = 6;

    /*
    A witness that allows us to sweep an HTLC output that was offered to us, and
    for which we have a payment preimage. This HTLC output isn't directly on our
    commitment transaction, but is the result of confirmed second-level HTLC
    transaction. As a result, we can only spend this after a CSV delay.
    */
    HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL = 7;

    /*
    A witness that allows us to sweep an HTLC that we offered to the remote
    party which lies in the commitment transaction of the remote party. We can
    spend this output after the absolute CLTV timeout of the HTLC as passed.
    */
    HTLC_OFFERED_REMOTE_TIMEOUT = 8;

    /*
    A witness that allows us to sweep an HTLC that was offered to us by the
    remote party. We use this witness in the case that the remote party goes to
    chain, and we know the pre-image to the HTLC. We can sweep this without any
    additional timeout.
    */
    HTLC_ACCEPTED_REMOTE_SUCCESS = 9;

    /*
    A witness that allows us to sweep an HTLC from the remote party's commitment
    transaction in the case that the broadcast a revoked commitment, but then
    also immediately attempt to go to the second level to claim the HTLC.
    */
    HTLC_SECOND_LEVEL_REVOKE = 10;

    /*
    A witness type that allows us to spend a regular p2wkh output that's sent to
    an output which is under complete control of the backing wallet.
    */
    WITNESS_KEY_HASH = 11;

    /*
    A witness type that allows us to sweep an output that sends to a nested P2SH
    script that pays to a key solely under our control.
    */
    NESTED_WITNESS_KEY_HASH = 12;
}

message PendingSweep {
    // The outpoint of the output we're attempting to sweep.
    lnrpc.OutPoint outpoint = 1 [json_name = "outpoint"];

    // The witness type of the output we're attempting to sweep.
    WitnessType witness_type = 2 [json_name = "witness_type"];

    // The value of the output we're attempting to sweep.
    uint32 amount_sat = 3 [json_name = "amount_sat"];

    /*
    The fee rate we'll use to sweep the output. The fee rate is only determined
    once a sweeping transaction for the output is created, so it's possible for
    this to be 0 before this.
    */
    uint32 sat_per_byte = 4 [json_name = "sat_per_byte"];

    // The number of broadcast attempts we've made to sweep the output.
    uint32 broadcast_attempts = 5 [json_name = "broadcast_attempts"];

    /*
    The next height of the chain at which we'll attempt to broadcast the
    sweep transaction of the output.
    */
    uint32 next_broadcast_height = 6 [json_name = "next_broadcast_height"];
}

message PendingSweepsRequest {
}

message PendingSweepsResponse {
    /*
    The set of outputs currently being swept by lnd's central batching engine.
    */
    repeated PendingSweep pending_sweeps = 1 [json_name = "pending_sweeps"];
}

message BumpFeeRequest {
    // The input we're attempting to bump the fee of.
    lnrpc.OutPoint outpoint = 1 [json_name = "outpoint"];

    // The target number of blocks that the input should be spent within.
    uint32 target_conf = 2 [json_name = "target_conf"];

    /*
    The fee rate, expressed in sat/byte, that should be used to spend the input
    with.
    */
    uint32 sat_per_byte = 3 [json_name = "sat_per_byte"];
}

message BumpFeeResponse {
}

service WalletKit {
    /**
    DeriveNextKey attempts to derive the *next* key within the key family
    (account in BIP43) specified. This method should return the next external
    child within this branch.
    */
    rpc DeriveNextKey(KeyReq) returns (signrpc.KeyDescriptor);

    /**
    DeriveKey attempts to derive an arbitrary key specified by the passed
    KeyLocator. 
    */
    rpc DeriveKey(signrpc.KeyLocator) returns (signrpc.KeyDescriptor);

    /**
    NextAddr returns the next unused address within the wallet.
    */
    rpc NextAddr(AddrRequest) returns (AddrResponse);

    /**
    PublishTransaction attempts to publish the passed transaction to the
    network. Once this returns without an error, the wallet will continually
    attempt to re-broadcast the transaction on start up, until it enters the
    chain.
    */
    rpc PublishTransaction(Transaction) returns (PublishResponse);

    /**
    SendOutputs is similar to the existing sendmany call in Bitcoind, and
    allows the caller to create a transaction that sends to several outputs at
    once. This is ideal when wanting to batch create a set of transactions.
    */
    rpc SendOutputs(SendOutputsRequest) returns (SendOutputsResponse);

    /**
    EstimateFee attempts to query the internal fee estimator of the wallet to
    determine the fee (in sat/kw) to attach to a transaction in order to
    achieve the confirmation target.
    */
    rpc EstimateFee(EstimateFeeRequest) returns (EstimateFeeResponse);

    /*
    PendingSweeps returns lists of on-chain outputs that lnd is currently
    attempting to sweep within its central batching engine. Outputs with similar
    fee rates are batched together in order to sweep them within a single
    transaction.

    NOTE: Some of the fields within PendingSweepsRequest are not guaranteed to
    remain supported. This is an advanced API that depends on the internals of
    the UtxoSweeper, so things may change.
    */
    rpc PendingSweeps(PendingSweepsRequest) returns (PendingSweepsResponse);

    /*
    BumpFee bumps the fee of an arbitrary input within a transaction. This RPC
    takes a different approach than bitcoind's bumpfee command. lnd has a
    central batching engine in which inputs with similar fee rates are batched
    together to save on transaction fees. Due to this, we cannot rely on
    bumping the fee on a specific transaction, since transactions can change at
    any point with the addition of new inputs. The list of inputs that
    currently exist within lnd's central batching engine can be retrieved
    through the PendingSweeps RPC.

    When bumping the fee of an input that currently exists within lnd's central
    batching engine, a higher fee transaction will be created that replaces the
    lower fee transaction through the Replace-By-Fee (RBF) policy. If it

    This RPC also serves useful when wanting to perform a Child-Pays-For-Parent
    (CPFP), where the child transaction pays for its parent's fee. This can be
    done by specifying an outpoint within the low fee transaction that is under
    the control of the wallet.

    The fee preference can be expressed either as a specific fee rate or a delta
    of blocks in which the output should be swept on-chain within. If a fee
    preference is not explicitly specified, then an error is returned.

    Note that this RPC currently doesn't perform any validation checks on the
    fee preference being provided. For now, the responsibility of ensuring that
    the new fee preference is sufficient is delegated to the user.
    */
    rpc BumpFee(BumpFeeRequest) returns (BumpFeeResponse);
}

src:./autopilotrpc/autopilot.proto


syntax = "proto3";

package autopilotrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/autopilotrpc";

// Autopilot is a service that can be used to get information about the current
// state of the daemon's autopilot agent, and also supply it with information
// that can be used when deciding where to open channels.
service Autopilot {
    /**
    Status returns whether the daemon's autopilot agent is active.
    */
    rpc Status(StatusRequest) returns (StatusResponse);

    /**
    ModifyStatus is used to modify the status of the autopilot agent, like
    enabling or disabling it.
    */
    rpc ModifyStatus(ModifyStatusRequest) returns (ModifyStatusResponse);

    /**
    QueryScores queries all available autopilot heuristics, in addition to any
    active combination of these heruristics, for the scores they would give to
    the given nodes.
    */
    rpc QueryScores(QueryScoresRequest) returns (QueryScoresResponse);

    /**
    SetScores attempts to set the scores used by the running autopilot agent,
    if the external scoring heuristic is enabled.
    */
    rpc SetScores(SetScoresRequest) returns (SetScoresResponse);
}

message StatusRequest{
}

message StatusResponse{
    /// Indicates whether the autopilot is active or not.
    bool active = 1 [json_name = "active"];
}

message ModifyStatusRequest{
    /// Whether the autopilot agent should be enabled or not.
    bool enable = 1 [json_name = "enable"];
}

message ModifyStatusResponse {}

message QueryScoresRequest{
    repeated string pubkeys = 1 [json_name = "pubkeys"];

    /// If set, we will ignore the local channel state when calculating scores.
    bool ignore_local_state = 2 [json_name = "no_state"];
}

message QueryScoresResponse {
    message HeuristicResult {
        string heuristic = 1 [json_name = "heuristic"];
        map<string, double> scores= 2 [json_name = "scores"];
    }

    repeated HeuristicResult results = 1 [json_name = "results"];
}

message SetScoresRequest{
    /// The name of the heuristic to provide scores to.
    string heuristic = 1 [json_name = "heuristic"];

    /**
    A map from hex-encoded public keys to scores. Scores must be in the range
    [0.0, 1.0].
    */
    map<string, double> scores = 2 [json_name = "scores"];
}

message SetScoresResponse {}

src:./invoicesrpc/invoices.proto


syntax = "proto3";

import "google/api/annotations.proto";
import "rpc.proto";

package invoicesrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc";

// Invoices is a service that can be used to create, accept, settle and cancel
// invoices.
service Invoices {
    /**
    SubscribeSingleInvoice returns a uni-directional stream (server -> client)
    to notify the client of state transitions of the specified invoice.
    Initially the current invoice state is always sent out.
    */
    rpc SubscribeSingleInvoice (SubscribeSingleInvoiceRequest) returns (stream lnrpc.Invoice);

    /**
    CancelInvoice cancels a currently open invoice. If the invoice is already 
    canceled, this call will succeed. If the invoice is already settled, it will
    fail.
    */
    rpc CancelInvoice(CancelInvoiceMsg) returns (CancelInvoiceResp);

    /**
    AddHoldInvoice creates a hold invoice. It ties the invoice to the hash
    supplied in the request.
    */
    rpc AddHoldInvoice(AddHoldInvoiceRequest) returns (AddHoldInvoiceResp);
 
    /**
    SettleInvoice settles an accepted invoice. If the invoice is already
    settled, this call will succeed.
    */
    rpc SettleInvoice(SettleInvoiceMsg) returns (SettleInvoiceResp);
}

message CancelInvoiceMsg {
    /// Hash corresponding to the (hold) invoice to cancel.
    bytes payment_hash = 1;
} 
message CancelInvoiceResp {}

message AddHoldInvoiceRequest {
    /**
    An optional memo to attach along with the invoice. Used for record keeping
    purposes for the invoice's creator, and will also be set in the description
    field of the encoded payment request if the description_hash field is not
    being used.
    */
    string memo = 1 [json_name = "memo"];

    /// The hash of the preimage
    bytes hash = 2 [json_name = "hash"];

    /// The value of this invoice in satoshis
    int64 value = 3 [json_name = "value"];

    /**
    Hash (SHA-256) of a description of the payment. Used if the description of
    payment (memo) is too long to naturally fit within the description field
    of an encoded payment request.
    */
    bytes description_hash = 4 [json_name = "description_hash"];

    /// Payment request expiry time in seconds. Default is 3600 (1 hour).
    int64 expiry = 5 [json_name = "expiry"];

    /// Fallback on-chain address.
    string fallback_addr = 6 [json_name = "fallback_addr"];

    /// Delta to use for the time-lock of the CLTV extended to the final hop.
    uint64 cltv_expiry = 7 [json_name = "cltv_expiry"];

    /**
    Route hints that can each be individually used to assist in reaching the
    invoice's destination.
    */
    repeated lnrpc.RouteHint route_hints = 8 [json_name = "route_hints"];

    /// Whether this invoice should include routing hints for private channels.
    bool private = 9 [json_name = "private"];
}

message AddHoldInvoiceResp {
    /**
    A bare-bones invoice for a payment within the Lightning Network.  With the
    details of the invoice, the sender has all the data necessary to send a
    payment to the recipient.
    */
    string payment_request = 1 [json_name = "payment_request"];
}

message SettleInvoiceMsg {
    /// Externally discovered pre-image that should be used to settle the hold invoice.
    bytes preimage = 1;
} 

message SettleInvoiceResp {}

message SubscribeSingleInvoiceRequest {
    reserved 1;

    /// Hash corresponding to the (hold) invoice to subscribe to.
    bytes r_hash = 2 [json_name = "r_hash"];
}

src:./rpc.proto


syntax = "proto3";

import "google/api/annotations.proto";

package lnrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc";

/**
 * Comments in this file will be directly parsed into the API
 * Documentation as descriptions of the associated method, message, or field.
 * These descriptions should go right above the definition of the object, and
 * can be in either block or /// comment format. 
 * 
 * One edge case exists where a // comment followed by a /// comment in the
 * next line will cause the description not to show up in the documentation. In
 * that instance, simply separate the two comments with a blank line.
 * 
 * An RPC method can be matched to an lncli command by placing a line in the
 * beginning of the description in exactly the following format:
 * lncli: `methodname`
 * 
 * Failure to specify the exact name of the command will cause documentation
 * generation to fail.
 * 
 * More information on how exactly the gRPC documentation is generated from
 * this proto file can be found here:
 * https://github.com/lightninglabs/lightning-api
 */

// The WalletUnlocker service is used to set up a wallet password for
// lnd at first startup, and unlock a previously set up wallet.
service WalletUnlocker {
    /**
    GenSeed is the first method that should be used to instantiate a new lnd
    instance. This method allows a caller to generate a new aezeed cipher seed
    given an optional passphrase. If provided, the passphrase will be necessary
    to decrypt the cipherseed to expose the internal wallet seed.

    Once the cipherseed is obtained and verified by the user, the InitWallet
    method should be used to commit the newly generated seed, and create the
    wallet.
    */
    rpc GenSeed(GenSeedRequest) returns (GenSeedResponse) {
        option (google.api.http) = {
            get: "/v1/genseed"
        };
    }

    /** 
    InitWallet is used when lnd is starting up for the first time to fully
    initialize the daemon and its internal wallet. At the very least a wallet
    password must be provided. This will be used to encrypt sensitive material
    on disk.

    In the case of a recovery scenario, the user can also specify their aezeed
    mnemonic and passphrase. If set, then the daemon will use this prior state
    to initialize its internal wallet.

    Alternatively, this can be used along with the GenSeed RPC to obtain a
    seed, then present it to the user. Once it has been verified by the user,
    the seed can be fed into this RPC in order to commit the new wallet.
    */
    rpc InitWallet(InitWalletRequest) returns (InitWalletResponse) {
        option (google.api.http) = {
            post: "/v1/initwallet"
            body: "*"
        };
    }

    /** lncli: `unlock`
    UnlockWallet is used at startup of lnd to provide a password to unlock
    the wallet database.
    */
    rpc UnlockWallet(UnlockWalletRequest) returns (UnlockWalletResponse) {
        option (google.api.http) = {
            post: "/v1/unlockwallet"
            body: "*"
        };
    }

    /** lncli: `changepassword`
    ChangePassword changes the password of the encrypted wallet. This will
    automatically unlock the wallet database if successful.
    */
    rpc ChangePassword (ChangePasswordRequest) returns (ChangePasswordResponse) {
        option (google.api.http) = {
            post: "/v1/changepassword"
            body: "*"
        };
    }
}

message GenSeedRequest {
    /**
    aezeed_passphrase is an optional user provided passphrase that will be used
    to encrypt the generated aezeed cipher seed.
    */
    bytes aezeed_passphrase = 1;

    /**
    seed_entropy is an optional 16-bytes generated via CSPRNG. If not
    specified, then a fresh set of randomness will be used to create the seed.
    */
    bytes seed_entropy = 2;
}
message GenSeedResponse {
    /**
    cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
    cipher seed obtained by the user. This field is optional, as if not
    provided, then the daemon will generate a new cipher seed for the user.
    Otherwise, then the daemon will attempt to recover the wallet state linked
    to this cipher seed.
    */
    repeated string cipher_seed_mnemonic = 1;

    /**
    enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
    cipher text before run through our mnemonic encoding scheme.
    */
    bytes enciphered_seed = 2;
}

message InitWalletRequest {
    /**
    wallet_password is the passphrase that should be used to encrypt the
    wallet. This MUST be at least 8 chars in length. After creation, this
    password is required to unlock the daemon.
    */
    bytes wallet_password = 1;

    /**
    cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
    cipher seed obtained by the user. This may have been generated by the
    GenSeed method, or be an existing seed.
    */
    repeated string cipher_seed_mnemonic = 2;

    /**
    aezeed_passphrase is an optional user provided passphrase that will be used
    to encrypt the generated aezeed cipher seed.
    */
    bytes aezeed_passphrase = 3;

    /**
    recovery_window is an optional argument specifying the address lookahead
    when restoring a wallet seed. The recovery window applies to each
    individual branch of the BIP44 derivation paths. Supplying a recovery
    window of zero indicates that no addresses should be recovered, such after
    the first initialization of the wallet.
    */
    int32 recovery_window = 4;

    /**
    channel_backups is an optional argument that allows clients to recover the
    settled funds within a set of channels. This should be populated if the
    user was unable to close out all channels and sweep funds before partial or
    total data loss occurred. If specified, then after on-chain recovery of
    funds, lnd begin to carry out the data loss recovery protocol in order to
    recover the funds in each channel from a remote force closed transaction.
    */
    ChanBackupSnapshot channel_backups = 5;
}
message InitWalletResponse {
}

message UnlockWalletRequest {
    /**
    wallet_password should be the current valid passphrase for the daemon. This
    will be required to decrypt on-disk material that the daemon requires to
    function properly.
    */
    bytes wallet_password = 1;

    /**
    recovery_window is an optional argument specifying the address lookahead
    when restoring a wallet seed. The recovery window applies to each
    individual branch of the BIP44 derivation paths. Supplying a recovery
    window of zero indicates that no addresses should be recovered, such after
    the first initialization of the wallet.
    */
    int32 recovery_window = 2;

    /**
    channel_backups is an optional argument that allows clients to recover the
    settled funds within a set of channels. This should be populated if the
    user was unable to close out all channels and sweep funds before partial or
    total data loss occurred. If specified, then after on-chain recovery of
    funds, lnd begin to carry out the data loss recovery protocol in order to
    recover the funds in each channel from a remote force closed transaction.
    */
    ChanBackupSnapshot channel_backups = 3;
}
message UnlockWalletResponse {}

message ChangePasswordRequest {
    /**
    current_password should be the current valid passphrase used to unlock the
    daemon.
    */
    bytes current_password = 1;

    /**
    new_password should be the new passphrase that will be needed to unlock the
    daemon.
    */
    bytes new_password = 2;
}
message ChangePasswordResponse {}

service Lightning {
    /** lncli: `walletbalance`
    WalletBalance returns total unspent outputs(confirmed and unconfirmed), all
    confirmed unspent outputs and all unconfirmed unspent outputs under control
    of the wallet.
    */
    rpc WalletBalance (WalletBalanceRequest) returns (WalletBalanceResponse) {
        option (google.api.http) = {
            get: "/v1/balance/blockchain"
        };
    }

    /** lncli: `channelbalance`
    ChannelBalance returns the total funds available across all open channels
    in satoshis.
    */
    rpc ChannelBalance (ChannelBalanceRequest) returns (ChannelBalanceResponse) {
        option (google.api.http) = {
            get: "/v1/balance/channels"
        };
    }

    /** lncli: `listchaintxns`
    GetTransactions returns a list describing all the known transactions
    relevant to the wallet.
    */
    rpc GetTransactions (GetTransactionsRequest) returns (TransactionDetails) {
        option (google.api.http) = {
            get: "/v1/transactions"
        };
    }

    /** lncli: `estimatefee`
    EstimateFee asks the chain backend to estimate the fee rate and total fees
    for a transaction that pays to multiple specified outputs.
    */
    rpc EstimateFee (EstimateFeeRequest) returns (EstimateFeeResponse) {
        option (google.api.http) = {
            get: "/v1/transactions/fee"
        };
    }

    /** lncli: `sendcoins`
    SendCoins executes a request to send coins to a particular address. Unlike
    SendMany, this RPC call only allows creating a single output at a time. If
    neither target_conf, or sat_per_byte are set, then the internal wallet will
    consult its fee model to determine a fee for the default confirmation
    target.
    */
    rpc SendCoins (SendCoinsRequest) returns (SendCoinsResponse) {
        option (google.api.http) = {
            post: "/v1/transactions"
            body: "*"
        };
    }

    /** lncli: `listunspent`
    ListUnspent returns a list of all utxos spendable by the wallet with a
	number of confirmations between the specified minimum and maximum.
    */
    rpc ListUnspent (ListUnspentRequest) returns (ListUnspentResponse) {
        option (google.api.http) = {
            get: "/v1/utxos"
        };
    }

    /**
    SubscribeTransactions creates a uni-directional stream from the server to
    the client in which any newly discovered transactions relevant to the
    wallet are sent over.
    */
    rpc SubscribeTransactions (GetTransactionsRequest) returns (stream Transaction);

    /** lncli: `sendmany`
    SendMany handles a request for a transaction that creates multiple specified
    outputs in parallel. If neither target_conf, or sat_per_byte are set, then
    the internal wallet will consult its fee model to determine a fee for the
    default confirmation target.
    */
    rpc SendMany (SendManyRequest) returns (SendManyResponse);

    /** lncli: `newaddress`
    NewAddress creates a new address under control of the local wallet.
    */
    rpc NewAddress (NewAddressRequest) returns (NewAddressResponse) {
        option (google.api.http) = {
            get: "/v1/newaddress"
        };
    }

    /** lncli: `signmessage`
    SignMessage signs a message with this node's private key. The returned
    signature string is `zbase32` encoded and pubkey recoverable, meaning that
    only the message digest and signature are needed for verification.
    */
    rpc SignMessage (SignMessageRequest) returns (SignMessageResponse) {
        option (google.api.http) = {
            post: "/v1/signmessage"
            body: "*"
        };
    }

    /** lncli: `verifymessage`
    VerifyMessage verifies a signature over a msg. The signature must be
    zbase32 encoded and signed by an active node in the resident node's
    channel database. In addition to returning the validity of the signature,
    VerifyMessage also returns the recovered pubkey from the signature.
    */
    rpc VerifyMessage (VerifyMessageRequest) returns (VerifyMessageResponse) {
        option (google.api.http) = {
            post: "/v1/verifymessage"
            body: "*"
        };
    }

    /** lncli: `connect`
    ConnectPeer attempts to establish a connection to a remote peer. This is at
    the networking level, and is used for communication between nodes. This is
    distinct from establishing a channel with a peer.
    */
    rpc ConnectPeer (ConnectPeerRequest) returns (ConnectPeerResponse) {
        option (google.api.http) = {
            post: "/v1/peers"
            body: "*"
        };
    }

    /** lncli: `disconnect`
    DisconnectPeer attempts to disconnect one peer from another identified by a
    given pubKey. In the case that we currently have a pending or active channel
    with the target peer, then this action will be not be allowed.
    */
    rpc DisconnectPeer (DisconnectPeerRequest) returns (DisconnectPeerResponse) {
        option (google.api.http) = {
            delete: "/v1/peers/{pub_key}"
        };
    }

    /** lncli: `listpeers`
    ListPeers returns a verbose listing of all currently active peers.
    */
    rpc ListPeers (ListPeersRequest) returns (ListPeersResponse) {
        option (google.api.http) = {
            get: "/v1/peers"
        };
    }

    /** lncli: `getinfo`
    GetInfo returns general information concerning the lightning node including
    it's identity pubkey, alias, the chains it is connected to, and information
    concerning the number of open+pending channels.
    */
    rpc GetInfo (GetInfoRequest) returns (GetInfoResponse) {
        option (google.api.http) = {
            get: "/v1/getinfo"
        };
    }

    // TODO(roasbeef): merge with below with bool?
    /** lncli: `pendingchannels`
    PendingChannels returns a list of all the channels that are currently
    considered "pending". A channel is pending if it has finished the funding
    workflow and is waiting for confirmations for the funding txn, or is in the
    process of closure, either initiated cooperatively or non-cooperatively.
    */
    rpc PendingChannels (PendingChannelsRequest) returns (PendingChannelsResponse) {
        option (google.api.http) = {
           get: "/v1/channels/pending"
        };
    }

    /** lncli: `listchannels`
    ListChannels returns a description of all the open channels that this node
    is a participant in.
    */
    rpc ListChannels (ListChannelsRequest) returns (ListChannelsResponse) {
        option (google.api.http) = {
            get: "/v1/channels"
        };
    }

    /**
    SubscribeChannelEvents creates a uni-directional stream from the server to
    the client in which any updates relevant to the state of the channels are
    sent over. Events include new active channels, inactive channels, and closed
    channels.
    */
    rpc SubscribeChannelEvents (ChannelEventSubscription) returns (stream ChannelEventUpdate);

    /** lncli: `closedchannels`
    ClosedChannels returns a description of all the closed channels that
    this node was a participant in.
    */
    rpc ClosedChannels (ClosedChannelsRequest) returns (ClosedChannelsResponse) {
        option (google.api.http) = {
            get: "/v1/channels/closed"
        };
    }


    /**
    OpenChannelSync is a synchronous version of the OpenChannel RPC call. This
    call is meant to be consumed by clients to the REST proxy. As with all
    other sync calls, all byte slices are intended to be populated as hex
    encoded strings.
    */
    rpc OpenChannelSync (OpenChannelRequest) returns (ChannelPoint) {
        option (google.api.http) = {
            post: "/v1/channels"
            body: "*"
        };
    }

    /** lncli: `openchannel`
    OpenChannel attempts to open a singly funded channel specified in the
    request to a remote peer. Users are able to specify a target number of
    blocks that the funding transaction should be confirmed in, or a manual fee
    rate to us for the funding transaction. If neither are specified, then a
    lax block confirmation target is used.
    */
    rpc OpenChannel (OpenChannelRequest) returns (stream OpenStatusUpdate);

    /** lncli: `closechannel`
    CloseChannel attempts to close an active channel identified by its channel
    outpoint (ChannelPoint). The actions of this method can additionally be
    augmented to attempt a force close after a timeout period in the case of an
    inactive peer. If a non-force close (cooperative closure) is requested,
    then the user can specify either a target number of blocks until the
    closure transaction is confirmed, or a manual fee rate. If neither are
    specified, then a default lax, block confirmation target is used.
    */
    rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) {
        option (google.api.http) = {
            delete: "/v1/channels/{channel_point.funding_txid_str}/{channel_point.output_index}"
        };
    }

    /** lncli: `abandonchannel`
    AbandonChannel removes all channel state from the database except for a
    close summary. This method can be used to get rid of permanently unusable
    channels due to bugs fixed in newer versions of lnd. Only available
    when in debug builds of lnd.
    */
    rpc AbandonChannel (AbandonChannelRequest) returns (AbandonChannelResponse) {
        option (google.api.http) = {
            delete: "/v1/channels/abandon/{channel_point.funding_txid_str}/{channel_point.output_index}"
        };
    }


    /** lncli: `sendpayment`
    SendPayment dispatches a bi-directional streaming RPC for sending payments
    through the Lightning Network. A single RPC invocation creates a persistent
    bi-directional stream allowing clients to rapidly send payments through the
    Lightning Network with a single persistent connection.
    */
    rpc SendPayment (stream SendRequest) returns (stream SendResponse);

    /**
    SendPaymentSync is the synchronous non-streaming version of SendPayment.
    This RPC is intended to be consumed by clients of the REST proxy.
    Additionally, this RPC expects the destination's public key and the payment
    hash (if any) to be encoded as hex strings.
    */
    rpc SendPaymentSync (SendRequest) returns (SendResponse) {
        option (google.api.http) = {
            post: "/v1/channels/transactions"
            body: "*"
        };
    }

    /** lncli: `sendtoroute`
    SendToRoute is a bi-directional streaming RPC for sending payment through
    the Lightning Network. This method differs from SendPayment in that it
    allows users to specify a full route manually. This can be used for things
    like rebalancing, and atomic swaps.
    */
    rpc SendToRoute(stream SendToRouteRequest) returns (stream SendResponse);

    /**
    SendToRouteSync is a synchronous version of SendToRoute. It Will block
    until the payment either fails or succeeds.
    */
    rpc SendToRouteSync (SendToRouteRequest) returns (SendResponse) {
        option (google.api.http) = {
            post: "/v1/channels/transactions/route"
            body: "*"
        };
    }

    /** lncli: `addinvoice`
    AddInvoice attempts to add a new invoice to the invoice database. Any
    duplicated invoices are rejected, therefore all invoices *must* have a
    unique payment preimage.
    */
    rpc AddInvoice (Invoice) returns (AddInvoiceResponse) {
        option (google.api.http) = {
            post: "/v1/invoices"
            body: "*"
        };
    }

    /** lncli: `listinvoices`
    ListInvoices returns a list of all the invoices currently stored within the
    database. Any active debug invoices are ignored. It has full support for
    paginated responses, allowing users to query for specific invoices through
    their add_index. This can be done by using either the first_index_offset or
    last_index_offset fields included in the response as the index_offset of the
    next request. By default, the first 100 invoices created will be returned.
    Backwards pagination is also supported through the Reversed flag.
    */
    rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) {
        option (google.api.http) = {
            get: "/v1/invoices"
        };
    }

    /** lncli: `lookupinvoice`
    LookupInvoice attempts to look up an invoice according to its payment hash.
    The passed payment hash *must* be exactly 32 bytes, if not, an error is
    returned.
    */
    rpc LookupInvoice (PaymentHash) returns (Invoice) {
        option (google.api.http) = {
            get: "/v1/invoice/{r_hash_str}"
        };
    }

    /**
    SubscribeInvoices returns a uni-directional stream (server -> client) for
    notifying the client of newly added/settled invoices. The caller can
    optionally specify the add_index and/or the settle_index. If the add_index
    is specified, then we'll first start by sending add invoice events for all
    invoices with an add_index greater than the specified value.  If the
    settle_index is specified, the next, we'll send out all settle events for
    invoices with a settle_index greater than the specified value.  One or both
    of these fields can be set. If no fields are set, then we'll only send out
    the latest add/settle events.
    */
    rpc SubscribeInvoices (InvoiceSubscription) returns (stream Invoice) {
        option (google.api.http) = {
            get: "/v1/invoices/subscribe"
        };
    }

    /** lncli: `decodepayreq`
    DecodePayReq takes an encoded payment request string and attempts to decode
    it, returning a full description of the conditions encoded within the
    payment request.
    */
    rpc DecodePayReq (PayReqString) returns (PayReq) {
        option (google.api.http) = {
            get: "/v1/payreq/{pay_req}"
        };
    }

    /** lncli: `listpayments`
    ListPayments returns a list of all outgoing payments.
    */
    rpc ListPayments (ListPaymentsRequest) returns (ListPaymentsResponse) {
        option (google.api.http) = {
            get: "/v1/payments"
        };
    };

    /**
    DeleteAllPayments deletes all outgoing payments from DB.
    */
    rpc DeleteAllPayments (DeleteAllPaymentsRequest) returns (DeleteAllPaymentsResponse) {
        option (google.api.http) = {
            delete: "/v1/payments"
        };
    };

    /** lncli: `describegraph`
    DescribeGraph returns a description of the latest graph state from the
    point of view of the node. The graph information is partitioned into two
    components: all the nodes/vertexes, and all the edges that connect the
    vertexes themselves.  As this is a directed graph, the edges also contain
    the node directional specific routing policy which includes: the time lock
    delta, fee information, etc.
    */
    rpc DescribeGraph (ChannelGraphRequest) returns (ChannelGraph) {
        option (google.api.http) = {
            get: "/v1/graph"
        };
    }

    /** lncli: `getchaninfo`
    GetChanInfo returns the latest authenticated network announcement for the
    given channel identified by its channel ID: an 8-byte integer which
    uniquely identifies the location of transaction's funding output within the
    blockchain.
    */
    rpc GetChanInfo (ChanInfoRequest) returns (ChannelEdge) {
        option (google.api.http) = {
            get: "/v1/graph/edge/{chan_id}"
        };
    }

    /** lncli: `getnodeinfo`
    GetNodeInfo returns the latest advertised, aggregated, and authenticated
    channel information for the specified node identified by its public key.
    */
    rpc GetNodeInfo (NodeInfoRequest) returns (NodeInfo) {
        option (google.api.http) = {
            get: "/v1/graph/node/{pub_key}"
        };
    }

    /** lncli: `queryroutes`
    QueryRoutes attempts to query the daemon's Channel Router for a possible
    route to a target destination capable of carrying a specific amount of
    satoshis. The returned route contains the full details required to craft and
    send an HTLC, also including the necessary information that should be
    present within the Sphinx packet encapsulated within the HTLC.
    */
    rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) {
        option (google.api.http) = {
            get: "/v1/graph/routes/{pub_key}/{amt}"
        };
    }

    /** lncli: `getnetworkinfo`
    GetNetworkInfo returns some basic stats about the known channel graph from
    the point of view of the node.
    */
    rpc GetNetworkInfo (NetworkInfoRequest) returns (NetworkInfo) {
        option (google.api.http) = {
            get: "/v1/graph/info"
        };
    }

    /** lncli: `stop`
    StopDaemon will send a shutdown request to the interrupt handler, triggering
    a graceful shutdown of the daemon.
    */
    rpc StopDaemon(StopRequest) returns (StopResponse);

    /**
    SubscribeChannelGraph launches a streaming RPC that allows the caller to
    receive notifications upon any changes to the channel graph topology from
    the point of view of the responding node. Events notified include: new
    nodes coming online, nodes updating their authenticated attributes, new
    channels being advertised, updates in the routing policy for a directional
    channel edge, and when channels are closed on-chain.
    */
    rpc SubscribeChannelGraph(GraphTopologySubscription) returns (stream GraphTopologyUpdate);

    /** lncli: `debuglevel`
    DebugLevel allows a caller to programmatically set the logging verbosity of
    lnd. The logging can be targeted according to a coarse daemon-wide logging
    level, or in a granular fashion to specify the logging for a target
    sub-system.
    */
    rpc DebugLevel (DebugLevelRequest) returns (DebugLevelResponse);

    /** lncli: `feereport`
    FeeReport allows the caller to obtain a report detailing the current fee
    schedule enforced by the node globally for each channel.
    */
    rpc FeeReport(FeeReportRequest) returns (FeeReportResponse) {
        option (google.api.http) = {
            get: "/v1/fees"
        };
    }

    /** lncli: `updatechanpolicy`
    UpdateChannelPolicy allows the caller to update the fee schedule and
    channel policies for all channels globally, or a particular channel.
    */
    rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) {
        option (google.api.http) = {
            post: "/v1/chanpolicy"
            body: "*"
        };
    }

    /** lncli: `fwdinghistory`
    ForwardingHistory allows the caller to query the htlcswitch for a record of
    all HTLCs forwarded within the target time range, and integer offset
    within that time range. If no time-range is specified, then the first chunk
    of the past 24 hrs of forwarding history are returned.

    A list of forwarding events are returned. The size of each forwarding event
    is 40 bytes, and the max message size able to be returned in gRPC is 4 MiB.
    As a result each message can only contain 50k entries.  Each response has
    the index offset of the last entry. The index offset can be provided to the
    request to allow the caller to skip a series of records.
    */
    rpc ForwardingHistory(ForwardingHistoryRequest) returns (ForwardingHistoryResponse) {
        option (google.api.http) = {
            post: "/v1/switch"
            body: "*"
        };
    };

    /** lncli: `exportchanbackup`
    ExportChannelBackup attempts to return an encrypted static channel backup
    for the target channel identified by it channel point. The backup is
    encrypted with a key generated from the aezeed seed of the user. The
    returned backup can either be restored using the RestoreChannelBackup
    method once lnd is running, or via the InitWallet and UnlockWallet methods
    from the WalletUnlocker service.
    */
    rpc ExportChannelBackup(ExportChannelBackupRequest) returns (ChannelBackup) {
        option (google.api.http) = {
            get: "/v1/channels/backup/{chan_point.funding_txid_str}/{chan_point.output_index}"
        };
    };

    /**
    ExportAllChannelBackups returns static channel backups for all existing
    channels known to lnd. A set of regular singular static channel backups for
    each channel are returned. Additionally, a multi-channel backup is returned
    as well, which contains a single encrypted blob containing the backups of
    each channel.
    */
    rpc ExportAllChannelBackups(ChanBackupExportRequest) returns (ChanBackupSnapshot) {
        option (google.api.http) = {
            get: "/v1/channels/backup"
        };
    };

    /**
    VerifyChanBackup allows a caller to verify the integrity of a channel backup
    snapshot. This method will accept either a packed Single or a packed Multi.
    Specifying both will result in an error.
    */
    rpc VerifyChanBackup(ChanBackupSnapshot) returns (VerifyChanBackupResponse) {
        option (google.api.http) = {
            post: "/v1/channels/backup/verify"
            body: "*"
        };
    };

    /** lncli: `restorechanbackup`
    RestoreChannelBackups accepts a set of singular channel backups, or a
    single encrypted multi-chan backup and attempts to recover any funds
    remaining within the channel. If we are able to unpack the backup, then the
    new channel will be shown under listchannels, as well as pending channels.
    */
    rpc RestoreChannelBackups(RestoreChanBackupRequest) returns (RestoreBackupResponse)  {
        option (google.api.http) = {
            post: "/v1/channels/backup/restore"
            body: "*"
        };
    };

    /**
    SubscribeChannelBackups allows a client to sub-subscribe to the most up to
    date information concerning the state of all channel backups. Each time a
    new channel is added, we return the new set of channels, along with a
    multi-chan backup containing the backup info for all channels. Each time a
    channel is closed, we send a new update, which contains new new chan back
    ups, but the updated set of encrypted multi-chan backups with the closed
    channel(s) removed.
    */
    rpc SubscribeChannelBackups(ChannelBackupSubscription) returns (stream ChanBackupSnapshot) {
    };
}

message Utxo {
    /// The type of address
    AddressType type = 1 [json_name = "address_type"];

    /// The address
    string address = 2 [json_name = "address"];

    /// The value of the unspent coin in satoshis
    int64 amount_sat = 3 [json_name = "amount_sat"];

    /// The pkscript in hex
    string pk_script = 4 [json_name = "pk_script"];

    /// The outpoint in format txid:n
    OutPoint outpoint = 5 [json_name = "outpoint"];

    /// The number of confirmations for the Utxo
    int64 confirmations = 6 [json_name = "confirmations"];
}

message Transaction {
    /// The transaction hash
    string tx_hash = 1 [ json_name = "tx_hash" ];

    /// The transaction amount, denominated in satoshis
    int64 amount = 2 [ json_name = "amount" ];

    /// The number of confirmations
    int32 num_confirmations = 3 [ json_name = "num_confirmations" ];

    /// The hash of the block this transaction was included in
    string block_hash = 4 [ json_name = "block_hash" ];

    /// The height of the block this transaction was included in
    int32 block_height = 5 [ json_name = "block_height" ];

    /// Timestamp of this transaction 
    int64 time_stamp = 6 [ json_name = "time_stamp" ];

    /// Fees paid for this transaction
    int64 total_fees = 7 [ json_name = "total_fees" ];

    /// Addresses that received funds for this transaction
    repeated string dest_addresses = 8 [ json_name = "dest_addresses" ];

    /// The raw transaction hex.
    string raw_tx_hex = 9 [ json_name = "raw_tx_hex" ];
}
message GetTransactionsRequest {
}
message TransactionDetails {
    /// The list of transactions relevant to the wallet.
    repeated Transaction transactions = 1 [json_name = "transactions"];
}

message FeeLimit {
    oneof limit {
        /// The fee limit expressed as a fixed amount of satoshis.
        int64 fixed = 1;

        /// The fee limit expressed as a percentage of the payment amount.
        int64 percent = 2;
    }
}

message SendRequest {
    /// The identity pubkey of the payment recipient
    bytes dest = 1;

    /// The hex-encoded identity pubkey of the payment recipient
    string dest_string = 2;

    /// Number of satoshis to send.
    int64 amt = 3;

    /// The hash to use within the payment's HTLC
    bytes payment_hash = 4;

    /// The hex-encoded hash to use within the payment's HTLC
    string payment_hash_string = 5;

    /**
    A bare-bones invoice for a payment within the Lightning Network.  With the
    details of the invoice, the sender has all the data necessary to send a
    payment to the recipient.
    */
    string payment_request = 6;

    /**
    The CLTV delta from the current height that should be used to set the
    timelock for the final hop.
    */
    int32 final_cltv_delta = 7;

    /**
    The maximum number of satoshis that will be paid as a fee of the payment.
    This value can be represented either as a percentage of the amount being
    sent, or as a fixed amount of the maximum fee the user is willing the pay to
    send the payment.
    */
    FeeLimit fee_limit = 8;

    /**
    The channel id of the channel that must be taken to the first hop. If zero,
    any channel may be used.
    */
    uint64 outgoing_chan_id = 9;

    /** 
    An optional maximum total time lock for the route. If zero, there is no
    maximum enforced.
    */
    uint32 cltv_limit = 10;

    /** 
    An optional field that can be used to pass an arbitrary set of TLV records
    to a peer which understands the new records. This can be used to pass
    application specific data during the payment attempt.
    */
    map<uint64, bytes> dest_tlv = 11;
}

message SendResponse {
    string payment_error = 1 [json_name = "payment_error"];
    bytes payment_preimage = 2 [json_name = "payment_preimage"];
    Route payment_route = 3 [json_name = "payment_route"];
    bytes payment_hash = 4 [json_name = "payment_hash"];
}

message SendToRouteRequest {
    /// The payment hash to use for the HTLC.
    bytes payment_hash = 1;

    /// An optional hex-encoded payment hash to be used for the HTLC.
    string payment_hash_string = 2;

    reserved 3;

    /// Route that should be used to attempt to complete the payment.
    Route route = 4;
}

message ChannelPoint {
    oneof funding_txid {
        /// Txid of the funding transaction
        bytes funding_txid_bytes = 1 [json_name = "funding_txid_bytes"];

        /// Hex-encoded string representing the funding transaction
        string funding_txid_str = 2 [json_name = "funding_txid_str"];
    }

    /// The index of the output of the funding transaction
    uint32 output_index = 3 [json_name = "output_index"];
}

message OutPoint {
    /// Raw bytes representing the transaction id.
    bytes txid_bytes = 1 [json_name = "txid_bytes"];

    /// Reversed, hex-encoded string representing the transaction id.
    string txid_str = 2 [json_name = "txid_str"];

    /// The index of the output on the transaction.
    uint32 output_index = 3 [json_name = "output_index"];
}

message LightningAddress {
    /// The identity pubkey of the Lightning node
    string pubkey = 1 [json_name = "pubkey"];

    /// The network location of the lightning node, e.g. `69.69.69.69:1337` or `localhost:10011`
    string host = 2 [json_name = "host"];
}

message EstimateFeeRequest {
    /// The map from addresses to amounts for the transaction.
    map<string, int64> AddrToAmount = 1;

    /// The target number of blocks that this transaction should be confirmed by.
    int32 target_conf = 2;
}

message EstimateFeeResponse {
    /// The total fee in satoshis.
    int64 fee_sat = 1 [json_name = "fee_sat"];

    /// The fee rate in satoshi/byte.
    int64 feerate_sat_per_byte = 2 [json_name = "feerate_sat_per_byte"];
}

message SendManyRequest {
    /// The map from addresses to amounts
    map<string, int64> AddrToAmount = 1;

    /// The target number of blocks that this transaction should be confirmed by.
    int32 target_conf = 3;

    /// A manual fee rate set in sat/byte that should be used when crafting the transaction.
    int64 sat_per_byte = 5;
}
message SendManyResponse {
    /// The id of the transaction
    string txid = 1 [json_name = "txid"];
}

message SendCoinsRequest {
    /// The address to send coins to 
    string addr = 1;

    /// The amount in satoshis to send
    int64 amount = 2;

    /// The target number of blocks that this transaction should be confirmed by.
    int32 target_conf = 3;

    /// A manual fee rate set in sat/byte that should be used when crafting the transaction.
    int64 sat_per_byte = 5;

    /**
    If set, then the amount field will be ignored, and lnd will attempt to
    send all the coins under control of the internal wallet to the specified
    address.
    */
    bool send_all = 6; 
}
message SendCoinsResponse {
    /// The transaction ID of the transaction
    string txid = 1 [json_name = "txid"];
}

message ListUnspentRequest {
    /// The minimum number of confirmations to be included.
    int32 min_confs = 1;

    /// The maximum number of confirmations to be included.
    int32 max_confs = 2;
}
message ListUnspentResponse {
    /// A list of utxos
    repeated Utxo utxos = 1 [json_name = "utxos"];
}

/** 
`AddressType` has to be one of:

- `p2wkh`: Pay to witness key hash (`WITNESS_PUBKEY_HASH` = 0)
- `np2wkh`: Pay to nested witness key hash (`NESTED_PUBKEY_HASH` = 1)
*/
enum AddressType {
        WITNESS_PUBKEY_HASH = 0;
        NESTED_PUBKEY_HASH = 1;
        UNUSED_WITNESS_PUBKEY_HASH = 2;
        UNUSED_NESTED_PUBKEY_HASH = 3;
}

message NewAddressRequest {
    /// The address type
    AddressType type = 1;
}
message NewAddressResponse {
    /// The newly generated wallet address
    string address = 1 [json_name = "address"];
}

message SignMessageRequest {
    /// The message to be signed
    bytes msg = 1 [ json_name = "msg" ];
}
message SignMessageResponse {
    /// The signature for the given message
    string signature = 1 [ json_name = "signature" ];
}

message VerifyMessageRequest {
    /// The message over which the signature is to be verified
    bytes msg = 1 [ json_name = "msg" ];

    /// The signature to be verified over the given message
    string signature = 2 [ json_name = "signature" ];
}
message VerifyMessageResponse {
    /// Whether the signature was valid over the given message
    bool valid = 1 [ json_name = "valid" ];

    /// The pubkey recovered from the signature
    string pubkey = 2 [ json_name = "pubkey" ];
}

message ConnectPeerRequest {
    /// Lightning address of the peer, in the format `<pubkey>@host`
    LightningAddress addr = 1;

    /** If set, the daemon will attempt to persistently connect to the target
     * peer.  Otherwise, the call will be synchronous. */
    bool perm = 2;
}
message ConnectPeerResponse {
}

message DisconnectPeerRequest {
    /// The pubkey of the node to disconnect from
    string pub_key = 1 [json_name = "pub_key"];
}
message DisconnectPeerResponse {
}

message HTLC {
    bool incoming = 1 [json_name = "incoming"];
    int64 amount = 2 [json_name = "amount"];
    bytes hash_lock = 3 [json_name = "hash_lock"];
    uint32 expiration_height = 4 [json_name = "expiration_height"];
}

message Channel {
    /// Whether this channel is active or not
    bool active = 1 [json_name = "active"];

    /// The identity pubkey of the remote node
    string remote_pubkey = 2 [json_name = "remote_pubkey"];

    /**
    The outpoint (txid:index) of the funding transaction. With this value, Bob
    will be able to generate a signature for Alice's version of the commitment
    transaction.
    */
    string channel_point = 3 [json_name = "channel_point"];

    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 chan_id = 4 [json_name = "chan_id"];

    /// The total amount of funds held in this channel
    int64 capacity = 5 [json_name = "capacity"];

    /// This node's current balance in this channel
    int64 local_balance = 6 [json_name = "local_balance"];

    /// The counterparty's current balance in this channel
    int64 remote_balance = 7 [json_name = "remote_balance"];

    /**
    The amount calculated to be paid in fees for the current set of commitment
    transactions. The fee amount is persisted with the channel in order to
    allow the fee amount to be removed and recalculated with each channel state
    update, including updates that happen after a system restart.
    */
    int64 commit_fee = 8 [json_name = "commit_fee"];

    /// The weight of the commitment transaction
    int64 commit_weight = 9 [json_name = "commit_weight"];

    /**
    The required number of satoshis per kilo-weight that the requester will pay
    at all times, for both the funding transaction and commitment transaction.
    This value can later be updated once the channel is open.
    */
    int64 fee_per_kw = 10 [json_name = "fee_per_kw"];

    /// The unsettled balance in this channel
    int64 unsettled_balance = 11 [json_name = "unsettled_balance"];

    /**
    The total number of satoshis we've sent within this channel.
    */
    int64 total_satoshis_sent = 12 [json_name = "total_satoshis_sent"];

    /**
    The total number of satoshis we've received within this channel.
    */
    int64 total_satoshis_received = 13 [json_name = "total_satoshis_received"];

    /**
    The total number of updates conducted within this channel.
    */
    uint64 num_updates = 14 [json_name = "num_updates"];

    /**
    The list of active, uncleared HTLCs currently pending within the channel.
    */
    repeated HTLC pending_htlcs = 15 [json_name = "pending_htlcs"];

    /**
    The CSV delay expressed in relative blocks. If the channel is force closed,
    we will need to wait for this many blocks before we can regain our funds.
    */
    uint32 csv_delay = 16 [json_name = "csv_delay"];

    /// Whether this channel is advertised to the network or not.
    bool private = 17 [json_name = "private"];

    /// True if we were the ones that created the channel.
    bool initiator = 18 [json_name = "initiator"];

    /// A set of flags showing the current state of the channel.
    string chan_status_flags = 19 [json_name = "chan_status_flags"];

    /// The minimum satoshis this node is required to reserve in its balance.
    int64 local_chan_reserve_sat = 20 [json_name = "local_chan_reserve_sat"];

    /**
    The minimum satoshis the other node is required to reserve in its balance.
    */
    int64 remote_chan_reserve_sat = 21 [json_name = "remote_chan_reserve_sat"];
}


message ListChannelsRequest {
    bool active_only = 1;
    bool inactive_only = 2;
    bool public_only = 3;
    bool private_only = 4;
}
message ListChannelsResponse {
    /// The list of active channels
    repeated Channel channels = 11 [json_name = "channels"];
}

message ChannelCloseSummary {
    /// The outpoint (txid:index) of the funding transaction. 
    string channel_point = 1 [json_name = "channel_point"];

    ///  The unique channel ID for the channel. 
    uint64 chan_id = 2 [json_name = "chan_id"];

    /// The hash of the genesis block that this channel resides within.
    string chain_hash = 3 [json_name = "chain_hash"];

    /// The txid of the transaction which ultimately closed this channel.
    string closing_tx_hash = 4 [json_name = "closing_tx_hash"];

    /// Public key of the remote peer that we formerly had a channel with.
    string remote_pubkey = 5 [json_name = "remote_pubkey"];

    /// Total capacity of the channel.
    int64 capacity = 6 [json_name = "capacity"];

    /// Height at which the funding transaction was spent.
    uint32 close_height = 7 [json_name = "close_height"];

    /// Settled balance at the time of channel closure
    int64 settled_balance = 8 [json_name = "settled_balance"];

    /// The sum of all the time-locked outputs at the time of channel closure
    int64 time_locked_balance = 9 [json_name = "time_locked_balance"];

    enum ClosureType {
        COOPERATIVE_CLOSE = 0;
        LOCAL_FORCE_CLOSE = 1;
        REMOTE_FORCE_CLOSE = 2;
        BREACH_CLOSE = 3;
        FUNDING_CANCELED = 4;
        ABANDONED = 5;
    }

    /// Details on how the channel was closed.
    ClosureType close_type = 10 [json_name = "close_type"];
}

message ClosedChannelsRequest {
    bool cooperative = 1;
    bool local_force = 2;
    bool remote_force = 3;
    bool breach = 4;
    bool funding_canceled = 5;
    bool abandoned = 6;
}

message ClosedChannelsResponse { 
    repeated ChannelCloseSummary channels = 1 [json_name = "channels"];
}

message Peer {
    /// The identity pubkey of the peer
    string pub_key = 1 [json_name = "pub_key"];

    /// Network address of the peer; eg `127.0.0.1:10011`
    string address = 3 [json_name = "address"];

    /// Bytes of data transmitted to this peer
    uint64 bytes_sent = 4 [json_name = "bytes_sent"];

    /// Bytes of data transmitted from this peer
    uint64 bytes_recv = 5 [json_name = "bytes_recv"];

    /// Satoshis sent to this peer
    int64 sat_sent = 6 [json_name = "sat_sent"];

    /// Satoshis received from this peer
    int64 sat_recv = 7 [json_name = "sat_recv"];

    /// A channel is inbound if the counterparty initiated the channel
    bool inbound = 8 [json_name = "inbound"];

    /// Ping time to this peer
    int64 ping_time = 9 [json_name = "ping_time"];

    enum SyncType {
        /**
        Denotes that we cannot determine the peer's current sync type.
        */
        UNKNOWN_SYNC = 0;

        /**
        Denotes that we are actively receiving new graph updates from the peer.
        */
        ACTIVE_SYNC = 1;

        /**
        Denotes that we are not receiving new graph updates from the peer.
        */
        PASSIVE_SYNC = 2;
    }

    // The type of sync we are currently performing with this peer.
    SyncType sync_type = 10 [json_name = "sync_type"];
}

message ListPeersRequest {
}
message ListPeersResponse {
    /// The list of currently connected peers
    repeated Peer peers = 1 [json_name = "peers"];
}

message GetInfoRequest {
}
message GetInfoResponse {

    /// The identity pubkey of the current node.
    string identity_pubkey = 1 [json_name = "identity_pubkey"];

    /// If applicable, the alias of the current node, e.g. "bob"
    string alias = 2 [json_name = "alias"];

    /// Number of pending channels
    uint32 num_pending_channels = 3 [json_name = "num_pending_channels"];

    /// Number of active channels
    uint32 num_active_channels = 4 [json_name = "num_active_channels"];

    /// Number of peers
    uint32 num_peers = 5 [json_name = "num_peers"];

    /// The node's current view of the height of the best block
    uint32 block_height = 6 [json_name = "block_height"];

    /// The node's current view of the hash of the best block
    string block_hash = 8 [json_name = "block_hash"];

    /// Whether the wallet's view is synced to the main chain
    bool synced_to_chain = 9 [json_name = "synced_to_chain"];

    /** 
    Whether the current node is connected to testnet. This field is 
    deprecated and the network field should be used instead 
    **/
    bool testnet = 10 [json_name = "testnet", deprecated = true];

    reserved 11;

    /// The URIs of the current node.
    repeated string uris = 12 [json_name = "uris"];

    /// Timestamp of the block best known to the wallet
    int64 best_header_timestamp = 13 [ json_name = "best_header_timestamp" ];

    /// The version of the LND software that the node is running.
    string version = 14 [ json_name = "version" ];

    /// Number of inactive channels
    uint32 num_inactive_channels = 15 [json_name = "num_inactive_channels"];

    /// A list of active chains the node is connected to
    repeated Chain chains = 16 [json_name = "chains"];

    /// The color of the current node in hex code format
    string color = 17 [json_name = "color"];

    // Whether we consider ourselves synced with the public channel graph.
    bool synced_to_graph = 18 [json_name = "synced_to_graph"];
}

message Chain {
    /// The blockchain the node is on (eg bitcoin, litecoin)
    string chain = 1 [json_name = "chain"];

    /// The network the node is on (eg regtest, testnet, mainnet)
    string network = 2 [json_name = "network"];
}

message ConfirmationUpdate {
    bytes block_sha = 1;
    int32 block_height = 2;

    uint32 num_confs_left = 3;
}

message ChannelOpenUpdate {
    ChannelPoint channel_point = 1 [json_name = "channel_point"];
}

message ChannelCloseUpdate {
    bytes closing_txid = 1 [json_name = "closing_txid"];

    bool success = 2 [json_name = "success"];
}

message CloseChannelRequest {
    /**
    The outpoint (txid:index) of the funding transaction. With this value, Bob
    will be able to generate a signature for Alice's version of the commitment
    transaction.
    */
    ChannelPoint channel_point = 1;

    /// If true, then the channel will be closed forcibly. This means the current commitment transaction will be signed and broadcast.
    bool force = 2;

    /// The target number of blocks that the closure transaction should be confirmed by.
    int32 target_conf = 3;

    /// A manual fee rate set in sat/byte that should be used when crafting the closure transaction.
    int64 sat_per_byte = 4;
}

message CloseStatusUpdate {
    oneof update {
        PendingUpdate close_pending = 1 [json_name = "close_pending"];
        ChannelCloseUpdate chan_close = 3 [json_name = "chan_close"];
    }
}

message PendingUpdate {
    bytes txid = 1 [json_name = "txid"];
    uint32 output_index = 2 [json_name = "output_index"];
}

message OpenChannelRequest {
    /// The pubkey of the node to open a channel with
    bytes node_pubkey = 2 [json_name = "node_pubkey"];

    /// The hex encoded pubkey of the node to open a channel with
    string node_pubkey_string = 3 [json_name = "node_pubkey_string"];

    /// The number of satoshis the wallet should commit to the channel
    int64 local_funding_amount = 4 [json_name = "local_funding_amount"];

    /// The number of satoshis to push to the remote side as part of the initial commitment state
    int64 push_sat = 5 [json_name = "push_sat"];

    /// The target number of blocks that the funding transaction should be confirmed by.
    int32 target_conf = 6;

    /// A manual fee rate set in sat/byte that should be used when crafting the funding transaction.
    int64 sat_per_byte = 7;

    /// Whether this channel should be private, not announced to the greater network.
    bool private = 8 [json_name = "private"];

    /// The minimum value in millisatoshi we will require for incoming HTLCs on the channel.
    int64 min_htlc_msat = 9 [json_name = "min_htlc_msat"];

    /// The delay we require on the remote's commitment transaction. If this is not set, it will be scaled automatically with the channel size.
    uint32 remote_csv_delay = 10 [json_name = "remote_csv_delay"];

    /// The minimum number of confirmations each one of your outputs used for the funding transaction must satisfy.
    int32 min_confs = 11 [json_name = "min_confs"];

    /// Whether unconfirmed outputs should be used as inputs for the funding transaction.
    bool spend_unconfirmed = 12 [json_name = "spend_unconfirmed"];
}
message OpenStatusUpdate {
    oneof update {
        PendingUpdate chan_pending = 1 [json_name = "chan_pending"];
        ChannelOpenUpdate chan_open = 3 [json_name = "chan_open"];
    }
}

message PendingHTLC {

    /// The direction within the channel that the htlc was sent
    bool incoming = 1 [ json_name = "incoming" ];

    /// The total value of the htlc
    int64 amount = 2 [ json_name = "amount" ];

    /// The final output to be swept back to the user's wallet
    string outpoint = 3 [ json_name = "outpoint" ];

    /// The next block height at which we can spend the current stage
    uint32 maturity_height = 4 [ json_name = "maturity_height" ];

    /**
       The number of blocks remaining until the current stage can be swept.
       Negative values indicate how many blocks have passed since becoming
       mature.
    */
    int32 blocks_til_maturity = 5 [ json_name = "blocks_til_maturity" ];

    /// Indicates whether the htlc is in its first or second stage of recovery
    uint32 stage = 6 [ json_name = "stage" ];
}

message PendingChannelsRequest {}
message PendingChannelsResponse {
    message PendingChannel {
        string remote_node_pub = 1 [ json_name = "remote_node_pub" ];
        string channel_point = 2 [ json_name = "channel_point" ];

        int64 capacity = 3 [ json_name = "capacity" ];

        int64 local_balance = 4 [ json_name = "local_balance" ];
        int64 remote_balance = 5 [ json_name = "remote_balance" ];
       
        /// The minimum satoshis this node is required to reserve in its balance.
        int64 local_chan_reserve_sat = 6 [json_name = "local_chan_reserve_sat"];

        /**
        The minimum satoshis the other node is required to reserve in its
        balance.
        */
        int64 remote_chan_reserve_sat = 7 [json_name = "remote_chan_reserve_sat"];
    }

    message PendingOpenChannel {
        /// The pending channel
        PendingChannel channel = 1 [ json_name = "channel" ];

        /// The height at which this channel will be confirmed
        uint32 confirmation_height = 2 [ json_name = "confirmation_height" ];

        /**
        The amount calculated to be paid in fees for the current set of
        commitment transactions. The fee amount is persisted with the channel
        in order to allow the fee amount to be removed and recalculated with
        each channel state update, including updates that happen after a system
        restart.
        */
        int64 commit_fee = 4 [json_name = "commit_fee" ];

        /// The weight of the commitment transaction
        int64 commit_weight = 5 [ json_name = "commit_weight" ];

        /**
        The required number of satoshis per kilo-weight that the requester will
        pay at all times, for both the funding transaction and commitment
        transaction. This value can later be updated once the channel is open.
        */
        int64 fee_per_kw = 6 [ json_name = "fee_per_kw" ];
    }

    message WaitingCloseChannel {
        /// The pending channel waiting for closing tx to confirm
        PendingChannel channel = 1;

        /// The balance in satoshis encumbered in this channel
        int64 limbo_balance = 2 [ json_name = "limbo_balance" ];
    }

    message ClosedChannel {
        /// The pending channel to be closed
        PendingChannel channel = 1;

        /// The transaction id of the closing transaction
        string closing_txid = 2 [ json_name = "closing_txid" ];
    }

    message ForceClosedChannel {
        /// The pending channel to be force closed
        PendingChannel channel = 1 [ json_name = "channel" ];

        /// The transaction id of the closing transaction
        string closing_txid = 2 [ json_name = "closing_txid" ];

        /// The balance in satoshis encumbered in this pending channel
        int64 limbo_balance = 3 [ json_name = "limbo_balance" ];

        /// The height at which funds can be swept into the wallet
        uint32 maturity_height = 4 [ json_name = "maturity_height" ];

        /*
          Remaining # of blocks until the commitment output can be swept.
          Negative values indicate how many blocks have passed since becoming
          mature.
        */
        int32 blocks_til_maturity = 5 [ json_name = "blocks_til_maturity" ];

        /// The total value of funds successfully recovered from this channel
        int64 recovered_balance = 6 [ json_name = "recovered_balance" ];

        repeated PendingHTLC pending_htlcs = 8 [ json_name = "pending_htlcs" ];
    }

    /// The balance in satoshis encumbered in pending channels
    int64 total_limbo_balance = 1 [ json_name = "total_limbo_balance" ];

    /// Channels pending opening
    repeated PendingOpenChannel pending_open_channels = 2 [ json_name = "pending_open_channels" ];

    /// Channels pending closing
    repeated ClosedChannel pending_closing_channels = 3 [ json_name = "pending_closing_channels" ];

    /// Channels pending force closing
    repeated ForceClosedChannel pending_force_closing_channels =  4 [ json_name = "pending_force_closing_channels" ];

    /// Channels waiting for closing tx to confirm
    repeated WaitingCloseChannel waiting_close_channels = 5 [ json_name = "waiting_close_channels" ];
}

message ChannelEventSubscription {
}

message ChannelEventUpdate {
    oneof channel {
        Channel open_channel = 1 [ json_name = "open_channel" ];
        ChannelCloseSummary closed_channel = 2 [ json_name = "closed_channel" ];
        ChannelPoint active_channel = 3 [ json_name = "active_channel" ];
        ChannelPoint inactive_channel = 4 [ json_name = "inactive_channel" ];
    }

    enum UpdateType {
         OPEN_CHANNEL = 0;
         CLOSED_CHANNEL = 1;
         ACTIVE_CHANNEL = 2;
         INACTIVE_CHANNEL = 3;
    }

    UpdateType type = 5 [ json_name = "type" ];
}

message WalletBalanceRequest {
}
message WalletBalanceResponse {
    /// The balance of the wallet
    int64 total_balance = 1 [json_name = "total_balance"];

    /// The confirmed balance of a wallet(with >= 1 confirmations)
    int64 confirmed_balance = 2 [json_name = "confirmed_balance"];

    /// The unconfirmed balance of a wallet(with 0 confirmations)
    int64 unconfirmed_balance = 3 [json_name = "unconfirmed_balance"];
}

message ChannelBalanceRequest {
}
message ChannelBalanceResponse {
    /// Sum of channels balances denominated in satoshis
    int64 balance = 1 [json_name = "balance"];

    /// Sum of channels pending balances denominated in satoshis
    int64 pending_open_balance = 2 [json_name = "pending_open_balance"];
}

message QueryRoutesRequest {
    /// The 33-byte hex-encoded public key for the payment destination
    string pub_key = 1;

    /// The amount to send expressed in satoshis
    int64 amt = 2;

    reserved 3;

    /// An optional CLTV delta from the current height that should be used for the timelock of the final hop
    int32 final_cltv_delta = 4;

    /**
    The maximum number of satoshis that will be paid as a fee of the payment.
    This value can be represented either as a percentage of the amount being
    sent, or as a fixed amount of the maximum fee the user is willing the pay to
    send the payment.
    */
    FeeLimit fee_limit = 5;

    /**
    A list of nodes to ignore during path finding.
    */
    repeated bytes ignored_nodes = 6;

    /**
    Deprecated. A list of edges to ignore during path finding.
    */
    repeated EdgeLocator ignored_edges = 7 [deprecated = true];

    /**
    The source node where the request route should originated from. If empty,
    self is assumed.
    */
    string source_pub_key = 8;

    /**
    If set to true, edge probabilities from mission control will be used to get
    the optimal route.
    */
    bool use_mission_control = 9;

    /**
    A list of directed node pairs that will be ignored during path finding.
    */
    repeated NodePair ignored_pairs = 10;

    /** 
    An optional field that can be used to pass an arbitrary set of TLV records
    to a peer which understands the new records. This can be used to pass
    application specific data during the payment attempt. If the destination
    does not support the specified recrods, and error will be returned.
    */
    map<uint64, bytes> dest_tlv = 11;
}

message NodePair {
    /// The sending node of the pair.
    bytes from = 1;

    /// The receiving node of the pair.
    bytes to = 2;
}

message EdgeLocator {
    /// The short channel id of this edge.
    uint64 channel_id = 1;

    /**
    The direction of this edge. If direction_reverse is false, the direction
    of this edge is from the channel endpoint with the lexicographically smaller
    pub key to the endpoint with the larger pub key. If direction_reverse is
    is true, the edge goes the other way.
    */
    bool direction_reverse = 2;
}

message QueryRoutesResponse {
    /**
    The route that results from the path finding operation. This is still a
    repeated field to retain backwards compatibility.
    */
    repeated Route routes = 1 [json_name = "routes"];

    /**
    The success probability of the returned route based on the current mission
    control state. [EXPERIMENTAL]
    */
    double success_prob = 2 [json_name = "success_prob"];
}

message Hop {
    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 chan_id = 1 [json_name = "chan_id"];
    int64 chan_capacity = 2 [json_name = "chan_capacity"];
    int64 amt_to_forward = 3 [json_name = "amt_to_forward", deprecated = true];
    int64 fee = 4 [json_name = "fee", deprecated = true];
    uint32 expiry = 5 [json_name = "expiry"];
    int64 amt_to_forward_msat = 6 [json_name = "amt_to_forward_msat"];
    int64 fee_msat = 7 [json_name = "fee_msat"];

    /**
    An optional public key of the hop. If the public key is given, the payment
    can be executed without relying on a copy of the channel graph.
    */
    string pub_key = 8 [json_name = "pub_key"];

    /** 
    If set to true, then this hop will be encoded using the new variable length
    TLV format. Note that if any custom tlv_records below are specified, then
    this field MUST be set to true for them to be encoded properly.
    */
    bool tlv_payload = 9 [json_name = "tlv_payload"];

    /**
    An optional set of key-value TLV records. This is useful within the context
    of the SendToRoute call as it allows callers to specify arbitrary K-V pairs
    to drop off at each hop within the onion.
    */
    map<uint64, bytes> tlv_records = 10 [json_name = "tlv_records"];
}

/**
A path through the channel graph which runs over one or more channels in
succession. This struct carries all the information required to craft the
Sphinx onion packet, and send the payment along the first hop in the path. A
route is only selected as valid if all the channels have sufficient capacity to
carry the initial payment amount after fees are accounted for.
*/
message Route {

    /**
    The cumulative (final) time lock across the entire route.  This is the CLTV
    value that should be extended to the first hop in the route. All other hops
    will decrement the time-lock as advertised, leaving enough time for all
    hops to wait for or present the payment preimage to complete the payment.
    */
    uint32 total_time_lock = 1 [json_name = "total_time_lock"];

    /**
    The sum of the fees paid at each hop within the final route.  In the case
    of a one-hop payment, this value will be zero as we don't need to pay a fee
    to ourselves.
    */
    int64 total_fees = 2 [json_name = "total_fees", deprecated = true];

    /**
    The total amount of funds required to complete a payment over this route.
    This value includes the cumulative fees at each hop. As a result, the HTLC
    extended to the first-hop in the route will need to have at least this many
    satoshis, otherwise the route will fail at an intermediate node due to an
    insufficient amount of fees.
    */
    int64 total_amt = 3 [json_name = "total_amt", deprecated = true];

    /**
    Contains details concerning the specific forwarding details at each hop.
    */
    repeated Hop hops = 4 [json_name = "hops"];
    
    /**
    The total fees in millisatoshis.
    */
    int64 total_fees_msat = 5 [json_name = "total_fees_msat"];
    
    /**
    The total amount in millisatoshis.
    */
    int64 total_amt_msat = 6 [json_name = "total_amt_msat"];
}

message NodeInfoRequest {
    /// The 33-byte hex-encoded compressed public of the target node 
    string pub_key = 1;

    /// If true, will include all known channels associated with the node.
    bool include_channels = 2;
}

message NodeInfo {

    /**
    An individual vertex/node within the channel graph. A node is
    connected to other nodes by one or more channel edges emanating from it. As
    the graph is directed, a node will also have an incoming edge attached to
    it for each outgoing edge.
    */
    LightningNode node = 1 [json_name = "node"];

    /// The total number of channels for the node.
    uint32 num_channels = 2 [json_name = "num_channels"];

    /// The sum of all channels capacity for the node, denominated in satoshis.
    int64 total_capacity = 3 [json_name = "total_capacity"];

    /// A list of all public channels for the node.
    repeated ChannelEdge channels = 4 [json_name = "channels"];
}

/**
An individual vertex/node within the channel graph. A node is
connected to other nodes by one or more channel edges emanating from it. As the
graph is directed, a node will also have an incoming edge attached to it for
each outgoing edge.
*/
message LightningNode {
    uint32 last_update = 1 [ json_name = "last_update" ];
    string pub_key = 2 [ json_name = "pub_key" ];
    string alias = 3 [ json_name = "alias" ];
    repeated NodeAddress addresses = 4 [ json_name = "addresses" ];
    string color = 5 [ json_name = "color" ];
}

message NodeAddress {
    string network = 1 [ json_name = "network" ];
    string addr = 2 [ json_name = "addr" ];
}

message RoutingPolicy {
    uint32 time_lock_delta = 1 [json_name = "time_lock_delta"];
    int64 min_htlc = 2 [json_name = "min_htlc"];
    int64 fee_base_msat = 3 [json_name = "fee_base_msat"];
    int64 fee_rate_milli_msat = 4 [json_name = "fee_rate_milli_msat"];
    bool disabled = 5 [json_name = "disabled"];
    uint64 max_htlc_msat = 6 [json_name = "max_htlc_msat"];
    uint32 last_update = 7 [json_name = "last_update"];
}

/**
A fully authenticated channel along with all its unique attributes.
Once an authenticated channel announcement has been processed on the network,
then an instance of ChannelEdgeInfo encapsulating the channels attributes is
stored. The other portions relevant to routing policy of a channel are stored
within a ChannelEdgePolicy for each direction of the channel.
*/
message ChannelEdge {

    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 channel_id = 1 [json_name = "channel_id"];
    string chan_point = 2 [json_name = "chan_point"];

    uint32 last_update = 3 [json_name = "last_update", deprecated = true];

    string node1_pub = 4 [json_name = "node1_pub"];
    string node2_pub = 5 [json_name = "node2_pub"];

    int64 capacity = 6 [json_name = "capacity"];

    RoutingPolicy node1_policy = 7 [json_name = "node1_policy"];
    RoutingPolicy node2_policy = 8 [json_name = "node2_policy"];
}

message ChannelGraphRequest {
     /**
     Whether unannounced channels are included in the response or not. If set,
     unannounced channels are included. Unannounced channels are both private
     channels, and public channels that are not yet announced to the network.
     */
     bool include_unannounced = 1 [json_name = "include_unannounced"];
}

/// Returns a new instance of the directed channel graph.
message ChannelGraph {
    /// The list of `LightningNode`s in this channel graph
    repeated LightningNode nodes = 1 [json_name = "nodes"];

    /// The list of `ChannelEdge`s in this channel graph
    repeated ChannelEdge edges = 2 [json_name = "edges"];
}

message ChanInfoRequest {
    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 chan_id = 1;
}

message NetworkInfoRequest {
}
message NetworkInfo {
    uint32 graph_diameter = 1 [json_name = "graph_diameter"];
    double avg_out_degree = 2 [json_name = "avg_out_degree"];
    uint32 max_out_degree = 3 [json_name = "max_out_degree"];

    uint32 num_nodes = 4 [json_name = "num_nodes"];
    uint32 num_channels = 5 [json_name = "num_channels"];

    int64 total_network_capacity = 6 [json_name = "total_network_capacity"];

    double avg_channel_size = 7 [json_name = "avg_channel_size"];
    int64 min_channel_size = 8 [json_name = "min_channel_size"];
    int64 max_channel_size = 9 [json_name = "max_channel_size"];
    int64 median_channel_size_sat = 10 [json_name = "median_channel_size_sat"];

    // The number of edges marked as zombies.
    uint64 num_zombie_chans = 11 [json_name = "num_zombie_chans"];

    // TODO(roasbeef): fee rate info, expiry
    //  * also additional RPC for tracking fee info once in
}

message StopRequest{}
message StopResponse{}

message GraphTopologySubscription {}
message GraphTopologyUpdate {
    repeated NodeUpdate node_updates = 1;
    repeated ChannelEdgeUpdate channel_updates = 2;
    repeated ClosedChannelUpdate closed_chans = 3;
}
message NodeUpdate {
    repeated string addresses = 1;
    string identity_key = 2;
    bytes global_features = 3;
    string alias = 4;
    string color = 5;
}
message ChannelEdgeUpdate {
    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 chan_id = 1;

    ChannelPoint chan_point = 2;

    int64 capacity = 3;

    RoutingPolicy routing_policy  = 4;

    string advertising_node  = 5;
    string connecting_node = 6;
}
message ClosedChannelUpdate {
    /**
    The unique channel ID for the channel. The first 3 bytes are the block
    height, the next 3 the index within the block, and the last 2 bytes are the
    output index for the channel.
    */
    uint64 chan_id = 1;
    int64 capacity = 2;
    uint32 closed_height = 3;
    ChannelPoint chan_point = 4;
}

message HopHint {
    /// The public key of the node at the start of the channel.
    string node_id = 1 [json_name = "node_id"];

    /// The unique identifier of the channel.
    uint64 chan_id = 2 [json_name = "chan_id"];

    /// The base fee of the channel denominated in millisatoshis.
    uint32 fee_base_msat = 3 [json_name = "fee_base_msat"];

    /**
    The fee rate of the channel for sending one satoshi across it denominated in
    millionths of a satoshi.
    */
    uint32 fee_proportional_millionths = 4 [json_name = "fee_proportional_millionths"];

    /// The time-lock delta of the channel.
    uint32 cltv_expiry_delta = 5 [json_name = "cltv_expiry_delta"];
}

message RouteHint {
    /**
    A list of hop hints that when chained together can assist in reaching a
    specific destination.
    */
    repeated HopHint hop_hints = 1 [json_name = "hop_hints"];
}

message Invoice {
    /**
    An optional memo to attach along with the invoice. Used for record keeping
    purposes for the invoice's creator, and will also be set in the description
    field of the encoded payment request if the description_hash field is not
    being used.
    */
    string memo = 1 [json_name = "memo"];

    /** Deprecated. An optional cryptographic receipt of payment which is not
    implemented.
    */
    bytes receipt = 2 [json_name = "receipt", deprecated = true];

    /**
    The hex-encoded preimage (32 byte) which will allow settling an incoming
    HTLC payable to this preimage
    */
    bytes r_preimage = 3 [json_name = "r_preimage"];

    /// The hash of the preimage
    bytes r_hash = 4 [json_name = "r_hash"];

    /// The value of this invoice in satoshis
    int64 value = 5 [json_name = "value"];

    /// Whether this invoice has been fulfilled
    bool settled = 6 [json_name = "settled", deprecated = true];

    /// When this invoice was created
    int64 creation_date = 7 [json_name = "creation_date"];

    /// When this invoice was settled
    int64 settle_date = 8 [json_name = "settle_date"];

    /**
    A bare-bones invoice for a payment within the Lightning Network.  With the
    details of the invoice, the sender has all the data necessary to send a
    payment to the recipient.
    */
    string payment_request = 9 [json_name = "payment_request"];

    /**
    Hash (SHA-256) of a description of the payment. Used if the description of
    payment (memo) is too long to naturally fit within the description field
    of an encoded payment request.
    */
    bytes description_hash = 10 [json_name = "description_hash"];

    /// Payment request expiry time in seconds. Default is 3600 (1 hour).
    int64 expiry = 11 [json_name = "expiry"];

    /// Fallback on-chain address.
    string fallback_addr = 12 [json_name = "fallback_addr"];

    /// Delta to use for the time-lock of the CLTV extended to the final hop.
    uint64 cltv_expiry = 13 [json_name = "cltv_expiry"];

    /**
    Route hints that can each be individually used to assist in reaching the
    invoice's destination.
    */
    repeated RouteHint route_hints = 14 [json_name = "route_hints"];

    /// Whether this invoice should include routing hints for private channels.
    bool private = 15 [json_name = "private"];

    /**
    The "add" index of this invoice. Each newly created invoice will increment
    this index making it monotonically increasing. Callers to the
    SubscribeInvoices call can use this to instantly get notified of all added
    invoices with an add_index greater than this one.
    */
    uint64 add_index = 16 [json_name = "add_index"];

    /**
    The "settle" index of this invoice. Each newly settled invoice will
    increment this index making it monotonically increasing. Callers to the
    SubscribeInvoices call can use this to instantly get notified of all
    settled invoices with an settle_index greater than this one.
    */
    uint64 settle_index = 17 [json_name = "settle_index"];

    /// Deprecated, use amt_paid_sat or amt_paid_msat.
    int64 amt_paid = 18 [json_name = "amt_paid", deprecated = true];

    /**
    The amount that was accepted for this invoice, in satoshis. This will ONLY
    be set if this invoice has been settled. We provide this field as if the
    invoice was created with a zero value, then we need to record what amount
    was ultimately accepted. Additionally, it's possible that the sender paid
    MORE that was specified in the original invoice. So we'll record that here
    as well.
    */
    int64 amt_paid_sat = 19 [json_name = "amt_paid_sat"];

    /**
    The amount that was accepted for this invoice, in millisatoshis. This will
    ONLY be set if this invoice has been settled. We provide this field as if
    the invoice was created with a zero value, then we need to record what
    amount was ultimately accepted. Additionally, it's possible that the sender
    paid MORE that was specified in the original invoice. So we'll record that
    here as well.
    */
    int64 amt_paid_msat = 20 [json_name = "amt_paid_msat"];

    enum InvoiceState {
        OPEN = 0;
        SETTLED = 1;
        CANCELED = 2;
        ACCEPTED = 3;
    }

    /**
    The state the invoice is in.
    */
    InvoiceState state = 21 [json_name = "state"];

    /// List of HTLCs paying to this invoice [EXPERIMENTAL].
    repeated InvoiceHTLC htlcs = 22 [json_name = "htlcs"];
}

enum InvoiceHTLCState {
    ACCEPTED = 0;
    SETTLED = 1;
    CANCELLED = 2;
}

/// Details of an HTLC that paid to an invoice
message InvoiceHTLC {
    /// Short channel id over which the htlc was received.
    uint64 chan_id = 1 [json_name = "chan_id"];

    /// Index identifying the htlc on the channel.
    uint64 htlc_index = 2 [json_name = "htlc_index"];

    /// The amount of the htlc in msat.
    uint64 amt_msat = 3 [json_name = "amt_msat"];

    /// Block height at which this htlc was accepted.
    int32 accept_height = 4 [json_name = "accept_height"];

    /// Time at which this htlc was accepted.
    int64 accept_time = 5 [json_name = "accept_time"];

    /// Time at which this htlc was settled or cancelled.
    int64 resolve_time = 6 [json_name = "resolve_time"];
    
    /// Block height at which this htlc expires.
    int32 expiry_height = 7 [json_name = "expiry_height"];

    /// Current state the htlc is in.
    InvoiceHTLCState state = 8 [json_name = "state"];
}

message AddInvoiceResponse {
    bytes r_hash = 1 [json_name = "r_hash"];

    /**
    A bare-bones invoice for a payment within the Lightning Network.  With the
    details of the invoice, the sender has all the data necessary to send a
    payment to the recipient.
    */
    string payment_request = 2 [json_name = "payment_request"];

    /**
    The "add" index of this invoice. Each newly created invoice will increment
    this index making it monotonically increasing. Callers to the
    SubscribeInvoices call can use this to instantly get notified of all added
    invoices with an add_index greater than this one.
    */
    uint64 add_index = 16 [json_name = "add_index"];
}
message PaymentHash {
    /**
    The hex-encoded payment hash of the invoice to be looked up. The passed
    payment hash must be exactly 32 bytes, otherwise an error is returned.
    */
    string r_hash_str = 1 [json_name = "r_hash_str"];

    /// The payment hash of the invoice to be looked up.
    bytes r_hash = 2 [json_name = "r_hash"];
}

message ListInvoiceRequest {
    /// If set, only unsettled invoices will be returned in the response.
    bool pending_only = 1 [json_name = "pending_only"];

    /**
    The index of an invoice that will be used as either the start or end of a
    query to determine which invoices should be returned in the response.
    */
    uint64 index_offset = 4 [json_name = "index_offset"];

    /// The max number of invoices to return in the response to this query.
    uint64 num_max_invoices = 5 [json_name = "num_max_invoices"];

    /**
    If set, the invoices returned will result from seeking backwards from the
    specified index offset. This can be used to paginate backwards.
    */
    bool reversed = 6 [json_name = "reversed"];
}
message ListInvoiceResponse {
    /**
    A list of invoices from the time slice of the time series specified in the
    request.
    */
    repeated Invoice invoices = 1 [json_name = "invoices"];

    /**
    The index of the last item in the set of returned invoices. This can be used
    to seek further, pagination style.
    */
    uint64 last_index_offset = 2 [json_name = "last_index_offset"];

    /**
    The index of the last item in the set of returned invoices. This can be used
    to seek backwards, pagination style.
    */
    uint64 first_index_offset = 3 [json_name = "first_index_offset"];
}

message InvoiceSubscription {
    /**
    If specified (non-zero), then we'll first start by sending out
    notifications for all added indexes with an add_index greater than this
    value. This allows callers to catch up on any events they missed while they
    weren't connected to the streaming RPC.
    */
    uint64 add_index = 1 [json_name = "add_index"];

    /**
    If specified (non-zero), then we'll first start by sending out
    notifications for all settled indexes with an settle_index greater than
    this value. This allows callers to catch up on any events they missed while
    they weren't connected to the streaming RPC.
    */
    uint64 settle_index = 2 [json_name = "settle_index"];
}


message Payment {
    /// The payment hash
    string payment_hash = 1 [json_name = "payment_hash"];

    /// Deprecated, use value_sat or value_msat.
    int64 value = 2 [json_name = "value", deprecated = true];

    /// The date of this payment
    int64 creation_date = 3 [json_name = "creation_date"];

    /// The path this payment took
    repeated string path = 4 [ json_name = "path" ];

    /// Deprecated, use fee_sat or fee_msat.
    int64 fee = 5 [json_name = "fee", deprecated = true];

    /// The payment preimage
    string payment_preimage = 6 [json_name = "payment_preimage"];

    /// The value of the payment in satoshis
    int64 value_sat = 7 [json_name = "value_sat"];

    /// The value of the payment in milli-satoshis
    int64 value_msat = 8 [json_name = "value_msat"];

    /// The optional payment request being fulfilled.
    string payment_request = 9 [json_name = "payment_request"];

    enum PaymentStatus {
        UNKNOWN = 0;
        IN_FLIGHT = 1;
        SUCCEEDED = 2;
        FAILED = 3;
    }

    // The status of the payment.
    PaymentStatus status = 10 [json_name = "status"];

    ///  The fee paid for this payment in satoshis
    int64 fee_sat = 11 [json_name = "fee_sat"];

    ///  The fee paid for this payment in milli-satoshis
    int64 fee_msat = 12 [json_name = "fee_msat"];
}

message ListPaymentsRequest {
    /**
    If true, then return payments that have not yet fully completed. This means
    that pending payments, as well as failed payments will show up if this
    field is set to True.
    */
    bool include_incomplete = 1;
}

message ListPaymentsResponse {
    /// The list of payments
    repeated Payment payments = 1 [json_name = "payments"];
}

message DeleteAllPaymentsRequest {
}

message DeleteAllPaymentsResponse {
}

message AbandonChannelRequest {
    ChannelPoint channel_point = 1;
}

message AbandonChannelResponse {
}


message DebugLevelRequest {
    bool show = 1;
    string level_spec = 2;
}
message DebugLevelResponse {
    string sub_systems = 1 [json_name = "sub_systems"];
}

message PayReqString {
    /// The payment request string to be decoded
    string pay_req = 1;
}
message PayReq {
    string destination = 1 [json_name = "destination"];
    string payment_hash = 2 [json_name = "payment_hash"];
    int64 num_satoshis = 3 [json_name = "num_satoshis"];
    int64 timestamp = 4 [json_name = "timestamp"];
    int64 expiry = 5 [json_name = "expiry"];
    string description = 6 [json_name = "description"];
    string description_hash = 7 [json_name = "description_hash"];
    string fallback_addr = 8 [json_name = "fallback_addr"];
    int64 cltv_expiry = 9 [json_name = "cltv_expiry"];
    repeated RouteHint route_hints = 10 [json_name = "route_hints"];
}

message FeeReportRequest {}
message ChannelFeeReport {
    /// The channel that this fee report belongs to.
    string chan_point = 1 [json_name = "channel_point"];

    /// The base fee charged regardless of the number of milli-satoshis sent.
    int64 base_fee_msat = 2 [json_name = "base_fee_msat"];

    /// The amount charged per milli-satoshis transferred expressed in millionths of a satoshi.
    int64 fee_per_mil = 3 [json_name = "fee_per_mil"];

    /// The effective fee rate in milli-satoshis. Computed by dividing the fee_per_mil value by 1 million.
    double fee_rate = 4 [json_name = "fee_rate"];
}
message FeeReportResponse {
    /// An array of channel fee reports which describes the current fee schedule for each channel.
    repeated ChannelFeeReport channel_fees = 1 [json_name = "channel_fees"];

    /// The total amount of fee revenue (in satoshis) the switch has collected over the past 24 hrs.
    uint64 day_fee_sum = 2 [json_name = "day_fee_sum"];

    /// The total amount of fee revenue (in satoshis) the switch has collected over the past 1 week.
    uint64 week_fee_sum = 3 [json_name = "week_fee_sum"];

    /// The total amount of fee revenue (in satoshis) the switch has collected over the past 1 month.
    uint64 month_fee_sum = 4 [json_name = "month_fee_sum"];
}

message PolicyUpdateRequest {
    oneof scope {
        /// If set, then this update applies to all currently active channels.
        bool global = 1 [json_name = "global"] ;

        /// If set, this update will target a specific channel.
        ChannelPoint chan_point = 2 [json_name = "chan_point"];
    }

    /// The base fee charged regardless of the number of milli-satoshis sent.
    int64 base_fee_msat = 3 [json_name = "base_fee_msat"];

    /// The effective fee rate in milli-satoshis. The precision of this value goes up to 6 decimal places, so 1e-6.
    double fee_rate = 4 [json_name = "fee_rate"];

    /// The required timelock delta for HTLCs forwarded over the channel.
    uint32 time_lock_delta = 5 [json_name = "time_lock_delta"];
}
message PolicyUpdateResponse {
}

message ForwardingHistoryRequest {
    /// Start time is the starting point of the forwarding history request. All records beyond this point will be included, respecting the end time, and the index offset.
    uint64 start_time = 1 [json_name = "start_time"];

    /// End time is the end point of the forwarding history request. The response will carry at most 50k records between the start time and the end time. The index offset can be used to implement pagination.
    uint64 end_time = 2 [json_name = "end_time"];

    /// Index offset is the offset in the time series to start at. As each response can only contain 50k records, callers can use this to skip around within a packed time series.
    uint32 index_offset = 3 [json_name = "index_offset"];

    /// The max number of events to return in the response to this query.
    uint32 num_max_events = 4 [json_name = "num_max_events"];
}
message ForwardingEvent {
    /// Timestamp is the time (unix epoch offset) that this circuit was completed.
    uint64 timestamp = 1 [json_name = "timestamp"];

    /// The incoming channel ID that carried the HTLC that created the circuit.
    uint64 chan_id_in = 2 [json_name = "chan_id_in"];

    /// The outgoing channel ID that carried the preimage that completed the circuit.
    uint64 chan_id_out = 4 [json_name = "chan_id_out"];

    /// The total amount (in satoshis) of the incoming HTLC that created half the circuit.
    uint64 amt_in = 5 [json_name = "amt_in"];

    /// The total amount (in satoshis) of the outgoing HTLC that created the second half of the circuit.
    uint64 amt_out = 6 [json_name = "amt_out"];

    /// The total fee (in satoshis) that this payment circuit carried.
    uint64 fee = 7 [json_name = "fee"];

    /// The total fee (in milli-satoshis) that this payment circuit carried.
    uint64 fee_msat = 8 [json_name = "fee_msat"];

    // TODO(roasbeef): add settlement latency?
    //  * use FPE on the chan id?
    //  * also list failures?
}
message ForwardingHistoryResponse {
   /// A list of forwarding events from the time slice of the time series specified in the request.
   repeated ForwardingEvent forwarding_events = 1 [json_name = "forwarding_events"];

   /// The index of the last time in the set of returned forwarding events. Can be used to seek further, pagination style.
   uint32 last_offset_index = 2 [json_name = "last_offset_index"];
}

message ExportChannelBackupRequest {
    /// The target channel point to obtain a back up for.
    ChannelPoint chan_point = 1;
}

message ChannelBackup {
    /**
    Identifies the channel that this backup belongs to.
    */
    ChannelPoint chan_point = 1 [ json_name = "chan_point" ];

    /**
    Is an encrypted single-chan backup. this can be passed to
    RestoreChannelBackups, or the WalletUnlocker Init and Unlock methods in
    order to trigger the recovery protocol.
    */
    bytes chan_backup = 2 [ json_name = "chan_backup" ];
}

message MultiChanBackup {
    /**
    Is the set of all channels that are included in this multi-channel backup.
    */
    repeated ChannelPoint chan_points = 1 [ json_name = "chan_points" ];

    /**
    A single encrypted blob containing all the static channel backups of the
    channel listed above. This can be stored as a single file or blob, and
    safely be replaced with any prior/future versions.
    */
    bytes multi_chan_backup = 2 [ json_name = "multi_chan_backup" ];
}

message ChanBackupExportRequest {}
message ChanBackupSnapshot  {
    /**
    The set of new channels that have been added since the last channel backup
    snapshot was requested.
    */
    ChannelBackups single_chan_backups = 1 [ json_name = "single_chan_backups" ];

    /**
    A multi-channel backup that covers all open channels currently known to
    lnd.
    */
    MultiChanBackup multi_chan_backup  = 2 [ json_name = "multi_chan_backup" ];
}

message ChannelBackups {
    /**
    A set of single-chan static channel backups.
    */
    repeated ChannelBackup chan_backups = 1 [ json_name = "chan_backups" ];
}

message RestoreChanBackupRequest {
    oneof backup {
        ChannelBackups chan_backups = 1 [ json_name = "chan_backups" ];

        bytes multi_chan_backup = 2 [ json_name = "multi_chan_backup" ];
    }
}
message RestoreBackupResponse {}

message ChannelBackupSubscription {}

message VerifyChanBackupResponse {
}

src:./wtclientrpc/wtclient.proto


syntax = "proto3";

package wtclientrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/wtclientrpc";

message AddTowerRequest {
    // The identifying public key of the watchtower to add.
    bytes pubkey = 1 [json_name = "pubkey"];

    // A network address the watchtower is reachable over.
    string address = 2 [json_name = "address"];
}

message AddTowerResponse {
}

message RemoveTowerRequest {
    // The identifying public key of the watchtower to remove.
    bytes pubkey = 1 [json_name = "pubkey"];

    /*
    If set, then the record for this address will be removed, indicating that is
    is stale. Otherwise, the watchtower will no longer be used for future
    session negotiations and backups.
    */
    string address = 2 [json_name = "address"];
}

message RemoveTowerResponse {
}

message GetTowerInfoRequest {
    // The identifying public key of the watchtower to retrieve information for.
    bytes pubkey = 1 [json_name = "pubkey"];

    // Whether we should include sessions with the watchtower in the response.
    bool include_sessions = 2 [json_name = "include_sessions"];
}

message TowerSession {
    /*
    The total number of successful backups that have been made to the
    watchtower session.
    */
    uint32 num_backups = 1 [json_name = "num_backups"];

    /*
    The total number of backups in the session that are currently pending to be
    acknowledged by the watchtower.
    */
    uint32 num_pending_backups = 2 [json_name = "num_pending_backups"];

    // The maximum number of backups allowed by the watchtower session.
    uint32 max_backups = 3 [json_name = "max_backups"];

    /*
    The fee rate, in satoshis per vbyte, that will be used by the watchtower for
    the justice transaction in the event of a channel breach.
    */
    uint32 sweep_sat_per_byte = 4 [json_name = "sweep_sat_per_byte"];
}

message Tower {
    // The identifying public key of the watchtower.
    bytes pubkey = 1 [json_name = "pubkey"];

    // The list of addresses the watchtower is reachable over.
    repeated string addresses = 2 [json_name = "addresses"];

    // Whether the watchtower is currently a candidate for new sessions.
    bool active_session_candidate = 3 [json_name = "active_session_candidate"];

    // The number of sessions that have been negotiated with the watchtower.
    uint32 num_sessions = 4 [json_name = "num_sessions"];

    // The list of sessions that have been negotiated with the watchtower.
    repeated TowerSession sessions = 5 [json_name = "sessions"];
}

message ListTowersRequest {
    // Whether we should include sessions with the watchtower in the response.
    bool include_sessions = 1 [json_name = "include_sessions"];
}

message ListTowersResponse {
    // The list of watchtowers available for new backups.
    repeated Tower towers = 1 [json_name = "towers"];
}

message StatsRequest {
}

message StatsResponse {
    /*
    The total number of backups made to all active and exhausted watchtower
    sessions.
    */
    uint32 num_backups = 1 [json_name = "num_backups"];

    /*
    The total number of backups that are pending to be acknowledged by all
    active and exhausted watchtower sessions.
    */
    uint32 num_pending_backups = 2 [json_name = "num_pending_backups"];

    /*
    The total number of backups that all active and exhausted watchtower
    sessions have failed to acknowledge.
    */
    uint32 num_failed_backups = 3 [json_name = "num_failed_backups"];

    // The total number of new sessions made to watchtowers.
    uint32 num_sessions_acquired = 4 [json_name = "num_sessions_acquired"];

    // The total number of watchtower sessions that have been exhausted.
    uint32 num_sessions_exhausted = 5 [json_name = "num_sessions_exhausted"];
}

message PolicyRequest {
}

message PolicyResponse {
    /*
    The maximum number of updates each session we negotiate with watchtowers
    should allow.
    */
    uint32 max_updates = 1 [json_name = "max_updates"];

    /*
    The fee rate, in satoshis per vbyte, that will be used by watchtowers for
    justice transactions in response to channel breaches.
    */
    uint32 sweep_sat_per_byte = 2 [json_name = "sweep_sat_per_byte"];
}

service WatchtowerClient {
    /*
    AddTower adds a new watchtower reachable at the given address and
    considers it for new sessions. If the watchtower already exists, then
    any new addresses included will be considered when dialing it for
    session negotiations and backups.
    */
    rpc AddTower(AddTowerRequest) returns (AddTowerResponse);

    /*
    RemoveTower removes a watchtower from being considered for future session
    negotiations and from being used for any subsequent backups until it's added
    again. If an address is provided, then this RPC only serves as a way of
    removing the address from the watchtower instead.
    */
    rpc RemoveTower(RemoveTowerRequest) returns (RemoveTowerResponse);

    // ListTowers returns the list of watchtowers registered with the client. 
    rpc ListTowers(ListTowersRequest) returns (ListTowersResponse);

    // GetTowerInfo retrieves information for a registered watchtower.
    rpc GetTowerInfo(GetTowerInfoRequest) returns (Tower);

    // Stats returns the in-memory statistics of the client since startup.
    rpc Stats(StatsRequest) returns (StatsResponse);

    // Policy returns the active watchtower client policy configuration.
    rpc Policy(PolicyRequest) returns (PolicyResponse);
}

src:./routerrpc/router.proto


syntax = "proto3";

import "rpc.proto";

package routerrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/routerrpc";

message SendPaymentRequest {
    /// The identity pubkey of the payment recipient
    bytes dest = 1;

    /// Number of satoshis to send.
    int64 amt = 2;

    /// The hash to use within the payment's HTLC
    bytes payment_hash = 3;
 
    /**
    The CLTV delta from the current height that should be used to set the
    timelock for the final hop.
    */
    int32 final_cltv_delta = 4;

    /**
    A bare-bones invoice for a payment within the Lightning Network.  With the
    details of the invoice, the sender has all the data necessary to send a
    payment to the recipient. The amount in the payment request may be zero. In
    that case it is required to set the amt field as well. If no payment request
    is specified, the following fields are required: dest, amt and payment_hash.
    */
    string payment_request = 5;

    /**
    An upper limit on the amount of time we should spend when attempting to
    fulfill the payment. This is expressed in seconds. If we cannot make a
    successful payment within this time frame, an error will be returned.
    This field must be non-zero.
    */
    int32 timeout_seconds = 6;

    /**
    The maximum number of satoshis that will be paid as a fee of the payment.
    If this field is left to the default value of 0, only zero-fee routes will
    be considered. This usually means single hop routes connecting directly to
    the destination. To send the payment without a fee limit, use max int here.
    */
    int64 fee_limit_sat = 7;

    /**
    The channel id of the channel that must be taken to the first hop. If zero,
    any channel may be used.
    */
    uint64 outgoing_chan_id = 8;

    /** 
    An optional maximum total time lock for the route. If zero, there is no
    maximum enforced.
    */
    int32 cltv_limit = 9;

    /**
    Optional route hints to reach the destination through private channels.
    */
    repeated lnrpc.RouteHint route_hints = 10 [json_name = "route_hints"];

    /** 
    An optional field that can be used to pass an arbitrary set of TLV records
    to a peer which understands the new records. This can be used to pass
    application specific data during the payment attempt.
    */
    map<uint64, bytes> dest_tlv = 11;
}

message TrackPaymentRequest {
    /// The hash of the payment to look up.
    bytes payment_hash = 1;
}

enum PaymentState {
    /**
    Payment is still in flight.
    */
    IN_FLIGHT = 0;

    /**
    Payment completed successfully.
    */
    SUCCEEDED = 1;

    /**
    There are more routes to try, but the payment timeout was exceeded.
    */
    FAILED_TIMEOUT = 2;
    
    /**
    All possible routes were tried and failed permanently. Or were no
    routes to the destination at all.
    */
    FAILED_NO_ROUTE = 3;

    /**
    A non-recoverable error has occured.
    */
    FAILED_ERROR = 4;

    /**
    Payment details incorrect (unknown hash, invalid amt or
    invalid final cltv delta)
    */
    FAILED_INCORRECT_PAYMENT_DETAILS = 5;
}


message PaymentStatus {
    /// Current state the payment is in.
    PaymentState state = 1;

    /**
    The pre-image of the payment when state is SUCCEEDED.
    */
    bytes preimage = 2;

    /**
    The taken route when state is SUCCEEDED.
    */
    lnrpc.Route route = 3;
}


message RouteFeeRequest {
    /**
    The destination once wishes to obtain a routing fee quote to.
    */
    bytes dest = 1;

    /**
    The amount one wishes to send to the target destination.
    */
    int64 amt_sat = 2;
}

message RouteFeeResponse {
    /**
    A lower bound of the estimated fee to the target destination within the
    network, expressed in milli-satoshis.
    */
    int64 routing_fee_msat = 1;

    /**
    An estimate of the worst case time delay that can occur. Note that callers
    will still need to factor in the final CLTV delta of the last hop into this
    value.
    */
    int64 time_lock_delay = 2;
}

message SendToRouteRequest {
    /// The payment hash to use for the HTLC.
    bytes payment_hash = 1;

    /// Route that should be used to attempt to complete the payment.
    lnrpc.Route route = 2;
}

message SendToRouteResponse {
    /// The preimage obtained by making the payment.
    bytes preimage = 1;

    /// The failure message in case the payment failed.
    Failure failure = 2;
}

message Failure {
    enum FailureCode {
        /**
        The numbers assigned in this enumeration match the failure codes as
        defined in BOLT #4. Because protobuf 3 requires enums to start with 0,
        a RESERVED value is added.
        */
        RESERVED = 0;

        INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS = 1;
        INCORRECT_PAYMENT_AMOUNT = 2;
        FINAL_INCORRECT_CLTV_EXPIRY = 3;
        FINAL_INCORRECT_HTLC_AMOUNT = 4;
        FINAL_EXPIRY_TOO_SOON = 5;
        INVALID_REALM = 6;
        EXPIRY_TOO_SOON = 7;
        INVALID_ONION_VERSION = 8;
        INVALID_ONION_HMAC = 9;
        INVALID_ONION_KEY = 10;
        AMOUNT_BELOW_MINIMUM = 11;
        FEE_INSUFFICIENT = 12;
        INCORRECT_CLTV_EXPIRY = 13;
        CHANNEL_DISABLED = 14;
        TEMPORARY_CHANNEL_FAILURE = 15;
        REQUIRED_NODE_FEATURE_MISSING = 16;
        REQUIRED_CHANNEL_FEATURE_MISSING = 17;
        UNKNOWN_NEXT_PEER = 18;
        TEMPORARY_NODE_FAILURE = 19;
        PERMANENT_NODE_FAILURE = 20;
        PERMANENT_CHANNEL_FAILURE = 21;

        /**
        The error source is known, but the failure itself couldn't be decoded.
        */
        UNKNOWN_FAILURE = 998;

        /**
        An unreadable failure result is returned if the received failure message
        cannot be decrypted. In that case the error source is unknown.
        */
        UNREADABLE_FAILURE = 999;
    }

    /// Failure code as defined in the Lightning spec
    FailureCode code = 1;

    reserved 2;

    /// An optional channel update message.
    ChannelUpdate channel_update = 3;

    /// A failure type-dependent htlc value.
    uint64 htlc_msat = 4;

    /// The sha256 sum of the onion payload.
    bytes onion_sha_256 = 5;

    /// A failure type-dependent cltv expiry value.
    uint32 cltv_expiry = 6;

    /// A failure type-dependent flags value.
    uint32 flags = 7;

    /**
    The position in the path of the intermediate or final node that generated
    the failure message. Position zero is the sender node.
    **/
    uint32 failure_source_index = 8;
}


message ChannelUpdate {
    /**
    The signature that validates the announced data and proves the ownership
    of node id.
    */
    bytes signature = 1;

    /**
    The target chain that this channel was opened within. This value
    should be the genesis hash of the target chain. Along with the short
    channel ID, this uniquely identifies the channel globally in a
    blockchain.
    */
    bytes chain_hash = 2;

    /**
    The unique description of the funding transaction.
    */
    uint64 chan_id = 3;

    /**
    A timestamp that allows ordering in the case of multiple announcements.
    We should ignore the message if timestamp is not greater than the
    last-received.
    */
    uint32 timestamp = 4;

    /**
    The bitfield that describes whether optional fields are present in this
    update. Currently, the least-significant bit must be set to 1 if the
    optional field MaxHtlc is present.
    */
    uint32 message_flags = 10;

    /**
    The bitfield that describes additional meta-data concerning how the
    update is to be interpreted. Currently, the least-significant bit must be
    set to 0 if the creating node corresponds to the first node in the
    previously sent channel announcement and 1 otherwise. If the second bit
    is set, then the channel is set to be disabled.
    */
    uint32 channel_flags = 5;

    /**
    The minimum number of blocks this node requires to be added to the expiry
    of HTLCs. This is a security parameter determined by the node operator.
    This value represents the required gap between the time locks of the
    incoming and outgoing HTLC's set to this node.
    */
    uint32 time_lock_delta = 6;

    /**
    The minimum HTLC value which will be accepted.
    */
    uint64 htlc_minimum_msat = 7;

    /**
    The base fee that must be used for incoming HTLC's to this particular
    channel. This value will be tacked onto the required for a payment
    independent of the size of the payment.
    */
    uint32 base_fee = 8;

    /**
    The fee rate that will be charged per millionth of a satoshi.
    */
    uint32 fee_rate = 9;
    
    /**
    The maximum HTLC value which will be accepted.
    */
    uint64 htlc_maximum_msat = 11;
    
    /**
    The set of data that was appended to this message, some of which we may
    not actually know how to iterate or parse. By holding onto this data, we
    ensure that we're able to properly validate the set of signatures that
    cover these new fields, and ensure we're able to make upgrades to the
    network in a forwards compatible manner.
    */
    bytes extra_opaque_data = 12;
}
message ResetMissionControlRequest{}

message ResetMissionControlResponse{}

message QueryMissionControlRequest {}

/// QueryMissionControlResponse contains mission control state.
message QueryMissionControlResponse {
    /// Node-level mission control state.
    repeated NodeHistory nodes = 1 [json_name = "nodes"];

    /// Node pair-level mission control state.
    repeated PairHistory pairs = 2 [json_name = "pairs"];
}

/// NodeHistory contains the mission control state for a particular node.
message NodeHistory {
    /// Node pubkey
    bytes pubkey = 1 [json_name = "pubkey"];

    /// Time stamp of last failure. Set to zero if no failure happened yet.
    int64 last_fail_time = 2 [json_name = "last_fail_time"];

    /**
    Estimation of success probability of forwarding towards peers of this node
    for which no specific history is available.
    **/
    float other_success_prob = 3 [json_name = "other_success_prob"];

    reserved 4;
}

/// PairHistory contains the mission control state for a particular node pair.
message PairHistory {
    /// The source node pubkey of the pair.
    bytes node_from = 1 [json_name ="node_from"];
    
    /// The destination node pubkey of the pair.
    bytes node_to = 2 [json_name="node_to"];
    
    /// Time stamp of last result.
    int64 timestamp = 3 [json_name = "timestamp"];

    /// Minimum penalization amount (only applies to failed attempts).
    int64 min_penalize_amt_sat = 4 [json_name = "min_penalize_amt_sat"];

    /// Estimation of success probability for this pair.
    float success_prob = 5 [json_name = "success_prob"];

    /// Whether the last payment attempt through this pair was successful.
    bool last_attempt_successful = 6 [json_name = "last_attempt_successful"];
}

service Router {
    /**
    SendPayment attempts to route a payment described by the passed
    PaymentRequest to the final destination. The call returns a stream of
    payment status updates.
    */
    rpc SendPayment(SendPaymentRequest) returns (stream PaymentStatus);

    /**
    TrackPayment returns an update stream for the payment identified by the
    payment hash.
    */
    rpc TrackPayment(TrackPaymentRequest) returns (stream PaymentStatus);


    /**
    EstimateRouteFee allows callers to obtain a lower bound w.r.t how much it
    may cost to send an HTLC to the target end destination.
    */
    rpc EstimateRouteFee(RouteFeeRequest) returns (RouteFeeResponse);

    /**
    SendToRoute attempts to make a payment via the specified route. This method
    differs from SendPayment in that it allows users to specify a full route
    manually. This can be used for things like rebalancing, and atomic swaps.
    */
    rpc SendToRoute(SendToRouteRequest) returns (SendToRouteResponse);

    /**
    ResetMissionControl clears all mission control state and starts with a clean
    slate.
    */
    rpc ResetMissionControl(ResetMissionControlRequest) returns (ResetMissionControlResponse);
    
    /**
    QueryMissionControl exposes the internal mission control state to callers.
    It is a development feature.
    */
    rpc QueryMissionControl(QueryMissionControlRequest) returns (QueryMissionControlResponse);
}

src:./watchtowerrpc/watchtower.proto


syntax = "proto3";

package watchtowerrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/watchtowerrpc";

service Watchtower {
        /** lncli: tower info
        GetInfo returns general information concerning the companion watchtower
        including it's public key and URIs where the server is currently
        listening for clients.
        */
        rpc GetInfo(GetInfoRequest) returns (GetInfoResponse);
}

message GetInfoRequest{
}

message GetInfoResponse {
        /// The public key of the watchtower.
        bytes pubkey = 1 [json_name = "pubkey"];

        /// The listening addresses of the watchtower.
        repeated string listeners = 2 [json_name = "listeners"];

        /// The URIs of the watchtower.
        repeated string uris = 3 [json_name = "uris" ];
}

src:./signrpc/signer.proto


syntax = "proto3";

package signrpc;

option go_package = "github.com/lightningnetwork/lnd/lnrpc/signrpc";

message KeyLocator {
    /// The family of key being identified.
    int32 key_family = 1;

    /// The precise index of the key being identified.
    int32 key_index = 2;
}

message KeyDescriptor {
     /**
     The raw bytes of the key being identified. Either this or the KeyLocator
     must be specified.
     */
     bytes raw_key_bytes = 1;

     /** 
     The key locator that identifies which key to use for signing. Either this
     or the raw bytes of the target key must be specified.
     */
     KeyLocator key_loc = 2;
}

message TxOut {
    /// The value of the output being spent.
    int64 value = 1;

    /// The script of the output being spent.
    bytes pk_script = 2;
}

message SignDescriptor {
    /**
    A descriptor that precisely describes *which* key to use for signing. This
    may provide the raw public key directly, or require the Signer to re-derive
    the key according to the populated derivation path.
    */
    KeyDescriptor key_desc = 1;

    /**
    A scalar value that will be added to the private key corresponding to the
    above public key to obtain the private key to be used to sign this input.
    This value is typically derived via the following computation:

      * derivedKey = privkey + sha256(perCommitmentPoint || pubKey) mod N
    */
    bytes single_tweak = 2;

    /**
    A private key that will be used in combination with its corresponding
    private key to derive the private key that is to be used to sign the target
    input. Within the Lightning protocol, this value is typically the
    commitment secret from a previously revoked commitment transaction. This
    value is in combination with two hash values, and the original private key
    to derive the private key to be used when signing.
   
     * k = (privKey*sha256(pubKey || tweakPub) +
           tweakPriv*sha256(tweakPub || pubKey)) mod N
    */
    bytes double_tweak = 3;

    /**
    The full script required to properly redeem the output.  This field will
    only be populated if a p2wsh or a p2sh output is being signed.
    */
    bytes witness_script = 4;

    /**
    A description of the output being spent. The value and script MUST be provided.
    */
    TxOut output = 5;

    /**
    The target sighash type that should be used when generating the final
    sighash, and signature.
    */
    uint32 sighash = 7;

    /**
    The target input within the transaction that should be signed.
    */
    int32 input_index = 8;
}

message SignReq {
    /// The raw bytes of the transaction to be signed.
    bytes raw_tx_bytes = 1;

    /// A set of sign descriptors, for each input to be signed.
    repeated SignDescriptor sign_descs = 2;
}

message SignResp {
    /**
    A set of signatures realized in a fixed 64-byte format ordered in ascending
    input order.
    */
    repeated bytes raw_sigs = 1;
}

message InputScript {
    /// The serializes witness stack for the specified input.
    repeated bytes witness = 1;

    /***
    The optional sig script for the specified witness that will only be set if
    the input specified is a nested p2sh witness program.
    */
    bytes sig_script = 2;
}

message InputScriptResp {
    /// The set of fully valid input scripts requested.
    repeated InputScript input_scripts = 1;
}

service Signer {
    /**
    SignOutputRaw is a method that can be used to generated a signature for a
    set of inputs/outputs to a transaction. Each request specifies details
    concerning how the outputs should be signed, which keys they should be
    signed with, and also any optional tweaks. The return value is a fixed
    64-byte signature (the same format as we use on the wire in Lightning). 
    
    If we are  unable to sign using the specified keys, then an error will be
    returned.
    */
    rpc SignOutputRaw(SignReq) returns (SignResp);

    /**
    ComputeInputScript generates a complete InputIndex for the passed
    transaction with the signature as defined within the passed SignDescriptor.
    This method should be capable of generating the proper input script for
    both regular p2wkh output and p2wkh outputs nested within a regular p2sh
    output.

    Note that when using this method to sign inputs belonging to the wallet,
    the only items of the SignDescriptor that need to be populated are pkScript
    in the TxOut field, the value in that same field, and finally the input
    index.
    */
    rpc ComputeInputScript(SignReq) returns (InputScriptResp); 
}

exonum

TOC

如何創建服務

Cryptocurrency Tutorial: How to Create Services · exonum/exonum-doc

Exonum uses Protobuf as its serialization format for storage of data. Thus, we need to describe our structures using the Protobuf interface description language first.

syntax = "proto3";

// Allows to use `exonum.PublicKey` structure already described in `exonum`
// library.
import "helpers.proto";

// Wallet structure used to persist data within the service.
message Wallet {
  exonum.PublicKey pub_key = 1;
  string name = 2;
  uint64 balance = 3;
}

// Transaction type for creating a new wallet.
message TxCreateWallet {
  // UTF-8 string with the owner's name.
  string name = 1;
}

// Transaction type for transferring tokens between two wallets.
message TxTransfer {
  // Public key of the receiver.
  exonum.PublicKey to = 1;
  // Number of tokens to transfer from the sender's account to the receiver's
  // account.
  uint64 amount = 2;
  // Auxiliary number to guarantee non-idempotence of transactions.
  uint64 seed = 3;
}

如何生成 Google Protocol Buffers 文件

exonum/exonum/src/proto/schema/exonum at master · exonum/exonum

git clone https://github.com/exonum/exonum.git /tmp/src/exonum
bash tc.sh --gen-proto-doc /tmp/src/exonum/exonum/src/proto/schema/exonum /tmp/output.md

Generated Date:2019-09-12T11:31:08+08:00

Protocol Documentation

Table of Contents

Top

tests.proto

BlockchainTestTxA

FieldTypeLabelDescription
auint64

BlockchainTestTxB

FieldTypeLabelDescription
buint64
cuint32

CreateWallet

FieldTypeLabelDescription
pubkeyexonum.PublicKey
namestring

Point

FieldTypeLabelDescription
xuint32
yuint32

TestFixedArrays

FieldTypeLabelDescription
fixed_array_8bytes
fixed_array_16bytes
fixed_array_32bytes

TestProtobufConvert

FieldTypeLabelDescription
keyexonum.PublicKey
hashexonum.Hash
unsigned_32uint32
unsigned_64uint64
regular_i32int32
regular_i64int64
fixed_u32fixed32
fixed_u64fixed64
fixed_i32sfixed32
fixed_i64sfixed64
float_32float
float_64double
booleanbool
s_i32sint32
s_i64sint64
bytes_fieldbytes
string_fieldstring
message_fieldPoint
bit_vecexonum.BitVec
timegoogle.protobuf.Timestamp

TestProtobufConvertMap

FieldTypeLabelDescription
num_mapTestProtobufConvertMap.NumMapEntryrepeated
string_mapTestProtobufConvertMap.StringMapEntryrepeated
bytes_mapTestProtobufConvertMap.BytesMapEntryrepeated
point_mapTestProtobufConvertMap.PointMapEntryrepeated
key_string_mapTestProtobufConvertMap.KeyStringMapEntryrepeated

TestProtobufConvertMap.BytesMapEntry

FieldTypeLabelDescription
keyuint32
valuebytes

TestProtobufConvertMap.KeyStringMapEntry

FieldTypeLabelDescription
keystring
valueuint64

TestProtobufConvertMap.NumMapEntry

FieldTypeLabelDescription
keyuint32
valueuint64

TestProtobufConvertMap.PointMapEntry

FieldTypeLabelDescription
keyuint32
valuePoint

TestProtobufConvertMap.StringMapEntry

FieldTypeLabelDescription
keyuint32
valuestring

TestProtobufConvertRepeated

FieldTypeLabelDescription
keysexonum.PublicKeyrepeated
bytes_arraybytesrepeated
string_arraystringrepeated
num_arrayuint32repeated

TestServiceTx

FieldTypeLabelDescription
valueuint64

TimestampTx

FieldTypeLabelDescription
databytes

Transfer

FieldTypeLabelDescription
fromexonum.PublicKey
toexonum.PublicKey
amountuint64

TxAfterCommit

FieldTypeLabelDescription
heightuint64

TxConfig

FieldTypeLabelDescription
fromexonum.PublicKey
configbytes
actual_fromuint64

TxSimple

FieldTypeLabelDescription
public_keyexonum.PublicKey
msgstring

Top

doc_tests.proto

CreateWallet

FieldTypeLabelDescription
namestring

MyStructBig

FieldTypeLabelDescription
hashexonum.Hash
my_struct_smallMyStructSmall

MyStructSmall

FieldTypeLabelDescription
keyexonum.PublicKey
num_fielduint32
string_fieldstring

MyTransaction

FieldTypeLabelDescription
public_keyexonum.PublicKey

Point

FieldTypeLabelDescription
xint32
yint32

TxA

Transaction fields

TxB

...

Top

helpers.proto

BitVec

FieldTypeLabelDescription
databytes
lenuint64

Hash

FieldTypeLabelDescription
databytes

PublicKey

FieldTypeLabelDescription
databytes

Signature

FieldTypeLabelDescription
databytes

Top

storage.proto

IndexMetadata

FieldTypeLabelDescription
index_typeuint32
is_familybool

Top

protocol.proto

BlockRequest

FieldTypeLabelDescription
toexonum.PublicKey
heightuint64

BlockResponse

FieldTypeLabelDescription
toexonum.PublicKey
blockexonum.Block
precommitsbytesrepeated
transactionsexonum.Hashrepeated

Connect

FieldTypeLabelDescription
pub_addrstring
timegoogle.protobuf.Timestamp
user_agentstring

PeersRequest

FieldTypeLabelDescription
toexonum.PublicKey

PoolTransactionsRequest

FieldTypeLabelDescription
toexonum.PublicKey

Precommit

FieldTypeLabelDescription
validatoruint32
heightuint64
rounduint32
propose_hashexonum.Hash
block_hashexonum.Hash
timegoogle.protobuf.Timestamp

Prevote

FieldTypeLabelDescription
validatoruint32
heightuint64
rounduint32
propose_hashexonum.Hash
locked_rounduint32

PrevotesRequest

FieldTypeLabelDescription
toexonum.PublicKey
heightuint64
rounduint32
propose_hashexonum.Hash
validatorsexonum.BitVec

Propose

FieldTypeLabelDescription
validatoruint32
heightuint64
rounduint32
prev_hashexonum.Hash
transactionsexonum.Hashrepeated

ProposeRequest

FieldTypeLabelDescription
toexonum.PublicKey
heightuint64
propose_hashexonum.Hash

Status

FieldTypeLabelDescription
heightuint64
last_hashexonum.Hash
pool_sizeuint64

TransactionsRequest

FieldTypeLabelDescription
toexonum.PublicKey
txsexonum.Hashrepeated

TransactionsResponse

FieldTypeLabelDescription
toexonum.PublicKey
transactionsbytesrepeated

Top

blockchain.proto

Block

FieldTypeLabelDescription
proposer_iduint32
heightuint64
tx_countuint32
prev_hashHash
tx_hashHash
state_hashHash

ConfigReference

FieldTypeLabelDescription
actual_fromuint64
cfg_hashHash

TransactionResult

FieldTypeLabelDescription
statusuint32
descriptionstring

TxLocation

FieldTypeLabelDescription
block_heightuint64
position_in_blockuint64

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── blockchain.proto
├── doc_tests.proto
├── helpers.proto
├── protocol.proto
├── storage.proto
└── tests.proto

0 directories, 6 files

Protobuf sources

src:./tests.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

import "helpers.proto";
import "google/protobuf/timestamp.proto";

package exonum.tests;

message TimestampTx { bytes data = 1; }

message TxAfterCommit { uint64 height = 1; }

message TxConfig {
  exonum.PublicKey from = 1;
  bytes config = 2;
  uint64 actual_from = 3;
}

message TxSimple {
  exonum.PublicKey public_key = 1;
  string msg = 2;
}

message TestServiceTx { uint64 value = 1; }

message BlockchainTestTxA { uint64 a = 1; }

message BlockchainTestTxB {
  uint64 b = 1;
  uint32 c = 2;
}

message CreateWallet {
  exonum.PublicKey pubkey = 1;
  string name = 2;
}

message Transfer {
  exonum.PublicKey from = 1;
  exonum.PublicKey to = 2;
  uint64 amount = 3;
}

message Point {
  uint32 x = 1;
  uint32 y = 2;
}

message TestProtobufConvert {
  exonum.PublicKey key = 1;
  exonum.Hash hash = 2;
  uint32 unsigned_32 = 3;
  uint64 unsigned_64 = 4;
  int32 regular_i32 = 5;
  int64 regular_i64 = 6;
  fixed32 fixed_u32 = 7;
  fixed64 fixed_u64 = 8;
  sfixed32 fixed_i32 = 9;
  sfixed64 fixed_i64 = 10;
  float float_32 = 11;
  double float_64 = 12;
  bool boolean = 13;
  sint32 s_i32 = 14;
  sint64 s_i64 = 15;
  bytes bytes_field = 16;
  string string_field = 17;
  Point message_field = 18;
  exonum.BitVec bit_vec = 19;
  google.protobuf.Timestamp time = 20;
}

message TestProtobufConvertRepeated {
  repeated exonum.PublicKey keys = 1;
  repeated bytes bytes_array = 2;
  repeated string string_array = 3;
  repeated uint32 num_array = 4;
}

message TestProtobufConvertMap {
  map<uint32, uint64> num_map = 1;
  map<uint32, string> string_map = 2;
  map<uint32, bytes> bytes_map = 4;
  map<uint32, Point> point_map = 5;
  map<string, uint64> key_string_map = 6;
}

message TestFixedArrays {
  bytes fixed_array_8 = 1;
  bytes fixed_array_16 = 2;
  bytes fixed_array_32 = 3;
}

src:./doc_tests.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

import "helpers.proto";

package exonum.doc_tests;

message CreateWallet { string name = 1; }

message Point {
  int32 x = 1;
  int32 y = 2;
}

message TxA {
  // Transaction fields
}

message TxB {
  /// ...
}

message MyTransaction { exonum.PublicKey public_key = 1; }

message MyStructSmall {
  exonum.PublicKey key = 1;
  uint32 num_field = 2;
  string string_field = 3;
}
message MyStructBig {
  exonum.Hash hash = 1;
  MyStructSmall my_struct_small = 2;
}

src:./helpers.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

package exonum;

message Hash { bytes data = 1; }

message PublicKey { bytes data = 1; }

message Signature { bytes data = 1; }

message BitVec {
  bytes data = 1;
  uint64 len = 2;
}

src:./storage.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

package exonum;

message IndexMetadata {
  uint32 index_type = 1;
  bool is_family = 2;
}

src:./protocol.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

package exonum.consensus;

import "helpers.proto";
import "blockchain.proto";
import "google/protobuf/timestamp.proto";

message Connect {
  string pub_addr = 1;
  google.protobuf.Timestamp time = 2;
  string user_agent = 3;
}

message Status {
  uint64 height = 1;
  exonum.Hash last_hash = 2;
  uint64 pool_size = 3;
}

message Propose {
  uint32 validator = 1;
  uint64 height = 2;
  uint32 round = 3;
  exonum.Hash prev_hash = 4;
  repeated exonum.Hash transactions = 5;
}

message Prevote {
  uint32 validator = 1;
  uint64 height = 2;
  uint32 round = 3;
  exonum.Hash propose_hash = 4;
  uint32 locked_round = 5;
}

message Precommit {
  uint32 validator = 1;
  uint64 height = 2;
  uint32 round = 3;
  exonum.Hash propose_hash = 4;
  exonum.Hash block_hash = 5;
  google.protobuf.Timestamp time = 6;
}

message BlockResponse {
  exonum.PublicKey to = 1;
  exonum.Block block = 2;
  repeated bytes precommits = 3;
  repeated exonum.Hash transactions = 4;
}

message TransactionsResponse {
  exonum.PublicKey to = 1;
  repeated bytes transactions = 2;
}

message ProposeRequest {
  exonum.PublicKey to = 1;
  uint64 height = 2;
  exonum.Hash propose_hash = 3;
}

message TransactionsRequest {
  exonum.PublicKey to = 1;
  repeated exonum.Hash txs = 2;
}

message PrevotesRequest {
  exonum.PublicKey to = 1;
  uint64 height = 2;
  uint32 round = 3;
  exonum.Hash propose_hash = 4;
  exonum.BitVec validators = 5;
}

message PeersRequest { exonum.PublicKey to = 1; }

message BlockRequest {
  exonum.PublicKey to = 1;
  uint64 height = 2;
}

message PoolTransactionsRequest {
  exonum.PublicKey to = 1;
}

src:./blockchain.proto


// Copyright 2019 The Exonum Team
//
// 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.

syntax = "proto3";

package exonum;

import "helpers.proto";

message Block {
  uint32 proposer_id = 1;
  uint64 height = 2;
  uint32 tx_count = 3;
  exonum.Hash prev_hash = 4;
  exonum.Hash tx_hash = 5;
  exonum.Hash state_hash = 6;
}

message ConfigReference {
  uint64 actual_from = 1;
  exonum.Hash cfg_hash = 2;
}

message TxLocation {
  uint64 block_height = 1;
  uint64 position_in_block = 2;
}

message TransactionResult {
  uint32 status = 1;
  string description = 2;
}

Travel Rule Information Sharing Architecture for Virtual Asset Service Providers (TRISA)

trisacrypto/trisa - github 專案讓錢包或交易所等可符合 Financial Action Task Force (FATF) 的 travel rule 要求。參考報導 CipherTrace Enters Race to Solve Crypto's FATF Compliance Headache - CoinDesk

TOC

WIP 資料可信路徑分享延伸架構

AI「安全性」痛點使用保險轉移風險以及如何精算。

Lloyd’s Of London, Aon And Others Poised To Profit From Cryptocurrency Hacker Insurance

With $300 billion in crypto assets on the planet and less than $1 billion in available insurance coverage, there’s a huge imbalance between supply and demand.

發展 AI + 機械人上,日本也要失敗?(下) - *CUP

儘管技術已經做到頂尖,成本控制也在合理範圍內,但武藏精工卻還是無法完全以 AI 來取代人力。卡在他們眼前的瓶頸,叫做「安全性」。

生成 Google Protocol Buffers 文件

pseudomuto/protoc-gen-doc: Documentation generator plugin for Google Protocol Buffers

git clone https://github.com/trisacrypto/trisa.git /tmp/src/trisa
bash tc.sh --gen-proto-doc /tmp/src/trisa/proto /tmp/output.md

Generated Date:2019-09-11T16:47:55+08:00

Protocol Documentation

Table of Contents

Top

trisa/data/ethereum/v1alpha1/ethereum.proto

Data

FieldTypeLabelDescription
sourcestring
destinationstring
amountint32

Top

trisa/data/bitcoin/v1alpha1/bitcoin.proto

Data

FieldTypeLabelDescription
sourcestring
destinationstring
amountint32

Top

trisa/protocol/v1alpha1/trisa.proto

Transaction

FieldTypeLabelDescription
idstringThe transaction identifier generated by the sender. Any response to a transaction request needs to carry the same identifier.
transactionbytesEncrypted TransactionData
encryption_keybytesEncryption key used to encrypt the transaction blob. This key itself is encrypted using the public key of the receiver.
encryption_algorithmstringThe encryption algorithm used to encrypt the transaction blob.
hmacbytesHMAC signature calculated from encrypted transaction blob.
hmac_secretbytesThe HMAC secret used to calculate the HMAC signature. This secret itself is encrypted using the public key of the receiver.
hmac_algorithmstringThe algorithm used to calculate the HMAC signature.

TransactionData

FieldTypeLabelDescription
identitygoogle.protobuf.AnyIdentity contains any valid identity structure.
datagoogle.protobuf.AnyData contains the network specific data.

TrisaPeer2Peer

Method NameRequest TypeResponse TypeDescription
TransactionStreamTransaction streamTransaction stream

Top

trisa/identity/us/v1alpha1/identity.proto

Identity

FieldTypeLabelDescription
first_namestring
last_namestring
ssnstring
statestring
driver_licensestring

Top

trisa/identity/be/v1alpha1/identity.proto

Identity

FieldTypeLabelDescription
first_namestring
last_namestring
national_numberstring
city_of_birthstring

Top

tvca/discovery/discovery.proto

CRLStore

FieldTypeLabelDescription
revokedstringrepeated

Trisa

FieldTypeLabelDescription
castringURL where the /.well-known/trisa endpoint is located.
x509_root_storestringURL to the root certificate store.
x509_issuer_storestringURL to the intermediate/issuer certificate store.
x509_vasp_storestringURL to the active VASP certificate store.
crl_storestringURL to the CRL store.

X509

FieldTypeLabelDescription
idstring
pemstring

X509Store

FieldTypeLabelDescription
storeX509repeated

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── trisa
│   ├── data
│   │   ├── bitcoin
│   │   │   └── v1alpha1
│   │   │       └── bitcoin.proto
│   │   └── ethereum
│   │       └── v1alpha1
│   │           └── ethereum.proto
│   ├── identity
│   │   ├── be
│   │   │   └── v1alpha1
│   │   │       └── identity.proto
│   │   └── us
│   │       └── v1alpha1
│   │           └── identity.proto
│   └── protocol
│       └── v1alpha1
│           └── trisa.proto
└── tvca
    └── discovery
        └── discovery.proto

15 directories, 6 files

Protobuf sources

src:./trisa/data/ethereum/v1alpha1/ethereum.proto


syntax = "proto3";

package trisa.data.ethereum.v1alpha1;

option go_package = "github.com/trisacrypto/trisa/proto/trisa/data/ethereum/v1alpha1";

message Data {
    string source = 1;
    string destination = 2;
    int32 amount = 3;
}

src:./trisa/data/bitcoin/v1alpha1/bitcoin.proto


syntax = "proto3";

package trisa.data.bitcoin.v1alpha1;

option go_package = "github.com/trisacrypto/trisa/proto/trisa/data/bitcoin/v1alpha1";

message Data {
    string source = 1;
    string destination = 2;
    int32 amount = 3;
}

src:./trisa/protocol/v1alpha1/trisa.proto


syntax = "proto3";

package trisa.protocol.v1alpha1;

import "google/protobuf/any.proto";

option go_package = "github.com/trisacrypto/trisa/proto/trisa/protocol/v1alpha1";

service TrisaPeer2Peer {
    rpc TransactionStream(stream Transaction) returns (stream Transaction) {}
}

message Transaction {
    // The transaction identifier generated by the sender. Any response
    // to a transaction request needs to carry the same identifier.
    string id = 1;

    // Encrypted TransactionData
    bytes transaction = 2;

    // Encryption key used to encrypt the transaction blob. This key itself
    // is encrypted using the public key of the receiver.
    bytes encryption_key = 3;

    // The encryption algorithm used to encrypt the transaction blob.
    string encryption_algorithm = 4;

    // HMAC signature calculated from encrypted transaction blob.
    bytes hmac = 5;

    // The HMAC secret used to calculate the HMAC signature. This secret
    // itself is encrypted using the public key of the receiver.
    bytes hmac_secret = 6;

    // The algorithm used to calculate the HMAC signature.
    string hmac_algorithm = 7;
}

message TransactionData {
    // Identity contains any valid identity structure.
    google.protobuf.Any identity = 1;

    // Data contains the network specific data.
    google.protobuf.Any data = 2;
}

src:./trisa/identity/us/v1alpha1/identity.proto


syntax = "proto3";

package trisa.identity.us.v1alpha1;

option go_package = "github.com/trisacrypto/trisa/proto/trisa/identity/us/v1alpha1";

message Identity {
    string first_name = 1;
    string last_name = 2;
    string ssn = 3;
    string state = 4;
    string driver_license = 5;
}

src:./trisa/identity/be/v1alpha1/identity.proto


syntax = "proto3";

package trisa.identity.be.v1alpha1;

option go_package = "github.com/trisacrypto/trisa/proto/trisa/identity/be/v1alpha1";

message Identity {
    string first_name = 1;
    string last_name = 2;
    string national_number = 3;
    string city_of_birth = 4;
}

src:./tvca/discovery/discovery.proto


syntax = "proto3";

package trisa.tvca.discovery;

option go_package = "github.com/trisacrypto/trisa/proto/tvca/discovery";

message Trisa {
    // URL where the /.well-known/trisa endpoint is located.
    string ca = 1;

    // URL to the root certificate store.
    string x509_root_store = 2;

    // URL to the intermediate/issuer certificate store.
    string x509_issuer_store = 3;

    // URL to the active VASP certificate store.
    string x509_vasp_store = 4;

    // URL to the CRL store.
    string crl_store = 5;
}

message X509Store {
    repeated X509 store = 1;
}

message X509 {
    string id = 1;
    string pem = 2;
}

message CRLStore {
    repeated string revoked = 1;
}

xuperchain

xuperunion/pb at master · xuperchain/xuperunion

TOC

Create Google Protocol Buffers docs

git clone https://github.com/xuperchain/xuperunion.git /tmp/src/xuperunion
bash tc.sh --gen-proto-doc /tmp/src/xuperunion/pb /tmp/output.md

Generated Date:2019-09-12T15:04:36+08:00

Protocol Documentation

Table of Contents

Top

chainedbft.proto

ChainedBftPhaseMessage

ChainedBftPhaseMessage is the proposal message of the protocal. In Hotstuff, there are two kinds of messages, "NEW_VIEW_MESSAGE" and "QC_Message". A stable leader can skip this "NEW_VIEW_MESSAGE".

FieldTypeLabelDescription
TypeQCStateMessage Type: NEW_VIEW_MESSAGE or QC_MESSAGE
ViewNumberint64ViewNumber the current view number
ProposalQCQuorumCertThe new proposal send to other replicas while the
JustifyQCQuorumCertJustifyQC is the QC of the leader gathered, send to next leader, while the message type is "NEW_VIEW_MESSAGE"
MsgDigestbytesMsgDigest is the digest of the msgg
SignatureSignInfoSignature for this msg

ChainedBftVoteMessage

ChainedBftVoteMessage is the vote message of the protocal.

FieldTypeLabelDescription
ProposalIdbytesThe id of this message votes for.
SignatureSignInfoReplica will sign the QCMessage if the QuorumCert if valid.

QCSignInfos

QCSignInfos is the signs of the leader gathered from replicas of a specifically certType. A slice of signs is used at present. TODO @qizheng09: It will be change to Threshold-Signatures after Crypto lib support Threshold-Signatures.

FieldTypeLabelDescription
QCSignInfosSignInforepeatedQCSignInfos

QuorumCert

QuorumCert is a data type that combines a collection of signatures from replicas.

FieldTypeLabelDescription
ProposalIdbytesThe id of Proposal this QC certified.
ProposalMsgbytesThe msg of Proposal this QC certified.
TypeQCStateThe current type of this QC certified. the type contains NEW_VIEW, PREPARE
ViewNumberint64The view number of this QC certified.
SignInfosQCSignInfosSignInfos is the signs of the leader gathered from replicas of a specifically certType.

SignInfo

SignInfo is the signature information of the

FieldTypeLabelDescription
Addressstring
PublicKeystring
Signbytes

QCState

QCState is the phase of hotstuff

NameNumberDescription
NEW_VIEW0
PREPARE1
PRE_COMMIT2
COMMIT3
DECIDE4

Top

xcheck.proto

ComplianceCheckResponse

FieldTypeLabelDescription
headerHeader
signatureSignatureInfo

TransferCheckResponse

FieldTypeLabelDescription
headerHeader
signatureSignatureInfo

Xcheck

Method NameRequest TypeResponse TypeDescription
ComplianceCheckTxStatusComplianceCheckResponse
TransferCheckTxStatusTransferCheckResponse

Top

xchain_spv.proto

ECDSAAccount

助记词、私钥的json、公钥的json、钱包地址

FieldTypeLabelDescription
entropyBytebytes
mnemonicstring
jsonPrivateKeystring
jsonPublicKeystring
addressstring

ECDSAAccountFromCloud

钱包地址、被加密后的私钥、被加密后的助记词

FieldTypeLabelDescription
addressstring
jsonEncryptedPrivateKeystring
encryptedMnemonicstring

ECDSAAccountToCloud

钱包地址、被加密后的私钥、被加密后的助记词、支付密码的明文

FieldTypeLabelDescription
addressstring
jsonEncryptedPrivateKeystring
encryptedMnemonicstring
passwordstring

ECDSAInfo

助记词、随机字节数组、钱包地址

FieldTypeLabelDescription
entropyBytebytes
mnemonicstring
addressstring

Node

全节点

FieldTypeLabelDescription
hostbytes
utxoQueryUrlbytes
txPostUrlbytes
balanceQueryUrlbytes

TxInputs

交易输入列表

FieldTypeLabelDescription
txInputListTxInputrepeated

TxOutputs

交易输出列表

FieldTypeLabelDescription
txOutputListTxOutputrepeated

UTXO

未花费的交易输出

FieldTypeLabelDescription
amountbytes
toAddrbytes
toPubkeybytes
refTxidbytes
refOffsetint32

UTXOs

未花费的交易输出列表

FieldTypeLabelDescription
uTXOListUTXOrepeated

ReturnCode

ReturnCode is the code for client

NameNumberDescription
RETURNSUCCESS0Operation success
INTERNALERR101000Err about Account
FILENOTEXIST101002
PARAMERR101003
HTTPREQUERTFAIL101004
HTTPRESPONSEFAIL101005
ACCOUNTNOTEXIST101008
PWNOTEXIST101009
PWEXIST101010
NOTLOGIN101012
CONNECTNODEFAIL102001Err about Transaction
UTXONOTENOUGH102002
ADDRESSINVALID102003
FEEINVALID102004
CONNECTREFUSED102005
UTXOENCRYPTERR102006
FEENOTENOUGN102007
PARAMSINVALID102008
TXSIGNERR102009
REPOSTTXERR102010
BLOCKCHAINNOTEXIST102011
SERVERERR102012

Top

xchain.proto

AK2AccountRequest

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring

AK2AccountResponse

FieldTypeLabelDescription
headerHeader
bcnamestring
accountstringrepeated

Acl

Acl实际使用的结构

FieldTypeLabelDescription
pmPermissionModel采用的权限模型
aksWeightAcl.AksWeightEntryrepeated公钥or账户名 -> 权重
akSetsAkSets

Acl.AksWeightEntry

FieldTypeLabelDescription
keystring
valuedouble

AclStatus

查询Acl

FieldTypeLabelDescription
headerHeader
bcnamestring
accountNamestring
contractNamestring
methodNamestring
confirmedbool
aclAcl

AddressBalanceStatus

FieldTypeLabelDescription
headerHeader
addressstring
tfdsTokenFrozenDetailsrepeated

AddressStatus

FieldTypeLabelDescription
headerHeader
addressstring
bcsTokenDetailrepeated

AkSet

AK集的表示方法

FieldTypeLabelDescription
aksstringrepeated一堆公钥

AkSets

FieldTypeLabelDescription
setsAkSets.SetsEntryrepeated公钥or账户名集
expressionstring表达式,一期不支持表达式,默认集合内是and,集合间是or

AkSets.SetsEntry

FieldTypeLabelDescription
keystring
valueAkSet

BCSpeeds

FieldTypeLabelDescription
BcSpeedBCSpeeds.BcSpeedEntryrepeated

BCSpeeds.BcSpeedEntry

FieldTypeLabelDescription
keystring
valuedouble

BCStatus

BlockChain status

FieldTypeLabelDescription
headerHeader
bcnamestringblock name
metaLedgerMetaledger metadata
blockInternalBlockThe information of the longest block
utxoMetaUtxoMetaUtox information

BCTipStatus

FieldTypeLabelDescription
headerHeader
is_trunk_tipbool

BatchTxs

FieldTypeLabelDescription
headerHeader
TxsTxStatusrepeated

Block

FieldTypeLabelDescription
headerHeader
bcnamestring
blockidbytes
statusBlock.EBlockStatus
blockInternalBlock

BlockChains

FieldTypeLabelDescription
headerHeader
blockchainsstringrepeated

BlockHeight

FieldTypeLabelDescription
headerHeader
bcnamestring
heightint64

BlockID

FieldTypeLabelDescription
headerHeader
bcnamestring
blockidbytes
need_contentboolif need content

是否需要内容 |

CommonIn

FieldTypeLabelDescription
headerHeader

CommonReply

FieldTypeLabelDescription
headerHeader

ContractResponse

ContractResponse is the response returnd by contract

FieldTypeLabelDescription
statusint32
messagestring
bodybytes

ContractStatus

Status of a contract

FieldTypeLabelDescription
contract_namestring
txidstring
descbytes
is_bannedbool

DeployNativeCodeRequest

FieldTypeLabelDescription
headerHeader
bcnamestringchain name
descNativeCodeDescnative code desc
codebytescode is the bytes of binary code
addressstringthe address of deployer
pubkeybytesthe public key of deployer
signbytesthe sign of desc

DeployNativeCodeResponse

FieldTypeLabelDescription
headerHeader

DposCandidatesRequest

候选人列表接口

FieldTypeLabelDescription
headerHeader
bcnamestring

DposCandidatesResponse

候选人列表返回

FieldTypeLabelDescription
headerHeader
candidatesInfostringrepeated

DposCheckResultsRequest

查询检票结果记录请求

FieldTypeLabelDescription
headerHeader
bcnamestring
termint64

DposCheckResultsResponse

查询检票结果记录返回

FieldTypeLabelDescription
headerHeader
termint64
checkResultstringrepeated

DposNominateInfo

候选人信息

FieldTypeLabelDescription
candidatestring
txidstring

DposNominateRecordsRequest

提名者提名记录请求

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring

DposNominateRecordsResponse

提名者提名记录返回

FieldTypeLabelDescription
headerHeader
nominateRecordsDposNominateInforepeated

DposNomineeRecordsRequest

候选人被提名记录请求

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring

DposNomineeRecordsResponse

候选人被提名记录返回

FieldTypeLabelDescription
headerHeader
txidstring

DposStatus

FieldTypeLabelDescription
termint64
block_numint64
proposerstring
proposer_numint64
checkResultstringrepeated

DposStatusRequest

query dpos consensus current status request

FieldTypeLabelDescription
headerHeader
bcnamestring

DposStatusResponse

query dpos consensus current status reply

FieldTypeLabelDescription
headerHeader
statusDposStatus

DposVoteRecordsRequest

选民投票记录请求

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring

DposVoteRecordsResponse

选民投票记录返回

FieldTypeLabelDescription
headerHeader
voteTxidRecordsvoteRecordrepeated选民投票txid记录

DposVotedRecordsRequest

候选人被投票记录请求

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring

DposVotedRecordsResponse

候选人被投票记录返回

FieldTypeLabelDescription
headerHeader
votedTxidRecordsvotedRecordrepeated候选人被投票的txid记录

GetAccountContractsRequest

Query account contracts request

FieldTypeLabelDescription
headerHeader
bcnamestring
accountstring

GetAccountContractsResponse

Query account contracts response

FieldTypeLabelDescription
headerHeader
contracts_statusContractStatusrepeated

Header

FieldTypeLabelDescription
logidstring如果logid没填写,生成一个
from_nodestringcall rpc client address,客户端可以为空,节点一定要写自己的address
errorXChainErrorEnum

IdentityAuth

Identity authentication request

FieldTypeLabelDescription
signbytes
pubkeybytes
addrstring
peerIDstring
timestampstring

IdentityAuths

Identity authentication requests

FieldTypeLabelDescription
authIdentityAuthrepeated

InternalBlock

The internal block struct

FieldTypeLabelDescription
versionint32block version
nonceint32Random number used to avoid replay attacks
blockidbytesblockid generate the hash sign of the block used by sha256
pre_hashbytespre_hash is the parent blockid of the block
proposerbytesThe miner id
signbytesThe sign which miner signed: blockid + nonce + timestamp
pubkeybytesThe pk of the miner
merkle_rootbytesThe Merkle Tree root
heightint64The height of the blockchain
timestampint64Timestamp of the block
transactionsTransactionrepeatedTransactions of the block, only txid stored on kv, the detail information stored in another table
tx_countint32The transaction count of the block
merkle_treebytesrepeated所有交易hash的merkle tree
curTermint64
curBlockNumint64
failed_txsInternalBlock.FailedTxsEntryrepeatedtxid -> failed reason
targetBitsint32
JustifyQuorumCertJustify used in chained-bft
in_trunkbool下面的属性会动态变化 If the block is on the trunk
next_hashbytesNext next block which on trunk

InternalBlock.FailedTxsEntry

FieldTypeLabelDescription
keystring
valuestring

InvokeRPCRequest

FieldTypeLabelDescription
headerHeader
bcnamestring
requestsInvokeRequestrepeated
initiatorstring
auth_requirestringrepeated

InvokeRPCResponse

FieldTypeLabelDescription
headerHeader
bcnamestring
responseInvokeResponse

InvokeRequest

预执行的请求结构

FieldTypeLabelDescription
module_namestring
contract_namestring
method_namestring
argsInvokeRequest.ArgsEntryrepeated
resource_limitsResourceLimitrepeated

InvokeRequest.ArgsEntry

FieldTypeLabelDescription
keystring
valuebytes

InvokeResponse

预执行的返回结构

FieldTypeLabelDescription
inputsTxInputExtrepeated
outputsTxOutputExtrepeated
responsebytesrepeated
gas_usedint64
requestsInvokeRequestrepeated
responsesContractResponserepeated

LedgerMeta

Ledger metadata

FieldTypeLabelDescription
root_blockidbytesroot block id
tip_blockidbytestip block id
trunk_heightint64the height of the trunk
max_block_sizeint64max block size
reserved_contractsInvokeRequestrepeatedpreset contracts
forbidden_contractInvokeRequestreset forbidden contract configuration

NativeCodeDesc

FieldTypeLabelDescription
namestringnative code name
versionstringcode version
digestbytesdigest of binary
prevVersionstringthe previous verion
xuperApiVersionint32xuper api version

NativeCodeStatus

FieldTypeLabelDescription
descNativeCodeDesc
statusint32
healthybool

NativeCodeStatusRequest

FieldTypeLabelDescription
headerHeader
bcnamestring

NativeCodeStatusResponse

FieldTypeLabelDescription
headerHeader
statusNativeCodeStatusrepeated

PermissionModel

FieldTypeLabelDescription
rulePermissionRule
acceptValuedouble取决于用哪种rule, 可以表示签名率,签名数或权重阈值

PreExecWithSelectUTXORequest

PreExecWithSelectUTXORequest preExec + selectUtxo for request

FieldTypeLabelDescription
headerHeader
bcnamestring
addressstring
totalAmountint64
signInfoSignatureInfo
needLockbool
requestInvokeRPCRequest

PreExecWithSelectUTXOResponse

PreExecWithSelectUTXOResponse preExec + selectUtxo for response

FieldTypeLabelDescription
headerHeader
bcnamestring
responseInvokeResponse
utxoOutputUtxoOutputfor preExec & selectUTXO

RawUrl

RawUrl return the node's connect url

FieldTypeLabelDescription
headerHeader
rawUrlstring

ResourceLimit

FieldTypeLabelDescription
typeResourceType
limitint64

SignatureInfo

签名详情

FieldTypeLabelDescription
PublicKeystring
Signbytes

Speeds

FieldTypeLabelDescription
SumSpeedsSpeeds.SumSpeedsEntryrepeated
BcSpeedsSpeeds.BcSpeedsEntryrepeated

Speeds.BcSpeedsEntry

FieldTypeLabelDescription
keystring
valueBCSpeeds

Speeds.SumSpeedsEntry

FieldTypeLabelDescription
keystring
valuedouble

SystemsStatus

FieldTypeLabelDescription
headerHeader
bcs_statusBCStatusrepeated
speedsSpeeds
peerUrlsstringrepeated

SystemsStatusReply

FieldTypeLabelDescription
headerHeader
systems_statusSystemsStatus

TokenDetail

FieldTypeLabelDescription
bcnamestring
balancestring
errorXChainErrorEnum

TokenFrozenDetail

FieldTypeLabelDescription
balancestring
isFrozenbool

TokenFrozenDetails

FieldTypeLabelDescription
bcnamestring
tfdTokenFrozenDetailrepeated
errorXChainErrorEnum

Transaction

Transaction is the information of the transaction

FieldTypeLabelDescription
txidbytestxid is the id of this transaction
blockidbytesthe blockid the transaction belong to
tx_inputsTxInputrepeatedTransaction input list
tx_outputsTxOutputrepeatedTransaction output list
descbytesTransaction description or system contract
coinbaseboolMining rewards
noncestringRandom number used to avoid replay attacks
timestampint64Timestamp to launch the transaction
versionint32tx format version; tx格式版本号
autogenboolauto generated tx
tx_inputs_extTxInputExtrepeated
tx_outputs_extTxOutputExtrepeated
contract_requestsInvokeRequestrepeated
initiatorstring权限系统新增字段 交易发起者, 可以是一个Address或者一个Account
auth_requirestringrepeated交易发起需要被收集签名的AddressURL集合信息,包括用于utxo转账和用于合约调用
initiator_signsSignatureInforepeated交易发起者对交易元数据签名,签名的内容包括auth_require字段
auth_require_signsSignatureInforepeated收集到的签名
received_timestampint64节点收到tx的时间戳,不参与签名
xuper_signXuperSignature统一签名(支持多重签名/环签名等,与initiator_signs/auth_require_signs不同时使用)

TxData

FieldTypeLabelDescription
headerHeader
txidbytesTransaction id
bcnamestringBlock name
from_addrstringAccount which start the transaction
from_pubkeystringThe pk of the account which start the transaction
from_scrkeystringThe sk of the account which start the transaction
user_signbytesif user don't want to provide scrkey, he should sign the txdata into user_sign
accountTxDataAccountrepeatedThe account list accept tx
noncestringRandom number used to avoid replay attacks
timestampint64Timestamp to launch the Tx
descbytes
versionint32tx version

TxDataAccount

FieldTypeLabelDescription
addressstring地址
amountstring金额
frozen_heightint64冻结高度

TxInput

Transaction input

FieldTypeLabelDescription
ref_txidbytesThe transaction id referenced to
ref_offsetint32The output offset of the transaction referenced to
from_addrbytesThe address of the launcher
amountbytesThe amount of the transaction
frozen_heightint64Frozen height

TxInputExt

扩展输入

FieldTypeLabelDescription
bucketstring
keybytes
ref_txidbytes
ref_offsetint32

TxOutput

Transaction output

FieldTypeLabelDescription
amountbytesThe amount of the transaction
to_addrbytesThe address of the launcher
frozen_heightint64Fronzen height

TxOutputExt

扩展输出

FieldTypeLabelDescription
bucketstring
keybytes
valuebytes

TxStatus

FieldTypeLabelDescription
headerHeader
bcnamestring
txidbytes
statusTransactionStatus当前状态
distanceint64离主干末端的距离(如果在主干上)
txTransaction

Utxo

FieldTypeLabelDescription
amountbytes
toAddrbytes
toPubkeybytes
refTxidbytes
refOffsetint32

UtxoInput

UtxoInput query info to query utxos

FieldTypeLabelDescription
headerHeader
bcnamestringwhich bcname to select
addressstringaddress to select
publickeystringpublickey of the address
totalNeedstringtotalNeed refer the total need utxos to select
userSignbytesuserSign of input
needLockboolneed lock

UtxoMeta

Utxo metadata

FieldTypeLabelDescription
latest_blockidbytesutxo vm目前执行到的blockid
lock_key_liststringrepeated
utxo_totalstring当前utxo vm上的总资产
avgDelayint64平均上链延时
unconfirmTxAmountint64待确认交易量

UtxoOutput

UtxoOutput query results

FieldTypeLabelDescription
headerHeader
utxoListUtxorepeatedoutSign return the output bytes outSign = 2; utxo list
totalSelectedstringtotal selected amount

WasmCodeDesc

FieldTypeLabelDescription
runtimestring
compilerstring
digestbytes
vm_compilerstring

XuperSignature

Unified Xuper Signature

FieldTypeLabelDescription
public_keysbytesrepeated
signaturebytes

voteRecord

选民投票记录

FieldTypeLabelDescription
candidatestring
txidstring

votedRecord

候选人被投票记录

FieldTypeLabelDescription
voterstring
txidstring

Block.EBlockStatus

NameNumberDescription
ERROR0
TRUNK1
BRANCH2
NOEXIST3

PermissionRule

-------- Account and Permission Section --------

NameNumberDescription
NULL0无权限控制
SIGN_THRESHOLD1签名阈值策略
SIGN_AKSET2AKSet签名策略
SIGN_RATE3签名率策略
SIGN_SUM4签名个数策略
CA_SERVER5CA服务器鉴权
COMMUNITY_VOTE6社区治理

ResourceType

NameNumberDescription
CPU0
MEMORY1
DISK2
XFEE3the fee used in kernel contract

TransactionStatus

TransactionStatus is the status of transaction

NameNumberDescription
UNDEFINE0Undefined status
NOEXIST1Transaction not exist
CONFIRM2Transaction have been confirmed
FURCATION3Transaction is on the furcation
UNCONFIRM4Transaction have not been confirmed

XChainErrorEnum

NameNumberDescription
SUCCESS0
UNKNOW_ERROR1
CONNECT_REFUSE2
NOT_ENOUGH_UTXO_ERROR3
UTXOVM_ALREADY_UNCONFIRM_ERROR4
UTXOVM_NOT_FOUND_ERROR5
INPUT_OUTPUT_NOT_EQUAL_ERROR6
TX_NOT_FOUND_ERROR7
TX_SIGN_ERROR8
BLOCKCHAIN_NOTEXIST9
VALIDATE_ERROR10
CANNOT_SYNC_BLOCK_ERROR11
CONFIRM_BLOCK_ERROR12
UTXOVM_PLAY_ERROR13
WALK_ERROR14
NOT_READY_ERROR15
BLOCK_EXIST_ERROR16
ROOT_BLOCK_EXIST_ERROR17
TX_DUPLICATE_ERROR19
SERVICE_REFUSED_ERROR20
TXDATA_SIGN_ERROR21
TX_SLE_ERROR25
TX_FEE_NOT_ENOUGH_ERROR26
UTXO_SIGN_ERROR28
DPOS_QUERY_ERROR31
RWSET_INVALID_ERROR33
RWACL_INVALID_ERROR34
GAS_NOT_ENOUGH_ERROR35
TX_VERSION_INVALID_ERROR36
COMPLIANCE_CHECK_NOT_APPROVED37
ACCOUNT_CONTRACT_STATUS_ERROR38
TX_VERIFICATION_ERROR40

Xchain

Xchain is the main interfaces

Method NameRequest TypeResponse TypeDescription
PostTxTxStatusCommonReplyPostTx post Transaction to a node
QueryACLAclStatusAclStatus
GetAccountContractsGetAccountContractsRequestGetAccountContractsResponse
QueryTxTxStatusTxStatusQueryTx query Transaction by TxStatus, Bcname and Txid are required for this
GetBalanceAddressStatusAddressStatusGetBalance get balance of an address, Address is required for this
GetBalanceDetailAddressBalanceStatusAddressBalanceStatusGetFrozenBalance get two kinds of balance 1. Still be frozen of an address 2. Available now of an address Address is required for this
GetFrozenBalanceAddressStatusAddressStatusGetFrozenBalance get balance that still be frozen of an address, Address is required for this
GetBlockBlockIDBlockGetBlock get block by blockid and return if the block in trunk or in branch
GetBlockByHeightBlockHeightBlockGetBlockByHeight get block by height and return if the block in trunk or in branch
GetBlockChainStatusBCStatusBCStatus
GetBlockChainsCommonInBlockChainsGet blockchains query blockchains
GetSystemStatusCommonInSystemsStatusReplyGetSystemStatus query system status
GetNetURLCommonInRawUrlGetNetURL return net url
SelectUTXOUtxoInputUtxoOutput新的Select utxos接口, 不需要签名,可以支持选择账户的utxo
PreExecWithSelectUTXOPreExecWithSelectUTXORequestPreExecWithSelectUTXOResponsePreExecWithSelectUTXO preExec & selectUtxo
DeployNativeCodeDeployNativeCodeRequestDeployNativeCodeResponseNative code deploy interface
NativeCodeStatusNativeCodeStatusRequestNativeCodeStatusResponseNative code status
DposCandidatesDposCandidatesRequestDposCandidatesResponseDposCandidates get all candidates of the tdpos consensus
DposNominateRecordsDposNominateRecordsRequestDposNominateRecordsResponseDposNominateRecords get all records nominated by an user
DposNomineeRecordsDposNomineeRecordsRequestDposNomineeRecordsResponseDposNomineeRecords get nominated record of a candidate
DposVoteRecordsDposVoteRecordsRequestDposVoteRecordsResponseDposVoteRecords get all vote records voted by an user
DposVotedRecordsDposVotedRecordsRequestDposVotedRecordsResponseDposVotedRecords get all vote records of a candidate
DposCheckResultsDposCheckResultsRequestDposCheckResultsResponseDposCheckResults get check results of a specific term
DposStatusDposStatusRequestDposStatusResponseDposStatus get dpos status
GetAccountByAKAK2AccountRequestAK2AccountResponseGetAccountByAK get account sets contain a specific address
PreExecInvokeRPCRequestInvokeRPCResponse预执行合约

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── chainedbft.proto
├── googleapis
│   └── google
│       └── api
│           ├── annotations.proto
│           └── http.proto
├── xchain.proto
├── xchain_spv.proto
└── xcheck.proto

3 directories, 6 files

Protobuf sources

src:./chainedbft.proto


syntax = "proto3";

package pb;

// QCState is the phase of hotstuff
enum QCState {
    NEW_VIEW = 0; 
    PREPARE = 1;
    PRE_COMMIT = 2;
    COMMIT = 3;
    DECIDE = 4;
}

// QuorumCert is a data type that combines a collection of signatures from replicas.
message QuorumCert {
    // The id of Proposal this QC certified.
    bytes ProposalId = 1;
    // The msg of Proposal this QC certified. 
    bytes ProposalMsg = 2;
    // The current type of this QC certified.
    // the type contains `NEW_VIEW`, `PREPARE`
	QCState Type = 3;
	// The view number of this QC certified.
	int64 ViewNumber = 4;
	// SignInfos is the signs of the leader gathered from replicas
    // of a specifically certType.
    QCSignInfos SignInfos  = 5;
}

// QCSignInfos is the signs of the leader gathered from replicas of a specifically certType.
// A slice of signs is used at present.
// TODO @qizheng09: It will be change to Threshold-Signatures after 
// Crypto lib support Threshold-Signatures.
message QCSignInfos {
    // QCSignInfos 
   repeated SignInfo QCSignInfos = 1; 
}

// SignInfo is the signature information of the 
message SignInfo {
  string Address = 1;
  string PublicKey = 2;
  bytes  Sign = 3;
}

// ChainedBftPhaseMessage is the proposal message of the protocal.
// In Hotstuff, there are two kinds of messages, "NEW_VIEW_MESSAGE" and "QC_Message".
// A stable leader can skip this "NEW_VIEW_MESSAGE".
message ChainedBftPhaseMessage {
    // Message Type: NEW_VIEW_MESSAGE or QC_MESSAGE
    QCState Type = 1;
    // ViewNumber the current view number 
    int64 ViewNumber = 2;
    // The new proposal send to other replicas while the 
	QuorumCert ProposalQC = 3;
    // JustifyQC is the QC of the leader gathered, send to next leader, while the message type is "NEW_VIEW_MESSAGE"
    QuorumCert JustifyQC = 4;
    // MsgDigest is the digest of the msgg
    bytes MsgDigest = 5;
    // Signature for this msg
    SignInfo Signature = 6;
}

// ChainedBftVoteMessage is the vote message of the protocal.
message ChainedBftVoteMessage {
    // The id of this message votes for.
    bytes ProposalId = 1;
    // Replica will sign the QCMessage if the QuorumCert if valid.
    SignInfo Signature = 2;
}

src:./xcheck.proto


syntax = "proto3";

package pb;

import "google/api/annotations.proto";
import "xchain.proto";

service Xcheck {
    rpc ComplianceCheck(TxStatus) returns (ComplianceCheckResponse);
    rpc TransferCheck(TxStatus) returns (TransferCheckResponse);
}

message ComplianceCheckResponse {
    Header header = 1;
    SignatureInfo signature = 2;
}

message TransferCheckResponse {
    Header header = 1;
    SignatureInfo signature = 2;
}

src:./xchain_spv.proto


syntax = "proto3";

package pb;

import "google/api/annotations.proto";
import "xchain.proto";

// 助记词、私钥的json、公钥的json、钱包地址
message ECDSAAccount
{
    bytes entropyByte = 1;
    string mnemonic = 2;
    string jsonPrivateKey = 3;
    string jsonPublicKey = 4;
    string address = 5;
}

// 助记词、随机字节数组、钱包地址
message ECDSAInfo
{
    bytes entropyByte = 1;
    string mnemonic = 2;
    string address = 3;
}

// 钱包地址、被加密后的私钥、被加密后的助记词
message ECDSAAccountFromCloud
{
    string address = 1;
    string jsonEncryptedPrivateKey = 2;
    string encryptedMnemonic = 3;
}

// 钱包地址、被加密后的私钥、被加密后的助记词、支付密码的明文
message ECDSAAccountToCloud
{
    string address = 1;
    string jsonEncryptedPrivateKey = 2;
    string encryptedMnemonic = 3;
    string password = 4;
}

// 全节点
message Node
{
    bytes host = 1;
    bytes utxoQueryUrl = 2;
    bytes txPostUrl = 3;
    bytes balanceQueryUrl = 4;
}

// 交易输入列表
message TxInputs
{
    repeated TxInput txInputList = 1;
}
// 交易输出列表
message TxOutputs
{
    repeated TxOutput txOutputList = 1;
}


// 未花费的交易输出列表
message UTXOs
{
    repeated UTXO uTXOList = 1;
}
// 未花费的交易输出
message UTXO
{
    bytes amount = 1;
    bytes toAddr = 2;
    bytes toPubkey = 3;
    bytes refTxid = 4;
    int32 refOffset = 5;
}

// ReturnCode is the code for client
enum ReturnCode {
    // Operation success
       RETURNSUCCESS = 0;
    // Err about Account
       INTERNALERR = 101000;
       FILENOTEXIST = 101002;
       PARAMERR = 101003;
       HTTPREQUERTFAIL = 101004;
       HTTPRESPONSEFAIL = 101005;
       ACCOUNTNOTEXIST = 101008;
       PWNOTEXIST = 101009;
       PWEXIST = 101010;
       NOTLOGIN = 101012;
    // Err about Transaction
       CONNECTNODEFAIL = 102001;
       UTXONOTENOUGH = 102002;
       ADDRESSINVALID = 102003;
       FEEINVALID = 102004;
       CONNECTREFUSED = 102005;
       UTXOENCRYPTERR = 102006;
       FEENOTENOUGN = 102007;
       PARAMSINVALID = 102008;
       TXSIGNERR = 102009;
       REPOSTTXERR = 102010;
       BLOCKCHAINNOTEXIST = 102011;
       SERVERERR = 102012;
    }

src:./xchain.proto


syntax = "proto3";
 
import "google/api/annotations.proto";
import "chainedbft.proto";
package pb;


enum XChainErrorEnum {
  SUCCESS = 0;
  UNKNOW_ERROR = 1;
  CONNECT_REFUSE = 2;
  NOT_ENOUGH_UTXO_ERROR = 3;
  UTXOVM_ALREADY_UNCONFIRM_ERROR = 4;
  UTXOVM_NOT_FOUND_ERROR = 5;
  INPUT_OUTPUT_NOT_EQUAL_ERROR = 6;
  TX_NOT_FOUND_ERROR = 7;
  TX_SIGN_ERROR = 8;
  BLOCKCHAIN_NOTEXIST = 9;
  VALIDATE_ERROR = 10;
  CANNOT_SYNC_BLOCK_ERROR = 11;
  CONFIRM_BLOCK_ERROR = 12;
  UTXOVM_PLAY_ERROR = 13;
  WALK_ERROR = 14;
  NOT_READY_ERROR = 15;
  BLOCK_EXIST_ERROR = 16;
  ROOT_BLOCK_EXIST_ERROR = 17;
  TX_DUPLICATE_ERROR = 19;
  SERVICE_REFUSED_ERROR = 20;
  TXDATA_SIGN_ERROR = 21;
  TX_SLE_ERROR = 25;
  TX_FEE_NOT_ENOUGH_ERROR = 26;
  UTXO_SIGN_ERROR = 28;
  DPOS_QUERY_ERROR = 31;
  RWSET_INVALID_ERROR = 33;
  RWACL_INVALID_ERROR = 34;
  GAS_NOT_ENOUGH_ERROR = 35;
  TX_VERSION_INVALID_ERROR = 36;
  COMPLIANCE_CHECK_NOT_APPROVED = 37;
  ACCOUNT_CONTRACT_STATUS_ERROR = 38;
  TX_VERIFICATION_ERROR = 40;
}

// TransactionStatus is the status of transaction
enum TransactionStatus {
  // Undefined status
  UNDEFINE = 0;
  // Transaction not exist
  NOEXIST = 1;
  // Transaction have been confirmed
  CONFIRM = 2;
  // Transaction is on the furcation
  FURCATION = 3;
  // Transaction have not been confirmed
  UNCONFIRM = 4;
}

// Xchain is the main interfaces
service Xchain {

  // PostTx post Transaction to a node
  rpc PostTx(TxStatus) returns (CommonReply) {
    option (google.api.http) = {
      post : "/v1/post_tx"
      body : "*"
    };
  }

  rpc QueryACL(AclStatus) returns (AclStatus) {
    option (google.api.http) = {
      post : "/v1/query_acl"
      body : "*"
    };
  }

  rpc GetAccountContracts(GetAccountContractsRequest)
      returns (GetAccountContractsResponse) {
    option (google.api.http) = {
      post : "/v1/get_account_contracts"
      body : "*"
    };
  }

  // QueryTx query Transaction by TxStatus,
  // Bcname and Txid are required for this
  rpc QueryTx(TxStatus) returns (TxStatus) {
    option (google.api.http) = {
      post : "/v1/query_tx"
      body : "*"
    };
  }

  // GetBalance get balance of an address,
  // Address is required for this
  rpc GetBalance(AddressStatus) returns (AddressStatus) {
    option (google.api.http) = {
      post : "/v1/get_balance"
      body : "*"
    };
  }
  
  // GetFrozenBalance get two kinds of balance
  // 1. Still be frozen of an address
  // 2. Available now of an address
  // Address is required for this
  rpc GetBalanceDetail(AddressBalanceStatus) returns (AddressBalanceStatus) {
  option (google.api.http) = {
    post: "/v1/get_balance_detail"
    body: "*"
    };
  }

  // GetFrozenBalance get balance that still be frozen of an address,
  // Address is required for this
  rpc GetFrozenBalance(AddressStatus) returns (AddressStatus) {
    option (google.api.http) = {
      post : "/v1/get_frozen_balance"
      body : "*"
    };
  }

  // GetBlock get block by blockid and return if the block in trunk or in branch
  rpc GetBlock(BlockID) returns (Block) {
    option (google.api.http) = {
      post : "/v1/get_block"
      body : "*"
    };
  }

  // GetBlockByHeight get block by height and return if the block in trunk or in
  // branch
  rpc GetBlockByHeight(BlockHeight) returns (Block) {
    option (google.api.http) = {
      post : "/v1/get_block_by_height"
      body : "*"
    };
  }

  rpc GetBlockChainStatus(BCStatus) returns (BCStatus) {
    option (google.api.http) = {
      post : "/v1/get_bcstatus"
      body : "*"
    };
  }

  // Get blockchains query blockchains
  rpc GetBlockChains(CommonIn) returns (BlockChains) {
    option (google.api.http) = {
      get : "/v1/get_bcchains"
      // body: "*"
    };
  }

  // GetSystemStatus query system status
  rpc GetSystemStatus(CommonIn) returns (SystemsStatusReply) {
    option (google.api.http) = {
      post : "/v1/get_sysstatus"
      body : "*"
    };
  }

  // GetNetURL return net url
  rpc GetNetURL(CommonIn) returns (RawUrl) {}

  // 新的Select utxos接口, 不需要签名,可以支持选择账户的utxo
  rpc SelectUTXO(UtxoInput) returns (UtxoOutput) {
    option (google.api.http) = {
      post : "/v1/select_utxos_v2"
      body : "*"
    };
  }

  // PreExecWithSelectUTXO preExec & selectUtxo
  rpc PreExecWithSelectUTXO(PreExecWithSelectUTXORequest) returns (PreExecWithSelectUTXOResponse);

  // Native code deploy interface
  rpc DeployNativeCode(DeployNativeCodeRequest)
      returns (DeployNativeCodeResponse);
  // Native code status
  rpc NativeCodeStatus(NativeCodeStatusRequest)
      returns (NativeCodeStatusResponse);

  /*
   * DPoS query interface
   */
  //  DposCandidates get all candidates of the tdpos consensus
  rpc DposCandidates(DposCandidatesRequest) returns (DposCandidatesResponse);
  //  DposNominateRecords get all records nominated by an user
  rpc DposNominateRecords(DposNominateRecordsRequest)
      returns (DposNominateRecordsResponse);
  //  DposNomineeRecords get nominated record of a candidate
  rpc DposNomineeRecords(DposNomineeRecordsRequest)
      returns (DposNomineeRecordsResponse);
  //  DposVoteRecords get all vote records voted by an user
  rpc DposVoteRecords(DposVoteRecordsRequest) returns (DposVoteRecordsResponse);
  //  DposVotedRecords get all vote records of a candidate
  rpc DposVotedRecords(DposVotedRecordsRequest)
      returns (DposVotedRecordsResponse);
  //  DposCheckResults get check results of a specific term
  rpc DposCheckResults(DposCheckResultsRequest)
      returns (DposCheckResultsResponse);

  // DposStatus get dpos status
  rpc DposStatus(DposStatusRequest) returns (DposStatusResponse);

  // GetAccountByAK get account sets contain a specific address
  rpc GetAccountByAK(AK2AccountRequest) returns (AK2AccountResponse) {
    option (google.api.http) = {
      post : "/v1/get_account_by_ak"
      body : "*"
    };
  }

  //预执行合约
  rpc PreExec(InvokeRPCRequest) returns (InvokeRPCResponse);
}

message Header {
  string logid = 1;  //如果logid没填写,生成一个
  string from_node = 2;  //call rpc client address,客户端可以为空,节点一定要写自己的address
  XChainErrorEnum error = 3;
}

message TxDataAccount {
  string address = 1;  //地址
  string amount = 2;  //金额
  int64 frozen_height = 3; //冻结高度
}

message TxData {
  Header header = 13;
  // Transaction id
  bytes txid = 1;
  // Block name
  string bcname = 2;
  // Account which start the transaction
  string from_addr = 3;
  // The pk of the account which start the transaction
  string from_pubkey = 4;
  // The sk of the account which start the transaction
  string from_scrkey = 5;
  // if user don't want to provide scrkey, he should sign the txdata into
  // user_sign
  bytes user_sign = 14;
  // The account list accept tx
  repeated TxDataAccount account = 6;
  // Random number used to avoid replay attacks
  string nonce = 8;
  // Timestamp to launch the Tx
  int64 timestamp = 9;
  bytes desc = 12;
  // tx version
  int32 version = 15;
}

message TxStatus {
  Header header = 1;
  string bcname = 2;
  bytes txid = 3;
  TransactionStatus status = 4;  //当前状态
  int64 distance = 5;  //离主干末端的距离(如果在主干上)
  Transaction tx = 7;
}

message BatchTxs {
  Header header = 1;
  repeated TxStatus Txs = 2;
}

message Block {
  Header header = 1;
  string bcname = 2;
  bytes blockid = 3;
  enum EBlockStatus {
    ERROR = 0;
    TRUNK = 1;
    BRANCH = 2;
    NOEXIST = 3;
  }
  EBlockStatus status = 4;
  InternalBlock block = 5;
}

message BlockID {
  Header header = 4;
  string bcname = 1;
  bytes blockid = 2;
  // if need content
  bool need_content = 3;  //是否需要内容
}

message BlockHeight {
  Header header = 3;
  string bcname = 1;
  int64 height = 2;
}

message CommonReply { Header header = 1; }

message CommonIn { Header header = 1; }

message TokenDetail {
  string bcname = 1;
  string balance = 2;
  XChainErrorEnum error = 3;
}

message AddressStatus {
  Header header = 1;
  string address = 2;
  repeated TokenDetail bcs = 3;
}

message TokenFrozenDetail
{
  string balance = 1;
  bool isFrozen = 2;
}

message TokenFrozenDetails
{
  string bcname = 1;
  repeated TokenFrozenDetail tfd = 2;
  XChainErrorEnum error  = 3;
}

message AddressBalanceStatus
{
  Header header = 1;
  string address = 2;
  repeated TokenFrozenDetails tfds = 3;
}

// Transaction input
message TxInput {
  // The transaction id referenced to
  bytes ref_txid = 1;
  // The output offset of the transaction referenced to
  int32 ref_offset = 2;
  // The address of the launcher
  bytes from_addr = 5;
  // The amount of the transaction
  bytes amount = 6;
  // Frozen height
  int64 frozen_height = 7;
}

// Transaction output
message TxOutput {
  // The amount of the transaction
  bytes amount = 1;
  // The address of the launcher
  bytes to_addr = 2;
  // Fronzen height
  int64 frozen_height = 4;
}

// Unified Xuper Signature
message XuperSignature {
  repeated bytes public_keys = 1;
  bytes signature = 2;
}

// Transaction is the information of the transaction
message Transaction {
  // txid is the id of this transaction
  bytes txid = 1;
  // the blockid the transaction belong to
  bytes blockid = 2;
  // Transaction input list
  repeated TxInput tx_inputs = 3;
  // Transaction output list
  repeated TxOutput tx_outputs = 4;
  // Transaction description or system contract
  bytes desc = 6;
  // Mining rewards
  bool coinbase = 7;
  // Random number used to avoid replay attacks
  string nonce = 8;
  // Timestamp to launch the transaction
  int64 timestamp = 9;
  // tx format version; tx格式版本号
  int32 version = 10;
  // auto generated tx
  bool autogen = 11;

  repeated TxInputExt tx_inputs_ext = 23;
  repeated TxOutputExt tx_outputs_ext = 24;
  repeated InvokeRequest contract_requests = 25;

  // 权限系统新增字段
  // 交易发起者, 可以是一个Address或者一个Account
  string initiator = 26;
  // 交易发起需要被收集签名的AddressURL集合信息,包括用于utxo转账和用于合约调用
  repeated string auth_require = 27;
  // 交易发起者对交易元数据签名,签名的内容包括auth_require字段
  repeated SignatureInfo initiator_signs = 28;
  // 收集到的签名
  repeated SignatureInfo auth_require_signs = 29;
  // 节点收到tx的时间戳,不参与签名
  int64 received_timestamp = 30;
  // 统一签名(支持多重签名/环签名等,与initiator_signs/auth_require_signs不同时使用)
  XuperSignature xuper_sign = 31;
}

// Ledger metadata
message LedgerMeta {
  // root block id
  bytes root_blockid = 1;
  // tip block id
  bytes tip_blockid = 2;
  // the height of the trunk
  int64 trunk_height = 3;
  // max block size
  int64 max_block_size = 4;
  // preset contracts
  repeated InvokeRequest reserved_contracts = 5;
  // reset forbidden contract configuration
  InvokeRequest forbidden_contract = 6;
}

// Utxo metadata
message UtxoMeta {
  bytes latest_blockid = 1; // utxo vm目前执行到的blockid
  repeated string lock_key_list = 2;
  string utxo_total = 3;       // 当前utxo vm上的总资产
  int64 avgDelay = 4;          // 平均上链延时
  int64 unconfirmTxAmount = 5; // 待确认交易量
}

// The internal block struct
message InternalBlock {
  // block version
  int32 version = 1;
  // Random number used to avoid replay attacks
  int32 nonce = 2;
  // blockid generate the hash sign of the block used by sha256
  bytes blockid = 3;
  // pre_hash is the parent blockid of the block
  bytes pre_hash = 4;
  // The miner id
  bytes proposer = 5;
  // The sign which miner signed: blockid + nonce + timestamp
  bytes sign = 6;
  // The pk of the miner
  bytes pubkey = 7;
  // The Merkle Tree root
  bytes merkle_root = 8;
  // The height of the blockchain
  int64 height = 9;
  // Timestamp of the block
  int64 timestamp = 10;
  // Transactions of the block, only txid stored on kv, the detail information
  // stored in another table
  repeated Transaction transactions = 11;
  // The transaction count of the block
  int32 tx_count = 12;
  // 所有交易hash的merkle tree
  repeated bytes merkle_tree = 13;
  int64 curTerm = 16;
  int64 curBlockNum = 17;
  map<string, string> failed_txs = 18; // txid -> failed reason
  int32 targetBits = 19;

  // Justify used in chained-bft
  QuorumCert Justify = 20;
  
  // 下面的属性会动态变化
  // If the block is on the trunk
  bool in_trunk = 14;
  // Next next block which on trunk
  bytes next_hash = 15;
}

// BlockChain status
message BCStatus {
  Header header = 1;
  // block name
  string bcname = 2;
  // ledger metadata
  LedgerMeta meta = 3;
  // The information of the longest block
  InternalBlock block = 4;
  // Utox information
  UtxoMeta utxoMeta = 5;
}

message BCTipStatus {
  Header header = 1;
  bool is_trunk_tip = 2;
}

message BlockChains {
  Header header = 1;
  repeated string blockchains = 2;
}

message Speeds {
  map<string, double> SumSpeeds = 1;
  map<string, BCSpeeds> BcSpeeds = 2;
}

message BCSpeeds { map<string, double> BcSpeed = 1; }

message SystemsStatus {
  Header header = 1;
  repeated BCStatus bcs_status = 2;
  Speeds speeds = 3;
  repeated string peerUrls = 4;
}

message SystemsStatusReply {
  Header header = 1;
  SystemsStatus systems_status = 2;
}

// RawUrl return the node's  connect url
message RawUrl {
  Header header = 1;
  string rawUrl = 2;
}

message Utxo {
  bytes amount = 1;
  bytes toAddr = 2;
  bytes toPubkey = 3;
  bytes refTxid = 4;
  int32 refOffset = 5;
}

// UtxoInput query info to query utxos
message UtxoInput {
  Header header = 1;
  // which bcname to select
  string bcname = 2;
  // address to select
  string address = 3;
  // publickey of the address
  string publickey = 4;
  // totalNeed refer the total need utxos to select
  string totalNeed = 5;
  // userSign of input
  bytes userSign = 7;
  // need lock
  bool needLock = 8;
}

// UtxoOutput query results
message UtxoOutput {
  Header header = 1;
  // outSign return the output
  // bytes outSign = 2;
  // utxo list
  repeated Utxo utxoList = 2;
  // total selected amount
  string totalSelected = 3;
}

message NativeCodeDesc {
  // native code name
  string name = 1;
  // code version
  string version = 2;
  // digest of binary
  bytes digest = 3;
  // the previous verion
  string prevVersion = 4;
  // xuper api version
  int32 xuperApiVersion = 5;
}

message WasmCodeDesc {
  string runtime = 1;
  string compiler = 2;
  bytes digest = 3;
  string vm_compiler = 4;
}

message DeployNativeCodeRequest {
  Header header = 1;
  // chain name
  string bcname = 2;
  // native code desc
  NativeCodeDesc desc = 3;
  // code is the bytes of binary code
  bytes code = 4;
  // the address of deployer
  string address = 5;
  // the public key of deployer
  bytes pubkey = 6;
  // the sign of desc
  bytes sign = 7;
}

message DeployNativeCodeResponse { Header header = 1; }

message NativeCodeStatus {
  NativeCodeDesc desc = 1;
  int32 status = 2;
  bool healthy = 3;
}

message NativeCodeStatusRequest {
  Header header = 1;
  string bcname = 2;
}

message NativeCodeStatusResponse {
  Header header = 1;
  repeated NativeCodeStatus status = 2;
}

/*
 * DPoS query interface
 */
// 候选人列表接口
message DposCandidatesRequest {
  Header header = 1;
  string bcname = 2;
}

// 候选人列表返回
message DposCandidatesResponse {
  Header header = 1;
  repeated string candidatesInfo = 2;
}

// 提名者提名记录请求
message DposNominateRecordsRequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
}

// 候选人信息
message DposNominateInfo {
  string candidate = 1;
  string txid = 2;
}

// 提名者提名记录返回
message DposNominateRecordsResponse {
  Header header = 1;
  repeated DposNominateInfo nominateRecords = 2;
}

// 候选人被提名记录请求
message DposNomineeRecordsRequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
}

// 候选人被提名记录返回
message DposNomineeRecordsResponse {
  Header header = 1;
  string txid = 2;
}

// 选民投票记录请求
message DposVoteRecordsRequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
}

// 选民投票记录
message voteRecord {
  string candidate = 1;
  string txid = 2;
}

// 选民投票记录返回
message DposVoteRecordsResponse {
  Header header = 1;
  // 选民投票txid记录
  repeated voteRecord voteTxidRecords = 2;
}

// 候选人被投票记录请求
message DposVotedRecordsRequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
}
// 候选人被投票记录
message votedRecord {
  string voter = 1;
  string txid = 2;
}

// 候选人被投票记录返回
message DposVotedRecordsResponse {
  Header header = 1;
  // 候选人被投票的txid记录
  repeated votedRecord votedTxidRecords = 2;
}

// 查询检票结果记录请求
message DposCheckResultsRequest {
  Header header = 1;
  string bcname = 2;
  int64 term = 3;
}

// 查询检票结果记录返回
message DposCheckResultsResponse {
  Header header = 1;
  int64 term = 2;
  repeated string checkResult = 3;
}

// query dpos consensus current status request
message DposStatusRequest {
  Header header = 1;
  string bcname = 2;
}

// query dpos consensus current status reply
message DposStatusResponse {
  Header header = 1;
  DposStatus status = 2;
}

message DposStatus {
  int64 term = 1;
  int64 block_num = 2;
  string proposer = 3;
  int64 proposer_num = 4;
  repeated string checkResult = 5;
}

message InvokeRPCRequest {
  Header header = 1;
  string bcname = 2;
  repeated InvokeRequest requests = 3;
  string initiator = 4;
  repeated string auth_require = 5;
}

message InvokeRPCResponse {
  Header header = 1;
  string bcname = 2;
  InvokeResponse response = 3;
}

// 预执行的请求结构
message InvokeRequest {
  string module_name = 1;
  string contract_name = 2;
  string method_name = 3;
  map<string, bytes> args = 4;
  repeated ResourceLimit resource_limits = 5;
}

// 预执行的返回结构
message InvokeResponse {
  repeated TxInputExt inputs = 1;
  repeated TxOutputExt outputs = 2;
  repeated bytes response = 3;
  int64 gas_used = 4;
  repeated InvokeRequest requests = 5;
  repeated ContractResponse responses = 6;
}

// 扩展输入
message TxInputExt {
  string bucket = 1;
  bytes key = 2;
  bytes ref_txid = 3;
  int32 ref_offset = 4;
}

// 扩展输出
message TxOutputExt {
  string bucket = 1;
  bytes key = 2;
  bytes value = 3;
}

// 签名详情
message SignatureInfo {
  string PublicKey = 1;
  bytes Sign = 2;
}

// --------   Account and Permission Section --------
enum PermissionRule {
  NULL = 0;           // 无权限控制
  SIGN_THRESHOLD = 1; // 签名阈值策略
  SIGN_AKSET = 2;     // AKSet签名策略
  SIGN_RATE = 3;      // 签名率策略
  SIGN_SUM = 4;       // 签名个数策略
  CA_SERVER = 5;      // CA服务器鉴权
  COMMUNITY_VOTE = 6; // 社区治理
}

message PermissionModel {
  PermissionRule rule = 1;
  double acceptValue = 2; // 取决于用哪种rule, 可以表示签名率,签名数或权重阈值
}

// AK集的表示方法
message AkSet {
  repeated string aks = 1; // 一堆公钥
}
message AkSets {
  map<string, AkSet> sets = 1; // 公钥or账户名集
  string expression =
      2; // 表达式,一期不支持表达式,默认集合内是and,集合间是or
}

// Acl实际使用的结构
message Acl {
  PermissionModel pm = 1;            // 采用的权限模型
  map<string, double> aksWeight = 2; // 公钥or账户名  -> 权重
  AkSets akSets = 3;
}

// 查询Acl
message AclStatus {
  Header header = 1;
  string bcname = 2;
  string accountName = 3;
  string contractName = 4;
  string methodName = 5;
  bool confirmed = 6;
  Acl acl = 7;
}

// Identity authentication request
message IdentityAuth {
  bytes sign = 1;
  bytes pubkey = 2;
  string addr = 3;
  string peerID = 4;
  string timestamp = 5;
}

// Identity authentication requests
message IdentityAuths { repeated IdentityAuth auth = 1; }

enum ResourceType {
  CPU = 0;
  MEMORY = 1;
  DISK = 2;
  XFEE = 3; // the fee used in kernel contract
}

message ResourceLimit {
  ResourceType type = 1;
  int64 limit = 2;
}

message AK2AccountRequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
}

message AK2AccountResponse {
  Header header = 1;
  string bcname = 2;
  repeated string account = 3;
}

// Query account contracts request
message GetAccountContractsRequest {
  Header header = 1;
  string bcname = 2;
  string account = 3;
}

// Query account contracts response
message GetAccountContractsResponse {
  Header header = 1;
  repeated ContractStatus contracts_status = 2;
}

// Status of a contract
message ContractStatus {
  string contract_name = 1;
  string txid = 2;
  bytes desc = 3;
  bool is_banned = 4;
}

// PreExecWithSelectUTXORequest preExec + selectUtxo for request
message PreExecWithSelectUTXORequest {
  Header header = 1;
  string bcname = 2;
  string address = 3;
  int64 totalAmount = 4;
  SignatureInfo signInfo = 6;
  bool needLock = 7;
  InvokeRPCRequest request = 5;
}

// PreExecWithSelectUTXOResponse preExec + selectUtxo for response
message PreExecWithSelectUTXOResponse {
  Header header = 1;
  string bcname = 2;
  InvokeResponse response = 3;
  // for preExec & selectUTXO
  UtxoOutput utxoOutput = 4;
}

// ContractResponse is the response returnd by contract
message ContractResponse {
  int32  status = 1;
  string message = 2;
  bytes  body = 3;
}

TrustWallet

wallet-core/src/proto at master · trustwallet/wallet-core

如何生成 Google Protocol Buffers 文件

pseudomuto/protoc-gen-doc: Documentation generator plugin for Google Protocol Buffers

git clone https://github.com/trustwallet/wallet-core.git /tmp/src/trustwallet-core
bash tc.sh --gen-proto-doc /tmp/src/trustwallet-core/src/proto /tmp/output.md

Generated Date:2019-09-12T11:57:39+08:00

Protocol Documentation

Table of Contents

Top

Ethereum.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
chain_idbytesChain identifier (256-bit number)
noncebytesNonce (256-bit number)
gas_pricebytesGas price (256-bit number)
gas_limitbytesGas limit (256-bit number)
to_addressstringRecipient's address.
amountbytesAmount to send in wei (256-bit number)
payloadbytesOptional payload
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.
vbytes
rbytes
sbytes

Top

Semux.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
private_keybytes
destinationstring
valueuint64
feeuint64
nonceuint64current latest transaction serial number
timestampuint64current timestamp in millisecond

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytes

Top

Aion.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
noncebytesNonce (256-bit number)
gas_pricebytesGas price (256-bit number)
gas_limitbytesGas limit (256-bit number)
to_addressstringRecipient's address.
amountbytesAmount to send in wei (256-bit number)
payloadbytesOptional payload
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.
signaturebytesSignature.

Top

Cosmos.proto

Amount

Amount

FieldTypeLabelDescription
denomstring
amountint64

Fee

Fee

FieldTypeLabelDescription
amountsAmountrepeated
gasuint64

SendCoinsMessage

Message for sending coins.

FieldTypeLabelDescription
from_addressstring
to_addressstring
amountsAmountrepeated
type_prefixstringdefault is cosmos-sdk/MsgSend

Signature

Signature

FieldTypeLabelDescription
public_keybytes
signaturebytes

SigningInput

Input data necessary to create a signed order.

FieldTypeLabelDescription
account_numberuint64
chain_idstring
feeFee
memostring
sequenceuint64
private_keybytes
send_coins_messageSendCoinsMessage
stake_messageStakeMessage
unstake_messageStakeMessage
withdraw_stake_reward_messageWithdrawStakeRewardMessage
type_prefixstringdefault is cosmos-sdk/MsgSend

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
signaturebytesSignature
jsonstringSigned transaction in JSON.

StakeMessage

Message for staking.

FieldTypeLabelDescription
delegator_addressstring
validator_addressstring
amountAmount
type_prefixstringcosmos-sdk/MsgDelegate to stake and cosmos-sdk/MsgUndelegate to unstake

Transaction

Transaction

FieldTypeLabelDescription
feeFee
memostring
signatureSignature
send_coins_messageSendCoinsMessage
stake_messageStakeMessage
unstake_messageStakeMessage
withdraw_stake_reward_messageWithdrawStakeRewardMessage

WithdrawStakeRewardMessage

Message for staking.

FieldTypeLabelDescription
delegator_addressstring
validator_addressstring
type_prefixstringdefault is cosmos-sdk/MsgWithdrawDelegationReward

Top

ARK.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
typeTransactionTypeTransaction type
amountuint64Amount to send
feeuint64Fee
to_addressstringRecipient's address.
timestampuint32Timestamp
private_keybytesPrivate key.

SigningOutput

FieldTypeLabelDescription
encodedstringJSON-encoded transaction parameters.
signaturebytesSignature.

TransactionType

NameNumberDescription
Transfer0

Top

IoTeX.proto

Action

FieldTypeLabelDescription
coreActionCore
senderPubKeybytes
signaturebytes

ActionCore

FieldTypeLabelDescription
versionuint32
nonceuint64
gasLimituint64
gasPricestring
transferTransfer
executionExecution

Execution

FieldTypeLabelDescription
amountstring
contractstring
databytes

SigningInput

transaction signing input

FieldTypeLabelDescription
versionuint32
nonceuint64
gasLimituint64
gasPricestring
privateKeybytes
transferTransfer
executionExecution

SigningOutput

transaction signing output

FieldTypeLabelDescription
encodedbytesSigned and encoded Action bytes
hashbytesSigned Action hash

Transfer

FieldTypeLabelDescription
amountstring
recipientstring
payloadbytes

Top

Bitcoin.proto

OutPoint

Bitcoin transaction out-point reference.

FieldTypeLabelDescription
hashbytesThe hash of the referenced transaction.
indexuint32The index of the specific output in the transaction.
sequenceuint32Transaction version as defined by the sender.

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
hash_typeuint32Hash type to use when signing.
amountint64Amount to send.
byte_feeint64Transaction fee per byte.
to_addressstringRecipient's address.
change_addressstringChange address.
private_keybytesrepeatedAvailable private keys.
scriptsSigningInput.ScriptsEntryrepeatedAvailable redeem scripts indexed by script hash.
utxoUnspentTransactionrepeatedAvailable unspent transaction outputs.
use_max_amountboolIf sending max amount.
coin_typeuint32Coin type (forks).

SigningInput.ScriptsEntry

FieldTypeLabelDescription
keystring
valuebytes

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
transactionTransactionResulting transaction. Note that the amount may be different than the requested amount to account for fees and available funds.
encodedbytesSigned and encoded transaction bytes.
feeint64Total transaction fees.
max_amountint64Maximum spendable amount.
transaction_idstringTransaction id

Transaction

FieldTypeLabelDescription
versionsint32Transaction data format version.
lockTimeuint32The block number or timestamp at which this transaction is unlocked.
inputsTransactionInputrepeatedA list of 1 or more transaction inputs or sources for coins.
outputsTransactionOutputrepeatedA list of 1 or more transaction outputs or destinations for coins

TransactionInput

Bitcoin transaction input.

FieldTypeLabelDescription
previousOutputOutPointReference to the previous transaction's output.
sequenceuint32Transaction version as defined by the sender.
scriptbytesComputational script for confirming transaction authorization.

TransactionOutput

Bitcoin transaction output.

FieldTypeLabelDescription
valueint64Transaction amount.
scriptbytesUsually contains the public key as a Bitcoin script setting up conditions to claim this output.

TransactionPlan

Describes a preliminary transaction plan.

FieldTypeLabelDescription
amountint64Amount to be received at the other end.
available_amountint64Maximum available amount.
feeint64Estimated transaction fee.
changeint64Change.
utxosUnspentTransactionrepeatedSelected unspent transaction outputs.

UnspentTransaction

FieldTypeLabelDescription
out_pointOutPoint
scriptbytes
amountint64

Top

Decred.proto

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
transactionTransactionResulting transaction. Note that the amount may be different than the requested amount to account for fees and available funds.
encodedbytesSigned and encoded transaction bytes.
feeint64Total transaction fees.
max_amountint64Maximum spendable amount.
transaction_idstringTransaction id

Transaction

FieldTypeLabelDescription
serializeTypeuint32Serialization format
versionuint32Transaction data format version
inputsTransactionInputrepeatedA list of 1 or more transaction inputs or sources for coins.
outputsTransactionOutputrepeatedA list of 1 or more transaction outputs or destinations for coins
lockTimeuint32The time when a transaction can be spent (usually zero, in which case it has no effect).
expiryuint32The block height at which the transaction expires and is no longer valid.

TransactionInput

Decred transaction input.

FieldTypeLabelDescription
previousOutputTW.Bitcoin.Proto.OutPointReference to the previous transaction's output.
sequenceuint32Transaction version as defined by the sender.
valueInint64
blockHeightuint32
blockIndexuint32
scriptbytesComputational script for confirming transaction authorization.

TransactionOutput

Decred transaction output.

FieldTypeLabelDescription
valueint64Transaction amount.
versionuint32Transaction output version.
scriptbytesUsually contains the public key as a Decred script setting up conditions to claim this output.

Top

Zilliqa.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
versionuint32Transaction version
nonceuint64Nonce
to_addressstringRecipient's address.
amountbytesAmount to send (256-bit number)
gas_pricebytesGasPrice (256-bit number)
gas_limituint64GasLimit
private_keybytesPrivate Key
codebytesSmart contract code
databytesString-ified JSON object specifying the transition parameter

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
signaturebytesSigned signature bytes.

Top

Solana.proto

DeactivateStake

FieldTypeLabelDescription
private_keybytesThe stake account private key
vote_pubkeystring

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
transfer_transactionTransfer
stake_transactionStake
deactivate_stake_transactionDeactivateStake
withdraw_transactionWithdrawStake
recent_blockhashstring

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytes

Stake

FieldTypeLabelDescription
from_private_keybytes
stake_private_keybytes
vote_pubkeystring
valueuint64

Transfer

FieldTypeLabelDescription
private_keybytes
recipientstring
valueuint64

WithdrawStake

FieldTypeLabelDescription
private_keybytesThe stake account private key
recipientstring
valueuint64

Top

Ontology.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
contractstring
methodstring
owner_private_keybytes
to_addressstringbase58 encode address string (160-bit number)
amountuint64
payer_private_keybytes
gas_priceuint64
gas_limituint64
query_addressstringbase58 encode address string (160-bit number)
nonceuint32

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.

Top

Stellar.proto

MemoHash

FieldTypeLabelDescription
hashbytes

MemoId

FieldTypeLabelDescription
idint64

MemoText

FieldTypeLabelDescription
textstring

MemoVoid

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
amountint64
feeint32
sequenceint64
accountstring
destinationstring
private_keybytesPrivate key.
memo_voidMemoVoid
memo_textMemoText
memo_idMemoId
memo_hashMemoHash
memo_return_hashMemoHash
operation_typeSigningInput.OperationType
passphrasestring

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
signaturestringSignature.

SigningInput.OperationType

NameNumberDescription
CREATE_ACCOUNT0
PAYMENT1

Top

Waves.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
amountint64
assetstring
feeint64minimum 0.001 Waves (100000 Wavelets) for now
fee_assetstring
tostring
attachmentbytesany 140 bytes payload, will be displayed to the client as utf-8 string
timestampint64in millis
private_keybytes

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
signaturebytes
jsonstring

Top

Common.proto

Result

Result type.

FieldTypeLabelDescription
successboolWhether the operation was successful.
errorstringOptional error message, only present if success is false.
objectsgoogle.protobuf.AnyrepeatedResult objects, if any.

Top

Ripple.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
amountint64
feeint64
sequenceint32
last_ledger_sequenceint32
accountstring
destinationstring
destination_tagint64
flagsint64
private_keybytes

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytes

Top

Binance.proto

CancelTradeOrder

FieldTypeLabelDescription
senderbytes0x166E681B // prefix

originating address | | symbol | string | | symbol for trading pair in full name of the tokens | | refid | string | | order id to cancel |

ClaimHTLOrder

FieldTypeLabelDescription
frombytes0xC1665300 // prefix

signer address | | swap_id | bytes | | | | random_number | bytes | | |

DepositHTLTOrder

FieldTypeLabelDescription
frombytes0xB33F9A24 // prefix

signer address | | amount | SendOrder.Token | repeated | | | swap_id | bytes | | |

HTLTOrder

FieldTypeLabelDescription
frombytes0xB33F9A24 // prefix

signer address | | to | bytes | | recipient address | | recipient_other_chain | string | | | | sender_other_chain | string | | | | random_number_hash | bytes | | hash of a random number and timestamp, based on SHA256 | | timestamp | int64 | | | | amount | SendOrder.Token | repeated | | | expected_income | string | | expected gained token on the other chain | | height_span | int64 | | | | cross_chain | bool | | |

RefundHTLTOrder

FieldTypeLabelDescription
frombytes0x3454A27C // prefix

signer address | | swap_id | bytes | | |

SendOrder

FieldTypeLabelDescription
inputsSendOrder.Inputrepeated
outputsSendOrder.Outputrepeated

SendOrder.Input

FieldTypeLabelDescription
addressbytes
coinsSendOrder.Tokenrepeated

SendOrder.Output

FieldTypeLabelDescription
addressbytes
coinsSendOrder.Tokenrepeated

SendOrder.Token

0x2A2C87FA

FieldTypeLabelDescription
denomstring
amountint64

Signature

FieldTypeLabelDescription
pub_keybytespublic key bytes of the signer address
signaturebytessignature bytes, please check chain access section for signature generation
account_numberint64another identifier of signer, which can be read from chain by account REST API or RPC
sequenceint64sequence number for the next transaction

Signature.PubKey

0xEB5AE987 // prefix bytes // public key bytes

SigningInput

Input data necessary to create a signed order.

FieldTypeLabelDescription
chain_idstring
account_numberint64
sequenceint64
sourceint64
memostring
private_keybytes
trade_orderTradeOrder
cancel_trade_orderCancelTradeOrder
send_orderSendOrder
freeze_orderTokenFreezeOrder
unfreeze_orderTokenUnfreezeOrder
htlt_orderHTLTOrder
depositHTLT_orderDepositHTLTOrder
claimHTLT_orderClaimHTLOrder
refundHTLT_orderRefundHTLTOrder

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.

TokenFreezeOrder

FieldTypeLabelDescription
frombytes0xE774B32D // prefix

owner address | | symbol | string | | token symbol, in full name with "-" suffix | | amount | int64 | | amount of token to freeze |

TokenUnfreezeOrder

FieldTypeLabelDescription
frombytes0x6515FF0D // prefix

owner address | | symbol | string | | token symbol, in full name with "-" suffix | | amount | int64 | | amount of token to unfreeze |

TradeOrder

FieldTypeLabelDescription
senderbytes0xCE6DC043 // prefix

originating address | | id | string | | order id, optional | | symbol | string | | symbol for trading pair in full name of the tokens | | ordertype | int64 | | only accept 2 for now, meaning limit order | | side | int64 | | 1 for buy and 2 fory sell | | price | int64 | | price of the order, which is the real price multiplied by 1e8 (10^8) and rounded to integer | | quantity | int64 | | quantity of the order, which is the real price multiplied by 1e8 (10^8) and rounded to integer | | timeinforce | int64 | | 1 for Good Till Expire(GTE) order and 3 for Immediate Or Cancel (IOC) |

Transaction

FieldTypeLabelDescription
msgsbytesrepeatedint64 SIZE-OF-ENCODED // varint encoded length of the structure after encoding 0xF0625DEE // prefix

array of size 1, containing the transaction message, which are one of the transaction type below | | signatures | bytes | repeated | array of size 1, containing the standard signature structure of the transaction sender | | memo | string | | a short sentence of remark for the transaction, only for Transfer transactions. | | source | int64 | | an identifier for tools triggerring this transaction, set to zero if unwilling to disclose. | | data | bytes | | reserved for future use |

Top

Icon.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
from_addressstringSender address.
to_addressstringRecipient address.
valuebytesTransfer amount.
step_limitbytesThe amount of step to send with the transaction.
timestampint64UNIX epoch time (from 1970.1.1 00:00:00) in microseconds
noncebytesInteger value increased by request to avoid replay attacks.
network_idbytesNetwork identifier
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedstringJSON-encoded transaction parameters.
signaturebytesSignature.

Top

VeChain.proto

Clause

FieldTypeLabelDescription
tostringRecipient address.
valuebytesTransaction amount.
databytesPayload data.

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
chain_taguint32Last byte of the genesis block ID which is used to identify a blockchain to prevent the cross-chain replay attack.
block_refuint64Reference to a specific block.
expirationuint32How long, in terms of the number of blocks, the transaction will be allowed to be mined in VeChainThor.
clausesClauserepeatedAn array of Clause objects. / / Each clause contains fields To, Value and Data to enable a single transaction to carry multiple tasks issued / by the transaction sender.
gas_price_coefuint32Coefficient used to calculate the gas price for the transaction.
gasuint64Maximum amount of gas allowed to pay for the transaction.
depends_onbytesID of the transaction on which the current transaction depends.
nonceuint64Number set by user.
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.
signaturebytesSignature.

Top

Tezos.proto

DelegationOperationData

Delegation operation specific data. Next field: 2

FieldTypeLabelDescription
delegatestring

Operation

An operation that can be applied to the Tezos blockchain. Next field: 12

FieldTypeLabelDescription
counterint64
sourcestring
feeint64
gas_limitint64
storage_limitint64
kindOperation.OperationKind
reveal_operation_dataRevealOperationData
transaction_operation_dataTransactionOperationData
origination_operation_dataOriginationOperationData
delegation_operation_dataDelegationOperationData

OperationList

A list of operations and a branch. Next field: 3

FieldTypeLabelDescription
branchstring
operationsOperationrepeated

OriginationOperationData

Origination operation specific data. Next field: 3

FieldTypeLabelDescription
manager_pubkeystring
balanceint64

RevealOperationData

Reveal operation specific data. Next field: 2

FieldTypeLabelDescription
public_keybytes

SigningInput

Input data necessary to create a signed Tezos transaction. Next field: 3

FieldTypeLabelDescription
operation_listOperationList
private_keybytes

SigningOutput

Transaction signing output. Next field: 2

FieldTypeLabelDescription
signed_bytesbytes

TransactionOperationData

Transaction operation specific data. Next field: 3

FieldTypeLabelDescription
destinationstring
amountint64

Operation.OperationKind

NameNumberDescription
ENDORSEMENT0Note: Proto3 semantics require a zero value.
REVEAL7
TRANSACTION8
ORIGINATION9
DELEGATION10

Top

Any.proto

SigningInput

FieldTypeLabelDescription
coin_typeuint32BIP44 network ID
transactionstringJSON transaction
private_keystringPrivate Key in HEX format

SigningOutput

FieldTypeLabelDescription
errorSigningOutput.Error
successbool
outputstring

SigningOutput.Error

FieldTypeLabelDescription
codeuint32Error code
descriptionstringError description

Top

Nebulas.proto

Data

FieldTypeLabelDescription
typestring
payloadbytes

RawTransaction

Raw transaction data

FieldTypeLabelDescription
hashbytes
frombytes
tobytes
valuebytes
nonceuint64
timestampint64
dataData
chain_iduint32
gas_pricebytes
gas_limitbytes
alguint32
signbytes

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
from_addressstringsender's address.
chain_idbytesChain identifier (256-bit number)
noncebytesNonce (256-bit number)
gas_pricebytesGas price (256-bit number)
gas_limitbytesGas limit (256-bit number)
to_addressstringRecipient's address.
amountbytesAmount to send in wei, 1 NAS = 10^18 Wei (256-bit number)
timestampbytesTimestamp to create transaction (256-bit number)
payloadstringOptional payload
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
algorithmuint32
signaturebytes
rawstring

Top

Bravo.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
chain_idbytesChain id (256-bit number)
senderstringSender's username
recipientstringRecipient's username
amountdoubleAmount in "BRAVO" or "TEST"
testnetboolWhether the transaction is for testnet
memostringMemo to attach to the transaction
reference_block_idbytesReference Block Id (160-bits)
reference_block_timesfixed32Timestamp on the reference block
private_keybytesSender's private key's raw bytes

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
json_encodedstringJSON of the signed transaction.

Top

Tron.proto

BlockHeader

FieldTypeLabelDescription
timestampint64
tx_trie_rootbytes
parent_hashbytes
numberint64
witness_addressbytes
versionint32

FreezeBalanceContract

FieldTypeLabelDescription
owner_addressstringSender address.
frozen_balanceint64Frozen balance. Minimum 1
frozen_durationint64Frozen duration
resourcestringResource type: BANDWIDTH
receiver_addressstringReceiver address

SigningInput

FieldTypeLabelDescription
transactionTransactionTransaction.
private_keybytesPrivate key.

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
idbytesTransaction identifier.
signaturebytesSignature.
ref_block_bytesbytes
ref_block_hashbytes

Transaction

FieldTypeLabelDescription
timestampint64Transaction timestamp in milliseconds.
expirationint64Transaction expiration time in milliseconds.
block_headerBlockHeaderTransaction block header.
fee_limitint64Transaction fee limit
transferTransferContract
transfer_assetTransferAssetContract
freeze_balanceFreezeBalanceContract
unfreeze_balanceUnfreezeBalanceContract
unfreeze_assetUnfreezeAssetContract
withdraw_balanceWithdrawBalanceContract
vote_assetVoteAssetContract
vote_witnessVoteWitnessContract
trigger_smart_contractTriggerSmartContract

TransferAssetContract

FieldTypeLabelDescription
asset_namestringAsset name.
owner_addressstringSender address.
to_addressstringRecipient address.
amountint64Amount to send.

TransferContract

FieldTypeLabelDescription
owner_addressstringSender address.
to_addressstringRecipient address.
amountint64Amount to send.

TriggerSmartContract

FieldTypeLabelDescription
owner_addressstring
contract_addressstring
call_valueint64
databytes
call_token_valueint64
token_idint64

UnfreezeAssetContract

FieldTypeLabelDescription
owner_addressstringSender address

UnfreezeBalanceContract

FieldTypeLabelDescription
owner_addressstringSender address
resourcestringResource type: BANDWIDTH
receiver_addressstringReceiver address

VoteAssetContract

FieldTypeLabelDescription
owner_addressstringSender address
vote_addressstringrepeatedVote addresses
supportbool
countint32

VoteWitnessContract

FieldTypeLabelDescription
owner_addressstring
votesVoteWitnessContract.Voterepeated
supportbool

VoteWitnessContract.Vote

FieldTypeLabelDescription
vote_addressstring
vote_countint64

WithdrawBalanceContract

FieldTypeLabelDescription
owner_addressstringSender address

Top

Theta.proto

SigningInput

Input data necessary to create a signed transaction

FieldTypeLabelDescription
chain_idstringChain ID string, mainnet, testnet and privatenet
to_addressstringRecipient address
theta_amountbytesTheta token amount to send in wei (256-bit number)
tfuel_amountbytesTFuel token amount to send in wei (256-bit number)
sequenceuint64Sequence number of the transaction for the sender address
feebytesFee amount in TFuel wei for the transaction (256-bit number)
private_keybytesPrivate key

SigningOutput

Transaction signing output

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes
signaturebytesSignature

Top

Aeternity.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
from_addressstringAddress of the sender with "ak_" prefix
to_addressstringAddress of the recipient with "ak_" prefix
amountbytes
feebytes
payloadstringMessage, optional
ttluint64Time to live until block height
nonceuint64
private_keybytes

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedstringSigned and encoded transaction bytes, Base64 with checksum
signaturestringSignature, Base58 with checksum

Top

Nimiq.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
private_keybytes
destinationstring
valueuint64
feeuint64
validity_start_heightuint32

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytes

Top

Harmony.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
chain_idbytesChain identifier (256-bit number)
noncebytesNonce (256-bit number)
gas_pricebytesGas price (256-bit number)
gas_limitbytesGas limit (256-bit number)
to_addressstringRecipient's address.
amountbytesAmount to send in wei (256-bit number)
payloadbytesOptional payload
private_keybytesPrivate key.
from_shard_idbytesFrom shard ID (256-bit number)
to_shard_idbytesTo Shard ID (256-bit number)

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
encodedbytesSigned and encoded transaction bytes.
vbytes
rbytes
sbytes

Top

EOS.proto

Asset

Values for an Asset object.

FieldTypeLabelDescription
amountint64
decimalsuint32
symbolstring

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
chain_idbytesChain id (256-bit number)
reference_block_idbytesReference Block Id (256-bits)
reference_block_timesfixed32Timestamp on the reference block
currencystringCurrency (e.g. "eosio.token")
senderstringSender's username
recipientstringRecipient's username
memostringMemo attached to the transaction
assetAssetAsset details and amount
private_keybytesSender's private key's raw bytes
private_key_typeKeyTypeType of the private key

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
json_encodedstringJSON of the packed transaction.

KeyType

NameNumberDescription
LEGACY0
MODERNK11
MODERNR12

Top

Nano.proto

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
private_keybytesPrivate key
parent_blockbytesOptional parent block hash
link_blockbytesHash of a block to receive from
link_recipientstringRecipient address to send coins to
representativestringRepresentative address
balancestringAccount balance (128-bit unsigned integer, as a string)

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
signaturebytesSignature
block_hashbytesBlock hash

Top

IOST.proto

AccountInfo

FieldTypeLabelDescription
namestring
active_keybytes
owner_keybytes

Action

The message defines transaction action struct.

FieldTypeLabelDescription
contractstringcontract name
action_namestringaction name
datastringdata

AmountLimit

The message defines transaction amount limit struct.

FieldTypeLabelDescription
tokenstringtoken name
valuestringlimit value

Signature

The message defines signature struct.

FieldTypeLabelDescription
algorithmAlgorithmsignature algorithm
signaturebytessignature bytes
public_keybytespublic key

SigningInput

Input data necessary to create a signed transaction.

FieldTypeLabelDescription
accountAccountInfo
transaction_templateTransaction
transfer_destinationstring
transfer_amountstring
transfer_memostring

SigningOutput

Transaction signing output.

FieldTypeLabelDescription
transactionTransactionSigned transaction

Transaction

The message defines the transaction request.

FieldTypeLabelDescription
timeint64transaction timestamp
expirationint64expiration timestamp
gas_ratiodoublegas price
gas_limitdoublegas limit
delayint64delay nanoseconds
chain_iduint32chain id
actionsActionrepeatedaction list
amount_limitAmountLimitrepeatedamount limit
signersstringrepeatedsigner list
signaturesSignaturerepeatedsignatures of signers
publisherstringpublisher
publisher_sigsSignaturerepeatedsignatures of publisher

Algorithm

The enumeration defines the signature algorithm.

NameNumberDescription
UNKNOWN0unknown
SECP256K11secp256k1
ED255192ed25519

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── Aeternity.proto
├── Aion.proto
├── Any.proto
├── ARK.proto
├── Binance.proto
├── Bitcoin.proto
├── Bravo.proto
├── Common.proto
├── Cosmos.proto
├── Decred.proto
├── EOS.proto
├── Ethereum.proto
├── Harmony.proto
├── Icon.proto
├── IOST.proto
├── IoTeX.proto
├── Nano.proto
├── Nebulas.proto
├── Nimiq.proto
├── Ontology.proto
├── Ripple.proto
├── Semux.proto
├── Solana.proto
├── Stellar.proto
├── Tezos.proto
├── Theta.proto
├── Tron.proto
├── VeChain.proto
├── Waves.proto
└── Zilliqa.proto

0 directories, 30 files

Protobuf sources

src:./Ethereum.proto


syntax = "proto3";

package TW.Ethereum.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Chain identifier (256-bit number)
    bytes chain_id = 1;

    // Nonce (256-bit number)
    bytes nonce = 2;

    // Gas price (256-bit number)
    bytes gas_price = 3;

    // Gas limit (256-bit number)
    bytes gas_limit = 4;

    // Recipient's address.
    string to_address = 5;

    // Amount to send in wei (256-bit number)
    bytes amount = 6;

    // Optional payload
    bytes payload = 7;

    // Private key.
    bytes private_key = 8;
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;

    bytes v = 2;
    bytes r = 3;
    bytes s = 4;
}

src:./Semux.proto


syntax = "proto3";

package TW.Semux.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    bytes private_key = 1;

    string destination = 2;

    uint64 value = 3;

    uint64 fee = 4;

    // current latest transaction serial number
    uint64 nonce = 5;

    // current timestamp in millisecond
    uint64 timestamp = 6;
}

// Transaction signing output.
message SigningOutput {
    bytes encoded = 1;
}

src:./Aion.proto


syntax = "proto3";

package TW.Aion.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Nonce (256-bit number)
    bytes nonce = 1;

    // Gas price (256-bit number)
    bytes gas_price = 2;

    // Gas limit (256-bit number)
    bytes gas_limit = 3;

    // Recipient's address.
    string to_address = 4;

    // Amount to send in wei (256-bit number)
    bytes amount = 5;

    // Optional payload
    bytes payload = 6;

    // Private key.
    bytes private_key = 7;
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;

    // Signature.
    bytes signature = 2;
}

src:./Cosmos.proto


syntax = "proto3";

package TW.Cosmos.Proto;
option java_package = "wallet.core.jni.proto";

// Amount
message Amount {
    string denom = 1;
    int64 amount = 2;
}

// Fee
message Fee {
    repeated Amount amounts = 1;
    uint64 gas = 2;
}

// Message for sending coins.
message SendCoinsMessage {
    string from_address = 1;
    string to_address = 2;
    repeated Amount amounts = 3;
    // default is cosmos-sdk/MsgSend
    string type_prefix = 4;
}

// Message for staking.
message StakeMessage {
    string delegator_address = 1;
    string validator_address = 2;
    Amount amount = 3;
    // cosmos-sdk/MsgDelegate to stake and cosmos-sdk/MsgUndelegate to unstake
    string type_prefix = 4;
}

// Message for staking.
message WithdrawStakeRewardMessage {
    string delegator_address = 1;
    string validator_address = 2;
    // default is cosmos-sdk/MsgWithdrawDelegationReward
    string type_prefix = 3;
}

// Signature
message Signature {
    bytes public_key = 1;
    bytes signature = 2;
}

// Transaction
message Transaction {
    Fee fee = 1;
    string memo = 2;
    Signature signature = 3;

    oneof message_oneof {
        SendCoinsMessage send_coins_message = 4;
        StakeMessage stake_message = 5;
        StakeMessage unstake_message = 6;
        WithdrawStakeRewardMessage withdraw_stake_reward_message = 7;
    }
}

// Input data necessary to create a signed order.
message SigningInput {
    uint64 account_number = 1;
    string chain_id = 2;
    Fee fee = 3;
    string memo = 4;
    uint64 sequence = 5; 

    bytes private_key = 6;

    oneof message_oneof {
        SendCoinsMessage send_coins_message = 7;
        StakeMessage stake_message = 8;
        StakeMessage unstake_message = 9;
        WithdrawStakeRewardMessage withdraw_stake_reward_message = 10;
    }
    // default is cosmos-sdk/MsgSend
    string type_prefix = 11;
}

// Transaction signing output.
message SigningOutput {
    // Signature
    bytes signature = 1;
    // Signed transaction in JSON.
    string json = 2;
}

src:./ARK.proto


syntax = "proto3";

package TW.ARK.Proto;
option java_package = "wallet.core.jni.proto";

enum TransactionType {
    Transfer = 0;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    // Transaction type
    TransactionType type = 1;

    // Amount to send
    uint64 amount = 2;

    // Fee
    uint64 fee = 3;

    // Recipient's address.
    string to_address = 4;

    // Timestamp
    uint32 timestamp = 5;

    // Private key.
    bytes private_key = 6;
}

message SigningOutput {
    // JSON-encoded transaction parameters.
    string encoded = 1;

    // Signature.
    bytes signature = 2;
}

src:./IoTeX.proto


syntax = "proto3";

package TW.IoTeX.Proto;
option java_package = "wallet.core.jni.proto";

message Transfer {
    string amount  = 1;
    string recipient = 2;
    bytes payload  = 3;
}

message Execution {
    string amount  = 1;
    string contract = 2;
    bytes data = 3;
}

message ActionCore {
    uint32 version = 1;
    uint64 nonce = 2;
    uint64 gasLimit = 3;
    string gasPrice = 4;
    oneof action {
        Transfer transfer = 10;
        Execution execution = 12;
  }
}

message Action {
    ActionCore core = 1;
    bytes senderPubKey = 2;
    bytes signature = 3;
}

// transaction signing input
message SigningInput {
    uint32 version = 1;
    uint64 nonce = 2;
    uint64 gasLimit = 3;
    string gasPrice = 4;
    bytes privateKey = 5;
    oneof action {
        Transfer transfer = 10;
        Execution execution = 12;
  }
}

// transaction signing output
message SigningOutput {
    // Signed and encoded Action bytes
    bytes encoded = 1;

    // Signed Action hash
    bytes hash = 2;
}

src:./Bitcoin.proto


syntax = "proto3";

package TW.Bitcoin.Proto;
option java_package = "wallet.core.jni.proto";

message Transaction {
    // Transaction data format version.
    sint32 version = 1;

    // The block number or timestamp at which this transaction is unlocked.
    uint32 lockTime = 2;

    // A list of 1 or more transaction inputs or sources for coins.
    repeated TransactionInput inputs = 3;

    // A list of 1 or more transaction outputs or destinations for coins
    repeated TransactionOutput outputs = 4;
}

// Bitcoin transaction input.
message TransactionInput {
    // Reference to the previous transaction's output.
    OutPoint previousOutput = 1;

    // Transaction version as defined by the sender.
    uint32 sequence = 2;

    // Computational script for confirming transaction authorization.
    bytes script = 3;
}

// Bitcoin transaction out-point reference.
message OutPoint {
    // The hash of the referenced transaction.
    bytes hash = 1;

    // The index of the specific output in the transaction.
    uint32 index = 2;

    // Transaction version as defined by the sender.
    uint32 sequence = 3;
}

// Bitcoin transaction output.
message TransactionOutput {
    // Transaction amount.
    int64 value = 1;

    // Usually contains the public key as a Bitcoin script setting up conditions to claim this output.
    bytes script = 2;
}

message UnspentTransaction {
    OutPoint out_point = 1;
    bytes script = 2;
    int64 amount = 3;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    // Hash type to use when signing.
    uint32 hash_type = 1;

    // Amount to send.
    int64 amount = 2;

    // Transaction fee per byte.
    int64 byte_fee = 3;

    // Recipient's address.
    string to_address = 4;

    // Change address.
    string change_address = 5;

    // Available private keys.
    repeated bytes private_key = 10;

    // Available redeem scripts indexed by script hash.
    map<string, bytes> scripts = 11;

    // Available unspent transaction outputs.
    repeated UnspentTransaction utxo = 12;

    // If sending max amount.
    bool use_max_amount = 13;

    // Coin type (forks).
    uint32 coin_type = 14;
}

// Describes a preliminary transaction plan.
message TransactionPlan {
    // Amount to be received at the other end.
    int64 amount = 1;

    // Maximum available amount.
    int64 available_amount = 2;

    // Estimated transaction fee.
    int64 fee = 3;

    // Change.
    int64 change = 4;

    // Selected unspent transaction outputs.
    repeated UnspentTransaction utxos = 5;
};

// Transaction signing output.
message SigningOutput {
    // Resulting transaction. Note that the amount may be different than the requested amount to account for fees and available funds.
    Transaction transaction = 1;

    // Signed and encoded transaction bytes.
    bytes encoded = 2;

    // Total transaction fees.
    int64 fee = 3;

    // Maximum spendable amount.
    int64 max_amount = 4;

    // Transaction id
    string transaction_id = 5;
}

src:./Decred.proto


syntax = "proto3";

package TW.Decred.Proto;
option java_package = "wallet.core.jni.proto";

import "Bitcoin.proto";

message Transaction {
    /// Serialization format
    uint32 serializeType = 1;

    /// Transaction data format version
    uint32 version = 2;

    // A list of 1 or more transaction inputs or sources for coins.
    repeated TransactionInput inputs = 3;

    // A list of 1 or more transaction outputs or destinations for coins
    repeated TransactionOutput outputs = 4;

    /// The time when a transaction can be spent (usually zero, in which case it has no effect).
    uint32 lockTime = 5;

    /// The block height at which the transaction expires and is no longer valid.
    uint32 expiry = 6;
}

// Decred transaction input.
message TransactionInput {
    // Reference to the previous transaction's output.
    Bitcoin.Proto.OutPoint previousOutput = 1;

    // Transaction version as defined by the sender.
    uint32 sequence = 2;

	int64 valueIn = 3;
	uint32 blockHeight = 4;
	uint32 blockIndex = 5;

    // Computational script for confirming transaction authorization.
    bytes script = 6;
}

// Decred transaction output.
message TransactionOutput {
    // Transaction amount.
    int64 value = 1;

    /// Transaction output version.
    uint32 version = 2;

    // Usually contains the public key as a Decred script setting up conditions to claim this output.
    bytes script = 3;
}

// Transaction signing output.
message SigningOutput {
    // Resulting transaction. Note that the amount may be different than the requested amount to account for fees and available funds.
    Transaction transaction = 1;

    // Signed and encoded transaction bytes.
    bytes encoded = 2;

    // Total transaction fees.
    int64 fee = 3;

    // Maximum spendable amount.
    int64 max_amount = 4;

    // Transaction id
    string transaction_id = 5;
}

src:./Zilliqa.proto


syntax = "proto3";

package TW.Zilliqa.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Transaction version
    uint32 version         = 1;

    // Nonce
    uint64 nonce           = 2;

    // Recipient's address.
    string to_address      = 3;

    // Amount to send (256-bit number)
    bytes amount           = 4;

    // GasPrice (256-bit number)
    bytes gas_price        = 5;

    // GasLimit
    uint64 gas_limit        = 6;

    // Private Key
    bytes private_key      = 7;

    // Smart contract code
    bytes code             = 10;

    // String-ified JSON object specifying the transition parameter
    bytes data             = 11;
}

// Transaction signing output.
message SigningOutput {
    // Signed signature bytes.
    bytes signature = 1;
}

src:./Solana.proto


syntax = "proto3";

package TW.Solana.Proto;
option java_package = "wallet.core.jni.proto";

message Transfer {
    bytes private_key = 1;
    string recipient = 2;
    uint64 value = 3;
}

message Stake {
    bytes from_private_key = 1;
    bytes stake_private_key = 2;
    string vote_pubkey = 3;
    uint64 value = 4;
}

message DeactivateStake {
    // The stake account private key
    bytes private_key = 1;
    string vote_pubkey = 2;
}

message WithdrawStake {
    // The stake account private key
    bytes private_key = 1;
    string recipient = 2;
    uint64 value = 3;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    oneof transaction_type {
        Transfer transfer_transaction = 1;
        Stake stake_transaction = 2;
        DeactivateStake deactivate_stake_transaction = 3;
        WithdrawStake withdraw_transaction = 4;
    }
    string recent_blockhash = 5;
}

// Transaction signing output.
message SigningOutput {
    bytes encoded = 1;
}

src:./Ontology.proto


syntax = "proto3";

package TW.Ontology.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {

    string contract = 1;

    string method = 2;

    bytes owner_private_key = 3;

    // base58 encode address string (160-bit number)
    string to_address = 4;

    uint64 amount = 5;

    bytes payer_private_key = 6;

    uint64 gas_price = 7;

    uint64 gas_limit = 8;

    // base58 encode address string (160-bit number)
    string query_address = 9;

    uint32 nonce = 10;

}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;
}

src:./Stellar.proto


syntax = "proto3";

package TW.Stellar.Proto;
option java_package = "wallet.core.jni.proto";

message MemoVoid {
}

message MemoText {
    string text = 1;
}

message MemoId {
    int64 id = 1;
}

message MemoHash {
    bytes hash = 1;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    int64 amount = 1;

    int32 fee = 2;

    int64 sequence = 3;

    string account = 4;

    string destination = 5;

    // Private key.
    bytes private_key = 6;

    oneof memo_type_oneof {
        MemoVoid memo_void = 7;
        MemoText memo_text = 8;
        MemoId memo_id = 9;
        MemoHash memo_hash = 10;
        MemoHash memo_return_hash = 11;
    }

    enum OperationType {
        CREATE_ACCOUNT = 0;
        PAYMENT = 1;
    }
    OperationType operation_type = 12;

    string passphrase = 13;
}

// Transaction signing output.
message SigningOutput {
    // Signature.
    string signature = 1;
}

src:./Waves.proto


syntax = "proto3";

package TW.Waves.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    int64 amount = 1;

    string asset = 2;

    // minimum 0.001 Waves (100000 Wavelets) for now
    int64 fee = 3;

    string fee_asset = 4;

    string to = 5;

    // any 140 bytes payload, will be displayed to the client as utf-8 string
    bytes attachment = 6;

    // in millis
    int64 timestamp = 7;

    bytes private_key = 8;
}

// Transaction signing output.
message SigningOutput {
    bytes signature = 1;
    string json = 2;
}

src:./Common.proto


syntax = "proto3";
import "google/protobuf/any.proto";

package TW.Proto;
option java_package = "wallet.core.jni.proto";

// Result type.
message Result {
    // Whether the operation was successful.
    bool success = 1;

    // Optional error message, only present if success is false.
    string error = 2;

    // Result objects, if any.
    repeated google.protobuf.Any objects = 3;
}

src:./Ripple.proto


syntax = "proto3";

package TW.Ripple.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    int64 amount = 1;

    int64 fee = 2;

    int32 sequence = 3;

    int32 last_ledger_sequence = 4;

    string account = 5;

    string destination = 6;

    int64 destination_tag = 7;

    int64 flags = 8;

    bytes private_key = 9;
}

// Transaction signing output.
message SigningOutput {
    bytes encoded = 1;
}

src:./Binance.proto


syntax = "proto3";

package TW.Binance.Proto;
option java_package = "wallet.core.jni.proto";

message Transaction {
    // int64 SIZE-OF-ENCODED      // varint encoded length of the structure after encoding
    // 0xF0625DEE                  // prefix
    repeated bytes msgs = 1;       // array of size 1, containing the transaction message, which are one of the transaction type below
    repeated bytes signatures = 2; // array of size 1, containing the standard signature structure of the transaction sender
    string memo = 3;               // a short sentence of remark for the transaction, only for `Transfer` transactions.
    int64 source = 4;              // an identifier for tools triggerring this transaction, set to zero if unwilling to disclose.
    bytes data = 5;                // reserved for future use
}

message Signature {
    message PubKey {
        // 0xEB5AE987          // prefix
        // bytes               // public key bytes
    }
    bytes pub_key = 1;         // public key bytes of the signer address
    bytes signature = 2;       // signature bytes, please check chain access section for signature generation
    int64 account_number = 3;  // another identifier of signer, which can be read from chain by account REST API or RPC
    int64 sequence = 4;        // sequence number for the next transaction
}

message TradeOrder {
    // 0xCE6DC043           // prefix
    bytes sender = 1;       // originating address
    string id = 2;          // order id, optional
    string symbol = 3;      // symbol for trading pair in full name of the tokens
    int64 ordertype = 4;    // only accept 2 for now, meaning limit order
    int64 side = 5;         // 1 for buy and 2 fory sell
    int64 price = 6;        // price of the order, which is the real price multiplied by 1e8 (10^8) and rounded to integer
    int64 quantity = 7;     // quantity of the order, which is the real price multiplied by 1e8 (10^8) and rounded to integer
    int64 timeinforce = 8;  // 1 for Good Till Expire(GTE) order and 3 for Immediate Or Cancel (IOC)
}

message CancelTradeOrder {
    // 0x166E681B      // prefix
    bytes sender = 1;  // originating address
    string symbol = 2; // symbol for trading pair in full name of the tokens
    string refid = 3;  // order id to cancel
}

message SendOrder {
    // 0x2A2C87FA
    message Token {
        string denom = 1;
        int64 amount = 2;
    }
    message Input {
        bytes address = 1;
        repeated Token coins = 2;
    }
    message Output {
        bytes address = 1;
        repeated Token coins = 2;
    }
    repeated Input inputs = 1;
    repeated Output outputs = 2;
}

message TokenFreezeOrder {
    // 0xE774B32D      // prefix
    bytes from = 1;    // owner address
    string symbol = 2; // token symbol, in full name with "-" suffix
    int64 amount = 3;  // amount of token to freeze
}

message TokenUnfreezeOrder {
    // 0x6515FF0D      // prefix
    bytes from = 1;    // owner address
    string symbol = 2; // token symbol, in full name with "-" suffix
    int64 amount = 3;  // amount of token to unfreeze
}

message HTLTOrder {
    // 0xB33F9A24      // prefix
    bytes from = 1;    // signer address
    bytes to = 2;    // recipient address
    string recipient_other_chain = 3;
    string sender_other_chain = 4;
    bytes random_number_hash = 5; //hash of a random number and timestamp, based on SHA256
    int64 timestamp = 6;
    repeated SendOrder.Token amount = 7;
    string expected_income = 8; // expected gained token on the other chain
    int64 height_span = 9;
    bool cross_chain = 10;
}

message DepositHTLTOrder {
    // 0xB33F9A24      // prefix
    bytes from = 1;    // signer address
    repeated SendOrder.Token amount = 2;
    bytes swap_id = 3;
}

message ClaimHTLOrder {
    // 0xC1665300      // prefix
    bytes from = 1;    // signer address
    bytes swap_id = 2;
    bytes random_number = 3;
}

message RefundHTLTOrder {
    // 0x3454A27C      // prefix
    bytes from = 1;    // signer address
    bytes swap_id = 2;
}

// Input data necessary to create a signed order.
message SigningInput {
    string chain_id = 1;
    int64 account_number = 2;
    int64 sequence = 3;
    int64 source = 4;
    string memo = 5;
    bytes private_key = 6;

    oneof order_oneof {
        TradeOrder trade_order = 8;
        CancelTradeOrder cancel_trade_order = 9;
        SendOrder send_order = 10;
        TokenFreezeOrder freeze_order = 11;
        TokenUnfreezeOrder unfreeze_order = 12;
        HTLTOrder htlt_order = 13;
        DepositHTLTOrder depositHTLT_order = 14;
        ClaimHTLOrder claimHTLT_order = 15;
        RefundHTLTOrder refundHTLT_order = 16;
    }
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;
}

src:./Icon.proto


syntax = "proto3";

package TW.Icon.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Sender address.
    string from_address = 1;

    // Recipient address.
    string to_address = 2;

    // Transfer amount.
    bytes value = 3;

    // The amount of step to send with the transaction.
    bytes step_limit = 4;

    // UNIX epoch time (from 1970.1.1 00:00:00) in microseconds
    int64 timestamp = 5;

    // Integer value increased by request to avoid replay attacks.
    bytes nonce = 6;

    // Network identifier
    bytes network_id = 7;

    // Private key.
    bytes private_key = 8;
}

// Transaction signing output.
message SigningOutput {
    // JSON-encoded transaction parameters.
    string encoded = 1;

    // Signature.
    bytes signature = 2;
}

src:./VeChain.proto


syntax = "proto3";

package TW.VeChain.Proto;
option java_package = "wallet.core.jni.proto";

message Clause {
    /// Recipient address.
    string to = 1;

    /// Transaction amount.
    bytes value = 2;

    /// Payload data.
    bytes data = 3;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    /// Last byte of the genesis block ID which is used to identify a blockchain to prevent the cross-chain replay attack.
    uint32 chain_tag = 1;

    /// Reference to a specific block.
    uint64 block_ref = 2;

    /// How long, in terms of the number of blocks, the transaction will be allowed to be mined in VeChainThor.
    uint32 expiration = 3;

    /// An array of Clause objects.
    ///
    /// Each clause contains fields To, Value and Data to enable a single transaction to carry multiple tasks issued
    /// by the transaction sender.
    repeated Clause clauses = 4;

    /// Coefficient used to calculate the gas price for the transaction.
    uint32 gas_price_coef = 5;

    /// Maximum amount of gas allowed to pay for the transaction.
    uint64 gas = 6;

    /// ID of the transaction on which the current transaction depends.
    bytes depends_on = 7;

    /// Number set by user.
    uint64 nonce = 8;

    // Private key.
    bytes private_key = 9;
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;

    // Signature.
    bytes signature = 2;
}

src:./Tezos.proto


syntax = "proto3";

package TW.Tezos.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed Tezos transaction.
// Next field: 3
message SigningInput {
  OperationList operation_list = 1;
  bytes private_key = 2;
}

// Transaction signing output.
// Next field: 2
message SigningOutput {
  bytes signed_bytes = 1;
}

// A list of operations and a branch.
// Next field: 3
message OperationList {
  string branch = 1;
  repeated Operation operations = 2;
}

// An operation that can be applied to the Tezos blockchain.
// Next field: 12
message Operation {
  int64 counter = 1;
  string source = 2;
  int64 fee = 3;
  int64 gas_limit = 4;
  int64 storage_limit = 5;

  enum OperationKind {
    // Note: Proto3 semantics require a zero value.
    ENDORSEMENT = 0;

    REVEAL = 7;
    TRANSACTION = 8;
    ORIGINATION = 9;
    DELEGATION = 10;
  }
  OperationKind kind = 7;

  // Operation specific data depending on the type of the operation.
  oneof operation_data {
    RevealOperationData reveal_operation_data = 8;
    TransactionOperationData transaction_operation_data = 9;
    OriginationOperationData origination_operation_data = 10;
    DelegationOperationData delegation_operation_data = 11;
  }
}

// Transaction operation specific data.
// Next field: 3
message TransactionOperationData {
  string destination = 1;
  int64 amount = 2;
}

// Reveal operation specific data.
// Next field: 2
message RevealOperationData {
  bytes public_key = 1;
}

// Origination operation specific data.
// Next field: 3
message OriginationOperationData {
  string manager_pubkey = 1;
  int64 balance = 2;
}

// Delegation operation specific data.
// Next field: 2
message DelegationOperationData {
  string delegate = 1;
}

src:./Any.proto


syntax = "proto3";

package TW.Any.Proto;
option java_package = "wallet.core.jni.proto";

message SigningInput {
    // BIP44 network ID
    uint32 coin_type   = 1;
    // JSON transaction
    string transaction = 2;
    // Private Key in HEX format
    string  private_key = 3;
}

message SigningOutput {
    message Error {
        // Error code
        uint32 code        = 1;
        // Error description
        string description = 2;
    }

    oneof result {
        Error error = 1;
        bool success = 2;
    }

    string output = 4;
}

src:./Nebulas.proto


syntax = "proto3";

package TW.Nebulas.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // sender's address.
    string from_address = 1;

    // Chain identifier (256-bit number)
    bytes chain_id = 2;

    // Nonce (256-bit number)
    bytes nonce = 3;

    // Gas price (256-bit number)
    bytes gas_price = 4;

    
    // Gas limit (256-bit number)
    bytes gas_limit = 5;

    // Recipient's address.
    string to_address = 6;

    // Amount to send in wei, 1 NAS = 10^18 Wei (256-bit number)
    bytes amount = 7;

    // Timestamp to create transaction (256-bit number)
    bytes timestamp = 8;

    // Optional payload
    string payload = 9;

    // Private key.
    bytes private_key = 10;
}

// Transaction signing output.
message SigningOutput {
    uint32 algorithm = 1;
    bytes signature = 2;
    string raw = 3;
}

//
message Data {
    string type = 1;
    bytes payload = 2;
}

// Raw transaction data
message RawTransaction {
    bytes hash  = 1;
    bytes from = 2;
    bytes to = 3;
    bytes value = 4;
    uint64 nonce = 5;
    int64 timestamp = 6;
    Data data = 7;
    uint32 chain_id = 8;
    bytes gas_price = 9;
    bytes gas_limit = 10;

    uint32 alg = 11;
    bytes sign = 12;
}

src:./Bravo.proto


syntax = "proto3";

package TW.Bravo.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Chain id (256-bit number)
    bytes chain_id = 1;

    // Sender's username
    string sender = 2;

    // Recipient's username
    string recipient = 3;

    // Amount in "BRAVO" or "TEST"
    double amount = 4;

    // Whether the transaction is for testnet
    bool testnet = 5;

    // Memo to attach to the transaction
    string memo = 6;

    // Reference Block Id (160-bits)
    bytes reference_block_id = 7;

    // Timestamp on the reference block
    sfixed32 reference_block_time = 8;

    // Sender's private key's raw bytes
    bytes private_key = 9;
}

// Transaction signing output.
message SigningOutput {
    // JSON of the signed transaction.
    string json_encoded = 1;
}

src:./Tron.proto


syntax = "proto3";

package TW.Tron.Proto;
option java_package = "wallet.core.jni.proto";

message TransferContract {
    // Sender address.
    string owner_address = 1;

    // Recipient address.
    string to_address = 2;

    // Amount to send.
    int64 amount = 3;
}

message TransferAssetContract {
    // Asset name.
    string asset_name = 1;

    // Sender address.
    string owner_address = 2;

    // Recipient address.
    string to_address = 3;

    // Amount to send.
    int64 amount = 4;
}

message FreezeBalanceContract {
    // Sender address.
    string owner_address = 1;
    // Frozen balance. Minimum 1
    int64 frozen_balance = 2;
    // Frozen duration
    int64 frozen_duration = 3;
    // Resource type: BANDWIDTH | ENERGY
    string resource = 10;
    // Receiver address
    string receiver_address = 15;
}

message UnfreezeBalanceContract {
    // Sender address
    string owner_address = 1;
    // Resource type: BANDWIDTH | ENERGY
    string resource = 10;
    // Receiver address
    string receiver_address = 15;
}

message UnfreezeAssetContract {
    // Sender address
    string owner_address = 1;
}

message VoteAssetContract {
    // Sender address
    string owner_address = 1;
    // Vote addresses
    repeated string vote_address = 2;
    bool support = 3;
    int32 count = 5;
}

message VoteWitnessContract {
    message Vote {
        string vote_address = 1;
        int64 vote_count = 2;
    }
    string owner_address = 1;
    repeated Vote votes = 2;
    bool support = 3;
}

message WithdrawBalanceContract {
    // Sender address
    string owner_address = 1;
}

message TriggerSmartContract {
    string owner_address = 1;
    string contract_address = 2;
    int64 call_value = 3;
    bytes data = 4;
    int64 call_token_value = 5;
    int64 token_id = 6;
}

message BlockHeader {
    int64 timestamp = 1;
    bytes tx_trie_root = 2;
    bytes parent_hash = 3;
    int64 number = 7;
    bytes witness_address = 9;
    int32 version = 10;
}

message Transaction {
    // Transaction timestamp in milliseconds.
    int64 timestamp = 1;

    // Transaction expiration time in milliseconds.
    int64 expiration = 2;

    // Transaction block header.
    BlockHeader block_header = 3;

    // Transaction fee limit
    int64 fee_limit = 4;

    // Contract.
    oneof contract_oneof {
        TransferContract transfer = 10;
        TransferAssetContract transfer_asset = 11;
        FreezeBalanceContract freeze_balance = 12;
        UnfreezeBalanceContract unfreeze_balance = 13;
        UnfreezeAssetContract unfreeze_asset = 14;
        WithdrawBalanceContract withdraw_balance = 15;
        VoteAssetContract vote_asset = 16;
        VoteWitnessContract vote_witness = 17;
        TriggerSmartContract trigger_smart_contract = 18;
    }
}

message SigningInput {
    // Transaction.
    Transaction transaction = 1;

    // Private key.
    bytes private_key = 2;
}

// Transaction signing output.
message SigningOutput {
    // Transaction identifier.
    bytes id = 1;

    // Signature.
    bytes signature = 2;

    bytes ref_block_bytes = 3;
    bytes ref_block_hash = 4;
}

src:./Theta.proto


syntax = "proto3";

package TW.Theta.Proto;
option java_package = "wallet.core.jni.proto";

/// Input data necessary to create a signed transaction
message SigningInput {
    /// Chain ID string, mainnet, testnet and privatenet
    string chain_id = 1;

    /// Recipient address
    string to_address = 2;

    /// Theta token amount to send in wei (256-bit number)
    bytes theta_amount = 3;

    /// TFuel token amount to send in wei (256-bit number)
    bytes tfuel_amount = 4;

    /// Sequence number of the transaction for the sender address
    uint64 sequence = 5;

    /// Fee amount in TFuel wei for the transaction (256-bit number)
    bytes fee = 6;

    /// Private key
    bytes private_key = 7;
}

/// Transaction signing output
message SigningOutput {
    /// Signed and encoded transaction bytes
    bytes encoded = 1;

    /// Signature
    bytes signature = 2;
}

src:./Aeternity.proto


syntax = "proto3";

package TW.Aeternity.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Address of the sender with "ak_" prefix
    string from_address = 1;

    // Address of the recipient with "ak_" prefix
    string to_address = 2;

    bytes amount = 3;

    bytes fee = 4;

    // Message, optional
    string payload = 5;

    // Time to live until block height
    uint64 ttl = 6;

    uint64 nonce = 7;

    bytes private_key = 8;
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes, Base64 with checksum
    string encoded = 1;
    // Signature, Base58 with checksum
    string signature = 2;
}

src:./Nimiq.proto


syntax = "proto3";

package TW.Nimiq.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    bytes private_key = 1;

    string destination = 2;

    uint64 value = 3;

    uint64 fee = 4;

    uint32 validity_start_height = 5;
}

// Transaction signing output.
message SigningOutput {
    bytes encoded = 1;
}

src:./Harmony.proto


syntax = "proto3";

package TW.Harmony.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Chain identifier (256-bit number)
    bytes chain_id = 1;

    // Nonce (256-bit number)
    bytes nonce = 2;

    // Gas price (256-bit number)
    bytes gas_price = 3;

    // Gas limit (256-bit number)
    bytes gas_limit = 4;

    // Recipient's address.
    string to_address = 5;

    // Amount to send in wei (256-bit number)
    bytes amount = 6;

    // Optional payload
    bytes payload = 7;

    // Private key.
    bytes private_key = 8;

    // From shard ID (256-bit number)
    bytes from_shard_id = 9;

    // To Shard ID (256-bit number)
    bytes to_shard_id = 10;
}

// Transaction signing output.
message SigningOutput {
    // Signed and encoded transaction bytes.
    bytes encoded = 1;

    bytes v = 2;
    bytes r = 3;
    bytes s = 4;
}

src:./EOS.proto


syntax = "proto3";

package TW.EOS.Proto;
option java_package = "wallet.core.jni.proto";

enum KeyType {
    LEGACY = 0;
    MODERNK1 = 1;
    MODERNR1 = 2;
}

// Values for an Asset object.
message Asset {
    int64 amount = 1;
    uint32 decimals = 2;
    string symbol = 3;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    // Chain id (256-bit number)
    bytes chain_id = 1;

    // Reference Block Id (256-bits)
    bytes reference_block_id = 2;

    // Timestamp on the reference block
    sfixed32 reference_block_time = 3;
    
    // Currency (e.g. "eosio.token")
    string currency = 4;

    // Sender's username
    string sender = 5;

    // Recipient's username
    string recipient = 6;

    // Memo attached to the transaction
    string memo = 7;

    // Asset details and amount
    Asset asset = 8;

    // Sender's private key's raw bytes
    bytes private_key = 9;

    // Type of the private key
    KeyType private_key_type = 10;
}

// Transaction signing output.
message SigningOutput {
    // JSON of the packed transaction.
    string json_encoded = 1;
}

src:./Nano.proto


syntax = "proto3";

package TW.Nano.Proto;
option java_package = "wallet.core.jni.proto";

// Input data necessary to create a signed transaction.
message SigningInput {
    // Private key
    bytes private_key = 1;

    // Optional parent block hash
    bytes parent_block = 2;

    oneof link_oneof {
        // Hash of a block to receive from
        bytes link_block = 3;
        // Recipient address to send coins to
        string link_recipient = 4;
    }

    // Representative address
    string representative = 5;

    // Account balance (128-bit unsigned integer, as a string)
    string balance = 6;
}

// Transaction signing output.
message SigningOutput {
    // Signature
    bytes signature = 1;
    // Block hash
    bytes block_hash = 2;
}

src:./IOST.proto


syntax = "proto3";

package TW.IOST.Proto;
option java_package = "wallet.core.jni.proto";

// The message defines transaction action struct.
message Action {
    // contract name
    string contract = 1;
    // action name
    string action_name = 2;
    // data
    string data = 3;
}

// The message defines transaction amount limit struct.
message AmountLimit {
    // token name
    string token = 1;
    // limit value
    string value = 2;
}

// The enumeration defines the signature algorithm.
enum Algorithm {
    // unknown
    UNKNOWN = 0;
    // secp256k1
    SECP256K1 = 1;
    // ed25519
    ED25519 = 2;
}

// The message defines signature struct.
message Signature {
    // signature algorithm
    Algorithm algorithm = 1;
    // signature bytes
    bytes signature = 2;
    // public key
    bytes public_key = 3;
}

// The message defines the transaction request.
message Transaction {
    // transaction timestamp
    int64 time = 1;
    // expiration timestamp
    int64 expiration = 2;
    // gas price
    double gas_ratio = 3;
    // gas limit
    double gas_limit = 4;
    // delay nanoseconds
    int64 delay = 5;
    // chain id
    uint32 chain_id = 6;
    // action list
    repeated Action actions = 7;
    // amount limit
    repeated AmountLimit amount_limit = 8;
    // signer list
    repeated string signers = 9;
    // signatures of signers
    repeated Signature signatures = 10;
    // publisher
    string publisher = 11;
    // signatures of publisher
    repeated Signature publisher_sigs = 12;
}

message AccountInfo {
    string name = 1;
    bytes active_key = 2;
    bytes owner_key = 3;
}

// Input data necessary to create a signed transaction.
message SigningInput {
    AccountInfo account = 1;
    Transaction transaction_template = 2;
    string transfer_destination = 3;
    string transfer_amount = 4;
    string transfer_memo = 5;
}

// Transaction signing output.
message SigningOutput {
    // Signed transaction
    Transaction transaction = 1;
}

OpenBazaar

openbazaar-go/pb/protos at master · OpenBazaar/openbazaar-go

如何生成 Google Protocol Buffers 文件

pseudomuto/protoc-gen-doc: Documentation generator plugin for Google Protocol Buffers

git clone https://github.com/OpenBazaar/openbazaar-go.git /tmp/src/openbazaar-go
bash tc.sh --gen-proto-doc /tmp/src/openbazaar-go/pb/protos /tmp/output.md

Generated Date:2019-09-12T11:21:43+08:00

Protocol Documentation

Table of Contents

Top

contracts.proto

BitcoinSignature

FieldTypeLabelDescription
inputIndexuint32
signaturebytes

Dispute

FieldTypeLabelDescription
timestampgoogle.protobuf.Timestamp
claimstring
payoutAddressstring
outpointsOutpointrepeated
serializedContractbytes

DisputeAcceptance

FieldTypeLabelDescription
timestampgoogle.protobuf.Timestamp
closedBystring

DisputeResolution

FieldTypeLabelDescription
timestampgoogle.protobuf.Timestamp
orderIdstring
proposedBystring
resolutionstring
payoutDisputeResolution.Payout
moderatorRatingSigsbytesrepeatedUsed in ratings

DisputeResolution.Payout

FieldTypeLabelDescription
sigsBitcoinSignaturerepeated
inputsOutpointrepeated
buyerOutputDisputeResolution.Payout.Output
vendorOutputDisputeResolution.Payout.Output
moderatorOutputDisputeResolution.Payout.Output

DisputeResolution.Payout.Output

FieldTypeLabelDescription
scriptstring
addressstring
amountuint64

ID

FieldTypeLabelDescription
peerIDstring
handlestring
pubkeysID.Pubkeys
bitcoinSigbytesBitcoin signature covering peerID

ID.Pubkeys

FieldTypeLabelDescription
identitybytesIPFS public key
bitcoinbytesBitcoin public key

Listing

FieldTypeLabelDescription
slugstring
vendorIDID
metadataListing.Metadata
itemListing.Item
shippingOptionsListing.ShippingOptionrepeated
taxesListing.Taxrepeated
couponsListing.Couponrepeated
moderatorsstringrepeated
termsAndConditionsstring
refundPolicystring

Listing.Coupon

FieldTypeLabelDescription
titlestring
hashstring
discountCodestring
percentDiscountfloat
priceDiscountuint64

Listing.Item

FieldTypeLabelDescription
titlestring
descriptionstring
processingTimestring
priceuint64
nsfwbool
tagsstringrepeated
imagesListing.Item.Imagerepeated
categoriesstringrepeated
gramsfloat
conditionstring
optionsListing.Item.Optionrepeated
skusListing.Item.Skurepeated

Listing.Item.Image

FieldTypeLabelDescription
filenamestring
originalstring
largestring
mediumstring
smallstring
tinystring

Listing.Item.Option

FieldTypeLabelDescription
namestring
descriptionstring
variantsListing.Item.Option.Variantrepeated

Listing.Item.Option.Variant

FieldTypeLabelDescription
namestring
imageListing.Item.Image

Listing.Item.Sku

FieldTypeLabelDescription
variantCombouint32repeated
productIDstring
surchargeint64
quantityint64Not saved with listing

Listing.Metadata

FieldTypeLabelDescription
versionuint32
contractTypeListing.Metadata.ContractType
formatListing.Metadata.Format
expirygoogle.protobuf.Timestamp
acceptedCurrenciesstringrepeated
pricingCurrencystring
languagestring
escrowTimeoutHoursuint32
coinTypestring
coinDivisibilityuint32
priceModifierfloat

Listing.ShippingOption

FieldTypeLabelDescription
namestring
typeListing.ShippingOption.ShippingType
regionsCountryCoderepeated
servicesListing.ShippingOption.Servicerepeated

Listing.ShippingOption.Service

FieldTypeLabelDescription
namestring
priceuint64
estimatedDeliverystring
additionalItemPriceuint64

Listing.Tax

FieldTypeLabelDescription
taxTypestring
taxRegionsCountryCoderepeated
taxShippingbool
percentagefloat

Order

FieldTypeLabelDescription
refundAddressstring
refundFeeuint64
shippingOrder.Shipping
buyerIDID
timestampgoogle.protobuf.Timestamp
itemsOrder.Itemrepeated
paymentOrder.Payment
ratingKeysbytesrepeated
alternateContactInfostring
versionuint32

Order.Item

FieldTypeLabelDescription
listingHashstring
quantityuint32order version < 2 used with listing version < 3
quantity64uint64order version >= 2 used with listing version >= 3
optionsOrder.Item.Optionrepeated
shippingOptionOrder.Item.ShippingOption
memostring
couponCodesstringrepeated
paymentAddressstring

Order.Item.Option

FieldTypeLabelDescription
namestring
valuestring

Order.Item.ShippingOption

FieldTypeLabelDescription
namestring
servicestring

Order.Payment

FieldTypeLabelDescription
methodOrder.Payment.Method
moderatorstring
amountuint64Satoshis
chaincodestringHex encoded
addressstringB58check encoded
redeemScriptstringHex encoded
moderatorKeybytes
coinstring

Order.Shipping

FieldTypeLabelDescription
shipTostring
addressstring
citystring
statestring
postalCodestring
countryCountryCode
addressNotesstring

OrderCompletion

FieldTypeLabelDescription
orderIdstring
timestampgoogle.protobuf.Timestamp
payoutSigsBitcoinSignaturerepeated
ratingsRatingrepeated

OrderConfirmation

FieldTypeLabelDescription
orderIDstring
timestampgoogle.protobuf.Timestamp
paymentAddressstringDirect payments only
requestedAmountuint64
ratingSignaturesRatingSignaturerepeated

OrderFulfillment

FieldTypeLabelDescription
orderIdstring
slugstring
timestampgoogle.protobuf.Timestamp
physicalDeliveryOrderFulfillment.PhysicalDeliveryrepeatedPhysical goods only
digitalDeliveryOrderFulfillment.DigitalDeliveryrepeatedDigital goods only
payoutOrderFulfillment.PayoutModerated payments only
ratingSignatureRatingSignature
notestring
cryptocurrencyDeliveryOrderFulfillment.CryptocurrencyDeliveryrepeatedCryptocurrencies only

OrderFulfillment.CryptocurrencyDelivery

FieldTypeLabelDescription
transactionIDstring

OrderFulfillment.DigitalDelivery

FieldTypeLabelDescription
urlstring
passwordstring

OrderFulfillment.Payout

FieldTypeLabelDescription
sigsBitcoinSignaturerepeated
payoutAddressstring
payoutFeePerByteuint64

OrderFulfillment.PhysicalDelivery

FieldTypeLabelDescription
shipperstring
trackingNumberstring

OrderProcessingFailure

FieldTypeLabelDescription
orderIDstring
attemptedMessageTypeMessage.MessageType
contractRicardianContract

OrderReject

FieldTypeLabelDescription
orderIDstring
timestampgoogle.protobuf.Timestamp
sigsBitcoinSignaturerepeated

Outpoint

FieldTypeLabelDescription
hashstringHex encoded
indexuint32
valueuint64

Rating

FieldTypeLabelDescription
ratingDataRating.RatingData
signaturebytes

Rating.RatingData

FieldTypeLabelDescription
ratingKeybytes
vendorIDID
vendorSigRatingSignature
buyerIDIDoptional
buyerNamestringoptional
buyerSigbytesoptional
moderatorSigbytesonly if a dispute was won
timestampgoogle.protobuf.Timestamp
overalluint32
qualityuint32
descriptionuint32
deliverySpeeduint32
customerServiceuint32
reviewstring

RatingSignature

FieldTypeLabelDescription
metadataRatingSignature.TransactionMetadata
signaturebytes

RatingSignature.TransactionMetadata

FieldTypeLabelDescription
listingSlugstring
ratingKeybytes
moderatorKeybytesOnly if moderated
listingTitlestring
thumbnailRatingSignature.TransactionMetadata.Image

RatingSignature.TransactionMetadata.Image

FieldTypeLabelDescription
tinystring
smallstring
mediumstring
largestring
originalstring

Refund

FieldTypeLabelDescription
orderIDstring
timestampgoogle.protobuf.Timestamp
sigsBitcoinSignaturerepeated
refundTransactionRefund.TransactionInfo
memostring

Refund.TransactionInfo

FieldTypeLabelDescription
txidstring
valueuint64

RicardianContract

FieldTypeLabelDescription
vendorListingsListingrepeated
buyerOrderOrder
vendorOrderConfirmationOrderConfirmation
vendorOrderFulfillmentOrderFulfillmentrepeated
buyerOrderCompletionOrderCompletion
disputeDispute
disputeResolutionDisputeResolution
disputeAcceptanceDisputeAcceptance
refundRefund
signaturesSignaturerepeated
errorsstringrepeated

Signature

FieldTypeLabelDescription
sectionSignature.Section
signatureBytesbytes

SignedListing

FieldTypeLabelDescription
listingListing
hashstring
signaturebytes

VendorFinalizedPayment

FieldTypeLabelDescription
orderIDstringOrderID which has its funds released to the vendor

Listing.Metadata.ContractType

NameNumberDescription
PHYSICAL_GOOD0
DIGITAL_GOOD1
SERVICE2
CROWD_FUND3
CRYPTOCURRENCY4

Listing.Metadata.Format

NameNumberDescription
FIXED_PRICE0
MARKET_PRICE2

Listing.ShippingOption.ShippingType

NameNumberDescription
LOCAL_PICKUP0
FIXED_PRICE1

Order.Payment.Method

NameNumberDescription
ADDRESS_REQUEST0
DIRECT1
MODERATED2

Signature.Section

NameNumberDescription
LISTING0
ORDER1
ORDER_CONFIRMATION2
ORDER_FULFILLMENT3
ORDER_COMPLETION4
DISPUTE5
DISPUTE_RESOLUTION6
REFUND7

Top

posts.proto

Post

FieldTypeLabelDescription
slugstring
vendorIDID
statusstring
longFormstring
imagesPost.Imagerepeated
tagsstringrepeated
channelsstringrepeated
postTypePost.PostType
referencestring
timestampgoogle.protobuf.Timestamp

Post.Image

FieldTypeLabelDescription
filenamestring
originalstring
largestring
mediumstring
smallstring
tinystring

SignedPost

FieldTypeLabelDescription
postPost
hashstring
signaturebytes

Post.PostType

NameNumberDescription
POST0
COMMENT1
REPOST2

Top

message.proto

Block

FieldTypeLabelDescription
rawDatabytes
cidstring

Chat

FieldTypeLabelDescription
messageIdstring
subjectstring
messagestring
timestampgoogle.protobuf.Timestamp
flagChat.Flag

CidList

FieldTypeLabelDescription
cidsstringrepeated

Envelope

FieldTypeLabelDescription
messageMessage
pubkeybytes
signaturebytes

Error

FieldTypeLabelDescription
codeuint32
errorMessagestring
orderIDstring

Message

FieldTypeLabelDescription
messageTypeMessage.MessageType
payloadgoogle.protobuf.Any
requestIdint32optional
isResponsebooloptional

OrderPaymentTxn

FieldTypeLabelDescription
coinstring
orderIDstring
transactionIDstring
withInputbool

SignedData

FieldTypeLabelDescription
senderPubkeybytes
serializedDatabytes
signaturebytes

SignedData.Command

FieldTypeLabelDescription
peerIDstring
typeMessage.MessageType
timestampgoogle.protobuf.Timestamp

Chat.Flag

NameNumberDescription
MESSAGE0
TYPING1
READ2

Message.MessageType

NameNumberDescription
PING0
CHAT1
FOLLOW2
UNFOLLOW3
ORDER4
ORDER_REJECT5
ORDER_CANCEL6
ORDER_CONFIRMATION7
ORDER_FULFILLMENT8
ORDER_COMPLETION9
DISPUTE_OPEN10
DISPUTE_UPDATE11
DISPUTE_CLOSE12
REFUND13
OFFLINE_ACK14
OFFLINE_RELAY15
MODERATOR_ADD16
MODERATOR_REMOVE17
STORE18
BLOCK19
VENDOR_FINALIZED_PAYMENT20
ORDER_PAYMENT21
ERROR500
ORDER_PROCESSING_FAILURE501

Top

countrycodes.proto

CountryCode

NameNumberDescription
NA0
AFGHANISTAN1
ALAND_ISLANDS2
ALBANIA3
ALGERIA4
AMERICAN_SAMOA5
ANDORRA6
ANGOLA7
ANGUILLA8
ANTIGUA9
ARGENTINA10
ARMENIA11
ARUBA12
AUSTRALIA13
AUSTRIA14
AZERBAIJAN15
BAHAMAS16
BAHRAIN17
BANGLADESH18
BARBADOS19
BELARUS20
BELGIUM21
BELIZE22
BENIN23
BERMUDA24
BHUTAN25
BOLIVIA26
BONAIRE_SINT_EUSTATIUS_SABA27
BOSNIA28
BOTSWANA29
BOUVET_ISLAND30
BRAZIL31
BRITISH_INDIAN_OCEAN_TERRITORY32
BRUNEI_DARUSSALAM33
BULGARIA34
BURKINA_FASO35
BURUNDI36
CABO_VERDE37
CAMBODIA38
CAMEROON39
CANADA40
CAYMAN_ISLANDS41
CENTRAL_AFRICAN_REPUBLIC42
CHAD43
CHILE44
CHINA45
CHRISTMAS_ISLAND46
COCOS_ISLANDS47
COLOMBIA48
COMOROS49
CONGO_REPUBLIC50
CONGO51
COOK_ISLANDS52
COSTA_RICA53
COTE_DIVOIRE54
CROATIA55
CUBA56
CURACAO57
CYPRUS58
CZECH_REPUBLIC59
DENMARK60
DJIBOUTI61
DOMINICA62
DOMINICAN_REPUBLIC63
ECUADOR64
EGYPT65
EL_SALVADOR66
EQUATORIAL_GUINEA67
ERITREA68
ESTONIA69
ETHIOPIA70
FALKLAND_ISLANDS71
FAROE_ISLANDS72
FIJI73
FINLAND74
FRANCE75
FRENCH_GUIANA76
FRENCH_POLYNESIA77
FRENCH_SOUTHERN_TERRITORIES78
GABON79
GAMBIA80
GEORGIA81
GERMANY82
GHANA83
GIBRALTAR84
GREECE85
GREENLAND86
GRENADA87
GUADELOUPE88
GUAM89
GUATEMALA90
GUERNSEY91
GUINEA92
GUINEA_BISSAU93
GUYANA94
HAITI95
HEARD_ISLAND96
HOLY_SEE97
HONDURAS98
HONG_KONG99
HUNGARY100
ICELAND101
INDIA102
INDONESIA103
IRAN104
IRAQ105
IRELAND106
ISLE_OF_MAN107
ISRAEL108
ITALY109
JAMAICA110
JAPAN111
JERSEY112
JORDAN113
KAZAKHSTAN114
KENYA115
KIRIBATI116
NORTH_KOREA117
SOUTH_KOREA118
KUWAIT119
KYRGYZSTAN120
LAO121
LATVIA122
LEBANON123
LESOTHO124
LIBERIA125
LIBYA126
LIECHTENSTEIN127
LITHUANIA128
LUXEMBOURG129
MACAO130
MACEDONIA131
MADAGASCAR132
MALAWI133
MALAYSIA134
MALDIVES135
MALI136
MALTA137
MARSHALL_ISLANDS138
MARTINIQUE139
MAURITANIA140
MAURITIUS141
MAYOTTE142
MEXICO143
MICRONESIA144
MOLDOVA145
MONACO146
MONGOLIA147
MONTENEGRO148
MONTSERRAT149
MOROCCO150
MOZAMBIQUE151
MYANMAR152
NAMIBIA153
NAURU154
NEPAL155
NETHERLANDS156
NEW_CALEDONIA157
NEW_ZEALAND158
NICARAGUA159
NIGER160
NIGERIA161
NIUE162
NORFOLK_ISLAND163
NORTHERN_MARIANA_ISLANDS164
NORWAY165
OMAN166
PAKISTAN167
PALAU168
PANAMA169
PAPUA_NEW_GUINEA170
PARAGUAY171
PERU172
PHILIPPINES173
PITCAIRN174
POLAND175
PORTUGAL176
PUERTO_RICO177
QATAR178
REUNION179
ROMANIA180
RUSSIA181
RWANDA182
SAINT_BARTHELEMY183
SAINT_HELENA184
SAINT_KITTS185
SAINT_LUCIA186
SAINT_MARTIN187
SAINT_PIERRE188
SAINT_VINCENT189
SAMOA190
SAN_MARINO191
SAO_TOME192
SAUDI_ARABIA193
SENEGAL194
SERBIA195
SEYCHELLES196
SIERRA_LEONE197
SINGAPORE198
SINT_MAARTEN199
SUCRE200
SLOVAKIA201
SLOVENIA202
SOLOMON_ISLANDS203
SOMALIA204
SOUTH_AFRICA205
SOUTH_SUDAN206
SPAIN207
SRI_LANKA208
SUDAN209
SURINAME210
SVALBARD211
ESWATINI212
SWAZILAND212
SWEDEN213
SWITZERLAND214
SYRIAN_ARAB_REPUBLIC215
TAIWAN216
TAJIKISTAN217
TANZANIA218
THAILAND219
TIMOR_LESTE220
TOGO221
TOKELAU222
TONGA223
TRINIDAD224
TUNISIA225
TURKEY226
TURKMENISTAN227
TURKS_AND_CAICOS_ISLANDS228
TUVALU229
UGANDA230
UKRAINE231
UNITED_ARAB_EMIRATES232
UNITED_KINGDOM233
UNITED_STATES234
URUGUAY235
UZBEKISTAN236
VANUATU237
VENEZUELA238
VIETNAM239
VIRGIN_ISLANDS_BRITISH240
VIRGIN_ISLANDS_US241
WALLIS_AND_FUTUNA242
WESTERN_SAHARA243
YEMEN244
ZAMBIA245
ZIMBABWE246
UNITED_STATES_MINOR_ISLANDS247
ALL500
AFRICA501
ASIA502
CENTRAL_AMERICA503
EUROPE504
MIDDLE_EAST505
NORTH_AMERICA506
SOUTH_AMERICA507
OCEANIA508

Top

profile.proto

Profile

FieldTypeLabelDescription
peerIDstring
handlestring
namestring
locationstring
aboutstring
shortDescriptionstring
nsfwbool
vendorbool
moderatorbool
moderatorInfoModerator
contactInfoProfile.Contact
colorsProfile.Colors
avatarHashesProfile.Image
headerHashesProfile.Image
statsProfile.Stats
bitcoinPubkeystring
lastModifiedgoogle.protobuf.Timestamp
currenciesstringrepeated

Profile.Colors

FieldTypeLabelDescription
primarystring
secondarystring
textstring
highlightstring
highlightTextstring

Profile.Contact

FieldTypeLabelDescription
websitestring
emailstring
phoneNumberstring
socialProfile.SocialAccountrepeated

Profile.Image

FieldTypeLabelDescription
tinystring
smallstring
mediumstring
largestring
originalstring

Profile.SocialAccount

FieldTypeLabelDescription
typestring
usernamestring
proofstring

Profile.Stats

FieldTypeLabelDescription
followerCountuint32
followingCountuint32
listingCountuint32
ratingCountuint32
postCountuint32
averageRatingfloat

Top

moderator.proto

DisputeUpdate

FieldTypeLabelDescription
orderIdstring
payoutAddressstring
outpointsOutpointrepeated
serializedContractbytes

Moderator

FieldTypeLabelDescription
descriptionstring
termsAndConditionsstring
languagesstringrepeated
acceptedCurrenciesstringrepeated
feeModerator.Fee

Moderator.Fee

FieldTypeLabelDescription
fixedFeeModerator.Price
percentagefloat
feeTypeModerator.Fee.FeeType

Moderator.Price

FieldTypeLabelDescription
currencyCodestring
amountuint64Bitcoins must be in satoshi

Moderator.Fee.FeeType

NameNumberDescription
FIXED0
PERCENTAGE1
FIXED_PLUS_PERCENTAGE2

Top

orders.proto

OrderState

NameNumberDescription
PENDING0Order has been funded and sent to the vendor but vendor has not yet responded
AWAITING_PAYMENT1Waiting for the buyer to fund the payment address
AWAITING_PICKUP2Waiting for the customer to pick up the order (customer pickup option only)
AWAITING_FULFILLMENT3Order has been fully funded and we're waiting for the vendor to fulfill
PARTIALLY_FULFILLED4Vendor has fulfilled part of the order
FULFILLED5Vendor has fulfilled the order
COMPLETED6Buyer has completed the order and left a review
CANCELED7Buyer canceled the order (offline order only)
DECLINED8Vendor declined to confirm the order (offline order only)
REFUNDED9Vendor refunded the order
DISPUTED10Contract is under active dispute
DECIDED11The moderator has resolved the dispute and we are waiting for the winning party to accept the payout.
RESOLVED12The winning party has accepted the dispute and it is now complete. After the buyer leaves a review the state should be set to COMPLETE.
PAYMENT_FINALIZED13Escrow has been released after waiting the timeout period. After the buyer leaves a review the state should be set to COMPLETE.
PROCESSING_ERROR14We screwed up and produced a order which didn't validate. This state is only used for offline orders. If a processing error occurred with an open connection between buyer and vendor the vendor just rejects the order on the spot neither party commits the order to the database.

Top

api.proto

CaseRespApi

FieldTypeLabelDescription
timestampgoogle.protobuf.Timestamp
buyerContractRicardianContract
vendorContractRicardianContract
buyerContractValidationErrorsstringrepeated
vendorContractValidationErrorsstringrepeated
stateOrderState
readbool
buyerOpenedbool
claimstring
unreadChatMessagesuint64
resolutionDisputeResolution

Coupon

FieldTypeLabelDescription
hashstring
codestring

OrderRespApi

FieldTypeLabelDescription
contractRicardianContract
stateOrderState
readbool
fundedbool
unreadChatMessagesuint64
paymentAddressTransactionsTransactionRecordrepeated
refundAddressTransactionTransactionRecord

PeerAndProfile

FieldTypeLabelDescription
peerIdstring
profileProfile

PeerAndProfileWithID

FieldTypeLabelDescription
idstring
peerIdstring
profileProfile

RatingWithID

FieldTypeLabelDescription
idstring
ratingIdstring
ratingRating

TransactionRecord

FieldTypeLabelDescription
txidstring
valueint64
confirmationsuint32
heightuint32
timestampgoogle.protobuf.Timestamp

Scalar Value Types

.proto TypeNotesC++ TypeJava TypePython Type
doubledoubledoublefloat
floatfloatfloatfloat
int32Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.int32intint
int64Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.int64longint/long
uint32Uses variable-length encoding.uint32intint/long
uint64Uses variable-length encoding.uint64longint/long
sint32Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.int32intint
sint64Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.int64longint/long
fixed32Always four bytes. More efficient than uint32 if values are often greater than 2^28.uint32intint
fixed64Always eight bytes. More efficient than uint64 if values are often greater than 2^56.uint64longint/long
sfixed32Always four bytes.int32intint
sfixed64Always eight bytes.int64longint/long
boolboolbooleanboolean
stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringStringstr/unicode
bytesMay contain any arbitrary sequence of bytes.stringByteStringstr

Protos File Tree


.
├── api.proto
├── contracts.proto
├── countrycodes.proto
├── message.proto
├── moderator.proto
├── orders.proto
├── posts.proto
└── profile.proto

0 directories, 8 files

Protobuf sources

src:./contracts.proto


syntax = "proto3";
option go_package = "pb";


import "countrycodes.proto";
import "message.proto";
import "google/protobuf/timestamp.proto";

message RicardianContract {
    repeated Listing vendorListings                    = 1;
    Order buyerOrder                                   = 2;
    OrderConfirmation vendorOrderConfirmation          = 3;
    repeated OrderFulfillment vendorOrderFulfillment   = 4;
    OrderCompletion buyerOrderCompletion               = 5;
    Dispute dispute                                    = 6;
    DisputeResolution disputeResolution                = 7;
    DisputeAcceptance disputeAcceptance                = 8;
    Refund refund                                      = 9;
    repeated Signature signatures                      = 10;
    repeated string errors                             = 11;
}

message Listing {
    string slug                             = 1;
    ID vendorID                             = 2;
    Metadata metadata                       = 3;
    Item item                               = 4;
    repeated ShippingOption shippingOptions = 5;
    repeated Tax taxes                      = 6;
    repeated Coupon coupons                 = 7;
    repeated string moderators              = 8;
    string termsAndConditions               = 9;
    string refundPolicy                     = 10;

    message Metadata {
        uint32 version                     = 1;
        ContractType contractType          = 2;
        Format format                      = 3;
        google.protobuf.Timestamp expiry   = 4;
        repeated string acceptedCurrencies = 5;
        string pricingCurrency             = 6;
        string language                    = 7;
        uint32 escrowTimeoutHours          = 8;
        string coinType                    = 9;
        uint32 coinDivisibility            = 10;
        float priceModifier                = 11;

        enum ContractType {
            PHYSICAL_GOOD  = 0;
            DIGITAL_GOOD   = 1;
            SERVICE        = 2;
            CROWD_FUND     = 3;
            CRYPTOCURRENCY = 4;
        }

        enum Format {
            FIXED_PRICE  = 0;
            MARKET_PRICE = 2;
        }
    }

    message Item {
        string title               = 1;
        string description         = 2;
        string processingTime      = 3;
        uint64 price               = 4;
        bool nsfw                  = 5;
        repeated string tags       = 6;
        repeated Image images      = 7;
        repeated string categories = 8;
        float grams                = 9;
        string condition           = 10;
        repeated Option options    = 11;
        repeated Sku skus          = 12;

        message Option {
            string name                = 1;
            string description         = 2;
            repeated Variant variants  = 3;

            message Variant {
                string name = 1;
                Image image = 2;
            }
        }

        message Sku {
            repeated uint32 variantCombo = 1;
            string productID             = 2;
            int64 surcharge              = 3;
            int64 quantity               = 4; // Not saved with listing
        }

        message Image {
            string filename = 1;
            string original = 2;
            string large    = 3;
            string medium   = 4;
            string small    = 5;
            string tiny     = 6;
        }
    }

    message ShippingOption {
        string name                         = 1;
        ShippingType type                   = 2;
        repeated CountryCode regions        = 3;
        repeated Service services           = 5;

        enum ShippingType {
            LOCAL_PICKUP = 0;
            FIXED_PRICE  = 1;
        }

        message Service {
            string name                = 1;
            uint64 price               = 2;
            string estimatedDelivery   = 3;
            uint64 additionalItemPrice = 4;
        }
    }

    message Tax {
        string taxType                  = 1;
        repeated CountryCode taxRegions = 2;
        bool taxShipping                = 3;
        float percentage                = 4;
    }

    message Coupon {
        string title = 1;
        oneof code {
            string hash         = 2;
            string discountCode = 3;
        }
        oneof discount {
            float percentDiscount = 5;
            uint64 priceDiscount  = 6;
        }
    }
}

message Order {
    string refundAddress                 = 1;
    uint64 refundFee                     = 2;
    Shipping shipping                    = 3;
    ID buyerID                           = 4;
    google.protobuf.Timestamp timestamp  = 5;
    repeated Item items                  = 6;
    Payment payment                      = 7;
    repeated bytes ratingKeys            = 8;
    string alternateContactInfo          = 9;
    uint32 version                       = 10;

    message Shipping {
        string shipTo       = 1;
        string address      = 2;
        string city         = 3;
        string state        = 4;
        string postalCode   = 5;
        CountryCode country = 6;
        string addressNotes = 7;
    }

    message Item {
        string listingHash            = 1;
        uint32 quantity               = 2; // order version < 2 used with listing version < 3
        uint64 quantity64             = 8; // order version >= 2 used with listing version >= 3
        repeated Option options       = 3;
        ShippingOption shippingOption = 4;
        string memo                   = 5;
        repeated string couponCodes   = 6;
        string paymentAddress         = 7;

        message Option {
            string name  = 1;
            string value = 2;
        }

        message ShippingOption {
            string name    = 1;
            string service = 2;
        }
    }

    message Payment {
        Method method       = 1;
        string moderator    = 2;
        uint64 amount       = 3; // Satoshis
        string chaincode    = 4; // Hex encoded
        string address      = 5; // B58check encoded
        string redeemScript = 6; // Hex encoded
        bytes  moderatorKey = 7;
        string coin         = 8;

        enum Method {
            ADDRESS_REQUEST = 0;
            DIRECT          = 1;
            MODERATED       = 2;
        }
    }
}

message OrderConfirmation {
    string orderID                            = 1;
    google.protobuf.Timestamp timestamp       = 2;
    // Direct payments only
    string paymentAddress                     = 3;
    uint64 requestedAmount                    = 4;

    repeated RatingSignature ratingSignatures = 5;
}

message OrderReject {
    string orderID                      = 1;
    google.protobuf.Timestamp timestamp = 2;
    repeated BitcoinSignature sigs      = 3;
}

message RatingSignature {
    TransactionMetadata metadata = 1;
    bytes signature              = 2;

    message TransactionMetadata {
        string listingSlug   = 1;
        bytes  ratingKey     = 2;
        bytes  moderatorKey  = 3; // Only if moderated
        string listingTitle  = 4;
        Image  thumbnail     = 5;

        message Image {
                string tiny     = 1;
                string small    = 2;
                string medium   = 3;
                string large    = 4;
                string original = 5;
        }
    }
}

message BitcoinSignature {
    uint32 inputIndex = 1;
    bytes signature   = 2;
}

message OrderFulfillment {
    string orderId                             = 1;

    string slug                                = 2;

    google.protobuf.Timestamp timestamp        = 3;

    // Physical goods only
    repeated PhysicalDelivery physicalDelivery = 4;

    //Digital goods only
    repeated DigitalDelivery digitalDelivery   = 5;

    // Moderated payments only
    Payout payout                              = 6;

    RatingSignature ratingSignature            = 7;

    string note                                = 8;

    // Cryptocurrencies only
    repeated CryptocurrencyDelivery cryptocurrencyDelivery = 9;

    message PhysicalDelivery {
        string shipper            = 1;
        string trackingNumber     = 2;
    }

    message DigitalDelivery {
        string url                = 1;
        string password           = 2;
    }

    message CryptocurrencyDelivery {
        string transactionID      = 1;
    }

    message Payout {
        repeated BitcoinSignature sigs = 1;
        string payoutAddress           = 2;
        uint64 payoutFeePerByte        = 3;
    }
}

message OrderCompletion {
    string orderId                       = 1;
    google.protobuf.Timestamp timestamp  = 2;
    repeated BitcoinSignature payoutSigs = 3;
    repeated Rating ratings              = 4;
}

message OrderProcessingFailure {
  string orderID                           = 1;
  Message.MessageType attemptedMessageType = 2;
  RicardianContract contract               = 3;
}

message Rating {
    RatingData ratingData = 1;
    bytes signature       = 2;

    message RatingData {
        bytes ratingKey                     = 1;
        ID vendorID                         = 2;
        RatingSignature vendorSig           = 3;
        ID buyerID                          = 4; // optional
        string buyerName                    = 5; // optional
        bytes buyerSig                      = 6; // optional
        bytes moderatorSig                  = 7; // only if a dispute was won


        google.protobuf.Timestamp timestamp = 8;

        uint32 overall                      = 9;
        uint32 quality                      = 10;
        uint32 description                  = 11;
        uint32 deliverySpeed                = 12;
        uint32 customerService              = 13;
        string review                       = 14;
    }
}

message Dispute {
    google.protobuf.Timestamp timestamp = 1;
    string claim                        = 2;
    string payoutAddress                = 3;
    repeated Outpoint outpoints         = 4;
    bytes serializedContract            = 5;
}

message DisputeResolution {
    google.protobuf.Timestamp timestamp = 1;
    string orderId                      = 2;
    string proposedBy                   = 3;
    string resolution                   = 4;
    Payout payout                       = 5;
    repeated bytes moderatorRatingSigs  = 6; // Used in ratings

    message Payout {
            repeated BitcoinSignature sigs = 1;
            repeated Outpoint inputs       = 2;
            Output buyerOutput             = 3;
            Output vendorOutput            = 4;
            Output moderatorOutput         = 5;

            message Output {
              oneof scriptOrAddress {
                string script  = 1;
                string address = 3;
              }
              uint64 amount  = 2;
            }
    }
}

message DisputeAcceptance {
    google.protobuf.Timestamp timestamp = 1;
    string closedBy                     = 2;
}

message Outpoint {
        string hash  = 1; // Hex encoded
        uint32 index = 2;
        uint64 value = 3;
}

message Refund {
    string orderID                      = 1;
    google.protobuf.Timestamp timestamp = 2;
    repeated BitcoinSignature sigs      = 3;
    TransactionInfo refundTransaction   = 4;
    string memo                         = 5;

    message TransactionInfo {
        string txid  = 1;
        uint64 value = 2;
    }
}

message VendorFinalizedPayment {
  string orderID = 1; // OrderID which has its funds released to the vendor
}

message ID {
    string peerID       = 1;
    string handle       = 2;
    Pubkeys pubkeys     = 3;
    bytes bitcoinSig    = 4; // Bitcoin signature covering peerID

    message Pubkeys {
        bytes identity = 1; // IPFS public key
        bytes bitcoin  = 2; // Bitcoin public key
    }
}

message Signature {
    Section section      = 1;
    bytes signatureBytes = 2;

    enum Section {
        LISTING            = 0;
        ORDER              = 1;
        ORDER_CONFIRMATION = 2;
        ORDER_FULFILLMENT  = 3;
        ORDER_COMPLETION   = 4;
        DISPUTE            = 5;
        DISPUTE_RESOLUTION = 6;
        REFUND             = 7;
    }
}

message SignedListing {
    Listing listing     = 1;
    string hash         = 2;
    bytes signature     = 3;
}

src:./posts.proto


syntax = "proto3";
option go_package = "pb";


import "google/protobuf/timestamp.proto";
import "contracts.proto";

message Post {
    string slug                         = 1;
    ID vendorID                         = 2;
    string status                       = 3;
    string longForm                     = 4;
    repeated Image images               = 5;
    repeated string tags                = 6;
    repeated string channels            = 7;
    PostType postType                   = 8;
    string reference                    = 9;
    google.protobuf.Timestamp timestamp = 10;

    message Image {
        string filename = 1;
        string original = 2;
        string large    = 3;
        string medium   = 4;
        string small    = 5;
        string tiny     = 6;
    }

    enum PostType {
        POST        = 0;
        COMMENT     = 1;
        REPOST      = 2;
    }
}

message SignedPost {
    Post post           = 1;
    string hash         = 2;
    bytes signature     = 3;
}

src:./message.proto


syntax = "proto3";
option go_package = "pb";


import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";

message Message {
    MessageType messageType     = 1;
    google.protobuf.Any payload = 2;
    int32 requestId             = 3; // optional
    bool isResponse             = 4; // optional

    enum MessageType {
        PING                     = 0;
        CHAT                     = 1;
        FOLLOW                   = 2;
        UNFOLLOW                 = 3;
        ORDER                    = 4;
        ORDER_REJECT             = 5;
        ORDER_CANCEL             = 6;
        ORDER_CONFIRMATION       = 7;
        ORDER_FULFILLMENT        = 8;
        ORDER_COMPLETION         = 9;
        DISPUTE_OPEN             = 10;
        DISPUTE_UPDATE           = 11;
        DISPUTE_CLOSE            = 12;
        REFUND                   = 13;
        OFFLINE_ACK              = 14;
        OFFLINE_RELAY            = 15;
        MODERATOR_ADD            = 16;
        MODERATOR_REMOVE         = 17;
        STORE                    = 18;
        BLOCK                    = 19;
        VENDOR_FINALIZED_PAYMENT = 20;
        ORDER_PAYMENT            = 21;
        ERROR                    = 500;
        ORDER_PROCESSING_FAILURE = 501;
    }
}

message Envelope {
    Message message = 1;
    bytes pubkey    = 2;
    bytes signature = 3;
}

message Chat  {
    string messageId                    = 1;
    string subject                      = 2;
    string message                      = 3;
    google.protobuf.Timestamp timestamp = 4;
    Flag flag                           = 5;

    enum Flag {
        MESSAGE = 0;
        TYPING  = 1;
        READ    = 2;
    }
}

message SignedData {
    bytes senderPubkey        = 1;
    bytes serializedData      = 2;
    bytes signature           = 3;

    message Command {
        string peerID                       = 1;
        Message.MessageType type            = 2;
        google.protobuf.Timestamp timestamp = 3;
    }
}

message CidList {
    repeated string cids = 1;
}

message Block {
    bytes rawData = 1;
    string cid    = 2;
}

message Error {
    uint32 code         = 1;
    string errorMessage = 2;
    string orderID      = 3;
}

message OrderPaymentTxn {
    string coin          = 1;
    string orderID       = 2;
    string transactionID = 3;
    bool withInput = 4;
}

src:./countrycodes.proto


syntax = "proto3";
option go_package = "pb";


enum CountryCode {
    option allow_alias = true;
    NA                             = 0;

    AFGHANISTAN                    = 1;
    ALAND_ISLANDS                  = 2;
    ALBANIA                        = 3;
    ALGERIA                        = 4;
    AMERICAN_SAMOA                 = 5;
    ANDORRA                        = 6;
    ANGOLA                         = 7;
    ANGUILLA                       = 8;
    ANTIGUA                        = 9;

    ARGENTINA                      = 10;
    ARMENIA                        = 11;
    ARUBA                          = 12;
    AUSTRALIA                      = 13;
    AUSTRIA                        = 14;
    AZERBAIJAN                     = 15;
    BAHAMAS                        = 16;
    BAHRAIN                        = 17;
    BANGLADESH                     = 18;
    BARBADOS                       = 19;

    BELARUS                        = 20;
    BELGIUM                        = 21;
    BELIZE                         = 22;
    BENIN                          = 23;
    BERMUDA                        = 24;
    BHUTAN                         = 25;
    BOLIVIA                        = 26;
    BONAIRE_SINT_EUSTATIUS_SABA    = 27;
    BOSNIA                         = 28;
    BOTSWANA                       = 29;

    BOUVET_ISLAND                  = 30;
    BRAZIL                         = 31;
    BRITISH_INDIAN_OCEAN_TERRITORY = 32;
    BRUNEI_DARUSSALAM              = 33;
    BULGARIA                       = 34;
    BURKINA_FASO                   = 35;
    BURUNDI                        = 36;
    CABO_VERDE                     = 37;
    CAMBODIA                       = 38;
    CAMEROON                       = 39;

    CANADA                         = 40;
    CAYMAN_ISLANDS                 = 41;
    CENTRAL_AFRICAN_REPUBLIC       = 42;
    CHAD                           = 43;
    CHILE                          = 44;
    CHINA                          = 45;
    CHRISTMAS_ISLAND               = 46;
    COCOS_ISLANDS                  = 47;
    COLOMBIA                       = 48;
    COMOROS                        = 49;

    CONGO_REPUBLIC                 = 50;
    CONGO                          = 51;
    COOK_ISLANDS                   = 52;
    COSTA_RICA                     = 53;
    COTE_DIVOIRE                   = 54;
    CROATIA                        = 55;
    CUBA                           = 56;
    CURACAO                        = 57;
    CYPRUS                         = 58;
    CZECH_REPUBLIC                 = 59;

    DENMARK                        = 60;
    DJIBOUTI                       = 61;
    DOMINICA                       = 62;
    DOMINICAN_REPUBLIC             = 63;
    ECUADOR                        = 64;
    EGYPT                          = 65;
    EL_SALVADOR                    = 66;
    EQUATORIAL_GUINEA              = 67;
    ERITREA                        = 68;
    ESTONIA                        = 69;

    ETHIOPIA                       = 70;
    FALKLAND_ISLANDS               = 71;
    FAROE_ISLANDS                  = 72;
    FIJI                           = 73;
    FINLAND                        = 74;
    FRANCE                         = 75;
    FRENCH_GUIANA                  = 76;
    FRENCH_POLYNESIA               = 77;
    FRENCH_SOUTHERN_TERRITORIES    = 78;
    GABON                          = 79;

    GAMBIA                         = 80;
    GEORGIA                        = 81;
    GERMANY                        = 82;
    GHANA                          = 83;
    GIBRALTAR                      = 84;
    GREECE                         = 85;
    GREENLAND                      = 86;
    GRENADA                        = 87;
    GUADELOUPE                     = 88;
    GUAM                           = 89;

    GUATEMALA                      = 90;
    GUERNSEY                       = 91;
    GUINEA                         = 92;
    GUINEA_BISSAU                  = 93;
    GUYANA                         = 94;
    HAITI                          = 95;
    HEARD_ISLAND                   = 96;
    HOLY_SEE                       = 97;
    HONDURAS                       = 98;
    HONG_KONG                      = 99;

    HUNGARY                        = 100;
    ICELAND                        = 101;
    INDIA                          = 102;
    INDONESIA                      = 103;
    IRAN                           = 104;
    IRAQ                           = 105;
    IRELAND                        = 106;
    ISLE_OF_MAN                    = 107;
    ISRAEL                         = 108;
    ITALY                          = 109;

    JAMAICA                        = 110;
    JAPAN                          = 111;
    JERSEY                         = 112;
    JORDAN                         = 113;
    KAZAKHSTAN                     = 114;
    KENYA                          = 115;
    KIRIBATI                       = 116;
    NORTH_KOREA                    = 117;
    SOUTH_KOREA                    = 118;
    KUWAIT                         = 119;

    KYRGYZSTAN                     = 120;
    LAO                            = 121;
    LATVIA                         = 122;
    LEBANON                        = 123;
    LESOTHO                        = 124;
    LIBERIA                        = 125;
    LIBYA                          = 126;
    LIECHTENSTEIN                  = 127;
    LITHUANIA                      = 128;
    LUXEMBOURG                     = 129;

    MACAO                          = 130;
    MACEDONIA                      = 131;
    MADAGASCAR                     = 132;
    MALAWI                         = 133;
    MALAYSIA                       = 134;
    MALDIVES                       = 135;
    MALI                           = 136;
    MALTA                          = 137;
    MARSHALL_ISLANDS               = 138;
    MARTINIQUE                     = 139;

    MAURITANIA                     = 140;
    MAURITIUS                      = 141;
    MAYOTTE                        = 142;
    MEXICO                         = 143;
    MICRONESIA                     = 144;
    MOLDOVA                        = 145;
    MONACO                         = 146;
    MONGOLIA                       = 147;
    MONTENEGRO                     = 148;
    MONTSERRAT                     = 149;

    MOROCCO                        = 150;
    MOZAMBIQUE                     = 151;
    MYANMAR                        = 152;
    NAMIBIA                        = 153;
    NAURU                          = 154;
    NEPAL                          = 155;
    NETHERLANDS                    = 156;
    NEW_CALEDONIA                  = 157;
    NEW_ZEALAND                    = 158;
    NICARAGUA                      = 159;

    NIGER                          = 160;
    NIGERIA                        = 161;
    NIUE                           = 162;
    NORFOLK_ISLAND                 = 163;
    NORTHERN_MARIANA_ISLANDS       = 164;
    NORWAY                         = 165;
    OMAN                           = 166;
    PAKISTAN                       = 167;
    PALAU                          = 168;
    PANAMA                         = 169;

    PAPUA_NEW_GUINEA               = 170;
    PARAGUAY                       = 171;
    PERU                           = 172;
    PHILIPPINES                    = 173;
    PITCAIRN                       = 174;
    POLAND                         = 175;
    PORTUGAL                       = 176;
    PUERTO_RICO                    = 177;
    QATAR                          = 178;
    REUNION                        = 179;

    ROMANIA                        = 180;
    RUSSIA                         = 181;
    RWANDA                         = 182;
    SAINT_BARTHELEMY               = 183;
    SAINT_HELENA                   = 184;
    SAINT_KITTS                    = 185;
    SAINT_LUCIA                    = 186;
    SAINT_MARTIN                   = 187;
    SAINT_PIERRE                   = 188;
    SAINT_VINCENT                  = 189;

    SAMOA                          = 190;
    SAN_MARINO                     = 191;
    SAO_TOME                       = 192;
    SAUDI_ARABIA                   = 193;
    SENEGAL                        = 194;
    SERBIA                         = 195;
    SEYCHELLES                     = 196;
    SIERRA_LEONE                   = 197;
    SINGAPORE                      = 198;
    SINT_MAARTEN                   = 199;

    SUCRE                          = 200;
    SLOVAKIA                       = 201;
    SLOVENIA                       = 202;
    SOLOMON_ISLANDS                = 203;
    SOMALIA                        = 204;
    SOUTH_AFRICA                   = 205;
    SOUTH_SUDAN                    = 206;
    SPAIN                          = 207;
    SRI_LANKA                      = 208;
    SUDAN                          = 209;

    SURINAME                       = 210;
    SVALBARD                       = 211;
    ESWATINI                       = 212;
    SWAZILAND                      = 212;
    SWEDEN                         = 213;
    SWITZERLAND                    = 214;
    SYRIAN_ARAB_REPUBLIC           = 215;
    TAIWAN                         = 216;
    TAJIKISTAN                     = 217;
    TANZANIA                       = 218;
    THAILAND                       = 219;

    TIMOR_LESTE                    = 220;
    TOGO                           = 221;
    TOKELAU                        = 222;
    TONGA                          = 223;
    TRINIDAD                       = 224;
    TUNISIA                        = 225;
    TURKEY                         = 226;
    TURKMENISTAN                   = 227;
    TURKS_AND_CAICOS_ISLANDS       = 228;
    TUVALU                         = 229;

    UGANDA                         = 230;
    UKRAINE                        = 231;
    UNITED_ARAB_EMIRATES           = 232;
    UNITED_KINGDOM                 = 233;
    UNITED_STATES                  = 234;
    URUGUAY                        = 235;
    UZBEKISTAN                     = 236;
    VANUATU                        = 237;
    VENEZUELA                      = 238;
    VIETNAM                        = 239;

    VIRGIN_ISLANDS_BRITISH         = 240;
    VIRGIN_ISLANDS_US              = 241;
    WALLIS_AND_FUTUNA              = 242;
    WESTERN_SAHARA                 = 243;
    YEMEN                          = 244;
    ZAMBIA                         = 245;
    ZIMBABWE                       = 246;
    UNITED_STATES_MINOR_ISLANDS    = 247;

    ALL                            = 500;
    AFRICA                         = 501;
    ASIA                           = 502;
    CENTRAL_AMERICA                = 503;
    EUROPE                         = 504;
    MIDDLE_EAST                    = 505;
    NORTH_AMERICA                  = 506;
    SOUTH_AMERICA                  = 507;
    OCEANIA                        = 508;
}

src:./profile.proto


syntax = "proto3";
option go_package = "pb";


import "google/protobuf/timestamp.proto";
import "moderator.proto";

message Profile {
    string peerID                          = 1;
    string handle                          = 2;
    string name                            = 3;
    string location                        = 4;
    string about                           = 5;
    string shortDescription                = 6;

    bool nsfw                              = 7;
    bool vendor                            = 8;
    bool moderator                         = 9;
    Moderator moderatorInfo                = 10;

    Contact contactInfo                    = 11;
    Colors colors                          = 12;

    // The following data is added to the profile
    // automatically by the server and may be omitted
    // when setting the profile via API.

    Image avatarHashes                     = 13;
    Image headerHashes                     = 14;

    Stats stats                            = 15;

    string bitcoinPubkey                   = 16;

    google.protobuf.Timestamp lastModified = 17;

    repeated string currencies             = 18;

    message Contact {
        string website                = 1;
        string email                  = 2;
        string phoneNumber            = 3;
        repeated SocialAccount social = 4;
    }

    message SocialAccount {
        string type     = 1;
        string username = 2;
        string proof    = 3;
    }

    message Image {
        string tiny     = 1;
        string small    = 2;
        string medium   = 3;
        string large    = 4;
        string original = 5;
    }

    message Colors {
        string primary       = 1;
        string secondary     = 2;
        string text          = 3;
        string highlight     = 4;
        string highlightText = 5;
    }

    message Stats {
        uint32 followerCount  = 1;
        uint32 followingCount = 2;
        uint32 listingCount   = 3;
        uint32 ratingCount    = 4;
        uint32 postCount      = 5;
        float averageRating   = 6;
    }
}

src:./moderator.proto


syntax = "proto3";
option go_package = "pb";


import "contracts.proto";

message Moderator {
    string description                 = 1;
    string termsAndConditions          = 2;
    repeated string languages          = 3;
    repeated string acceptedCurrencies = 4;
    Fee fee                            = 5;

    message Fee {
        Price fixedFee   = 1;
        float percentage = 2;
        FeeType feeType  = 3;

        enum FeeType {
            FIXED                 = 0;
            PERCENTAGE            = 1;
            FIXED_PLUS_PERCENTAGE = 2;
        }
    }

    message Price {
        string currencyCode = 1;
        uint64 amount       = 2; // Bitcoins must be in satoshi
    }
}

message DisputeUpdate {
    string orderId              = 1;
    string payoutAddress        = 2;
    repeated Outpoint outpoints = 3;
    bytes serializedContract    = 4;
}

src:./orders.proto


syntax = "proto3";
option go_package = "pb";


enum OrderState {
    // Order has been funded and sent to the vendor but vendor has not yet responded
    PENDING              = 0;

    // Waiting for the buyer to fund the payment address
    AWAITING_PAYMENT     = 1;

    // Waiting for the customer to pick up the order (customer pickup option only)
    AWAITING_PICKUP      = 2;

    // Order has been fully funded and we're waiting for the vendor to fulfill
    AWAITING_FULFILLMENT = 3;

    // Vendor has fulfilled part of the order
    PARTIALLY_FULFILLED  = 4;

    // Vendor has fulfilled the order
    FULFILLED            = 5;

    // Buyer has completed the order and left a review
    COMPLETED            = 6;

    // Buyer canceled the order (offline order only)
    CANCELED             = 7;

    // Vendor declined to confirm the order (offline order only)
    DECLINED             = 8;

    // Vendor refunded the order
    REFUNDED             = 9;

    // Contract is under active dispute
    DISPUTED             = 10;

    // The moderator has resolved the dispute and we are waiting for the winning party to
    // accept the payout.
    DECIDED              = 11;

    // The winning party has accepted the dispute and it is now complete. After the buyer
    // leaves a review the state should be set to COMPLETE.
    RESOLVED             = 12;

    // Escrow has been released after waiting the timeout period. After the buyer
    // leaves a review the state should be set to COMPLETE.
    PAYMENT_FINALIZED    = 13;

    // We screwed up and produced a order which didn't validate. This state is only used for offline orders. If a processing
    // error occurred with an open connection between buyer and vendor the vendor just rejects the order on the spot neither party
    // commits the order to the database.
    PROCESSING_ERROR     = 14;
}

src:./api.proto


syntax = "proto3";
option go_package = "pb";


import "contracts.proto";
import "orders.proto";
import "profile.proto";
import "google/protobuf/timestamp.proto";

// This schema is used for the /ob/listing api call structure
// We use protobuf for this instead of a basic struct because
// the listing object is in protobuf and we can't mix types. Also
// we want to avoid putting fields in the contract that are only
// used by the api.

message Coupon {
    string hash = 1;
    string code = 2;
}

message OrderRespApi {
    RicardianContract contract                            = 1;
    OrderState state                                      = 2;
    bool read                                             = 3;
    bool funded                                           = 4;
    uint64 unreadChatMessages                             = 5;
    repeated TransactionRecord paymentAddressTransactions = 6;
    TransactionRecord refundAddressTransaction            = 7;
}

message CaseRespApi {
    google.protobuf.Timestamp timestamp            = 1;
    RicardianContract buyerContract                = 2;
    RicardianContract vendorContract               = 3;
    repeated string buyerContractValidationErrors  = 4;
    repeated string vendorContractValidationErrors = 5;
    OrderState state                               = 6;
    bool read                                      = 7;
    bool buyerOpened                               = 8;
    string claim                                   = 9;
    uint64 unreadChatMessages                      = 10;
    DisputeResolution resolution                   = 11;
}

message TransactionRecord {
    string txid                         = 1;
    int64 value                         = 2;
    uint32 confirmations                = 3;
    uint32 height                       = 4;
    google.protobuf.Timestamp timestamp = 5;
}

message PeerAndProfile {
    string peerId   = 1;
    Profile profile = 2;
}

message PeerAndProfileWithID {
    string id       = 1;
    string peerId   = 2;
    Profile profile = 3;
}

message RatingWithID {
    string id       = 1;
    string ratingId = 2;
    Rating rating   = 3;
}

Decentralized autonomous organization (DAO)

Decentralized autonomous organization

DAO 績效

激勵原則 OKRs or KPI

DAO 績效分配參考Live OKRs - Joystream - github

  • 專案
  • 每版本
  • 每群組
  • 個人

影片

2018勞工影展 開幕片 《工人搞公司 Can We Do It Ourselves 》 - YouTube

TODO

DarkDAO

PolkaDAO - DAOstack

Belmont principles - DAO

Belmont Report - autonomous agents - Wikipedia

  • Respect for persons: protecting the autonomy of all people and treating them with courtesy and respect and allowing for informed consent. Researchers must be truthful and conduct no deception;
  • Beneficence: The philosophy of "Do no harm" while maximizing benefits for the research project and minimizing risks to the research subjects; and
  • Justice: ensuring reasonable, non-exploitative, and well-considered procedures are administered fairly — the fair distribution of costs and benefits to potential research participants — and equally.

201909

Aragon

Aragon

DAO 龙头项目 Aragon:我们为何选择 Cosmos 搭建新链? - 链闻 ChainNews

尽管在以太坊上进行交易的成本增加了,但真正的问题是我们无法预测未来的成本。当我们和企业客户沟通时,「需要多少钱才能使用 Aragon」是一个他们非常关心的问题,但对此我们却无法提供一个很好的答案。

Aragon Chain: a proof of stake blockchain for the Aragon community

JoyStream

議題

JoyStream forum module example

需要改寫前端 React – A JavaScript library for building user interfaces 框架與鏈端 paritytech/substrate: Substrate: The platform for blockchain innovators 框架。

testnet model

Proposal: New testnet model · Issue #119 · Joystream/joystream

  • Problem 1: Unegaged participants.
  • Problem 2: Sybill attacked token economics

測試鏈要收到反饋需要注意激勵與尋租的平衡。

on-chain forum

使用 discourse/discourse: A platform for community discussion. Free, open, simple. 既有的套裝開源論壇軟體缺點是使用者配置如果沒有經過串接會有獨立兩套的使用者資料,改成直接掛鏈論壇如 Joystream/substrate-forum-module: An on-chain forum. 除了使用者資料歸一處之外,另外好處是每筆發言編輯都有簽章為證,相反的掛鏈論壇缺點是小眾使用不適合高人氣網站的讀寫場景,也不像泛用型論壇軟體如 discourse 有現成美觀的 UI 介面,手機板也不用自己來寫。

鏈上使用手冊或是使用規範作法可以同步到所有節點,這類資料改寫少適合用在組織裡面。

testnet.joystream.org/acropolis/pioneer/#/forum/categories/4

Edgeware

Edgeware

Straightedge

Straightedge 為不滿意 Edgeware 的創世區塊分配方式而分叉改創世分配模式的分叉鏈,並跟 Edgeware 同日上鏈,不過沒過多久看來創世塊還是有計算錯誤問題,兩條鏈都有重啟的計畫。

Likecoin

Likecoin 使用 Cosoms 架構,其 LIKE 代幣帳本與治理,創作者創作之後加上讚賞鍵,依照點擊的次數來分配 LIKE 數量。該專案的程式碼庫為LikeCoin - Github,可以先看看📜 憲法 - LikeCoin

相關連結

如何在 mdbook 的文章中加入讚賞鍵 Likecoin Button

先註冊 Liker.Land 取得 LikerID,續讀一下中文說明 LikeCoin 是甚麼 - LikeCoin

放入 mdbook 產出的 HTML 靜態文件的重點是需要使用 javascript 來動態產生下面 HTML 片段於瀏覽器之中。

<div class="likecoin-embed likecoin-button">
  <div></div>
  <iframe scrolling="no" frameborder="0" 
    src="https://button.like.co/in/embed/LikerID/button?referrer=http://yourhost/foo/page.html">
  </iframe>
</div>

客製 mdbook 先新增 likebutton.js 於 book.toml 旁,也可以使用 likecoin/likecoin-button-sdk 的 sdk.js 原理類似。

likebutton.js

const LIKER_ID = "dltdojo";//記得換成自己的
let likeurl = `https://button.like.co/in/embed/${LIKER_ID}/button?referrer=${encodeURI(window.location.href)}`;
let el = document.getElementsByClassName("likebutton")[0];
if(el){
    el.innerHTML = `<div class="likecoin-embed likecoin-button">
  <div></div>
  <iframe scrolling="no" frameborder="0" src="${likeurl}"></iframe>
</div>`;
}

並複製 LikeCoinButton-integration/style.css 成為 likebutton.css

.likecoin-button {
  position: relative;
  width: 100%;
  max-width: 485px;
  max-height: 240px;
  margin: 0 auto;
}
.likecoin-button > div {
  padding-top: 49.48454%;
}
.likecoin-button > iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

編輯 book.toml 的 output.html 段落加入 js 與 css

[output.html]
default-theme = "coal"
mathjax-support = true
additional-js = ["likebutton.js"]
additional-css = ["likebutton.css"]

最後就是看那一頁 md 裡面要加上按鈕就新增一個 div 後用 class 為 likebutton 來綁住輸出。

<div class="likebutton"/>

上面寫在 md 內的 div 在經過 mdbook build 轉化成為 HTML 後輸出結果如下

目前只能限制一個 LikerID 使用,如要提供多用戶可以用 getElementsByClassName(LikerIDFoo) 來實做。

清明剛過,說到化讚為「賞」想到那個近千年前寫寒食帖的被貶者在年輕時寫的刑賞忠厚之至論。既然賞之過乎仁,也許哪天該小宇宙有個忠厚之至的無條件基本收入給創作者無寒食之憂。

天下之善不勝賞,而爵祿不足以勸也;
知天下之惡不勝刑,而刀鋸不足以裁也。
是故疑則舉而歸之於仁,以君子長者之
道待天下,使天下相率而歸於君子長者之道。

故曰:忠厚之至也。

參考資訊

探索心得

LikeCoin 是個資訊混亂的小宇宙,很多頁面沒有提供幣圈 UI/UX 慣用的資訊,下面說明如何找到這類資訊的做法。

如何取得帳號的LIKE歷史交易紀錄

查閱交易歷史的功能在手機 app 可以點擊顯示餘額的下方 bigdipper 按鈕,但在 like.co 找不到明顯可按的按鈕來查閱交易歷史紀錄。

  • 必須先找到LikeCoin 錢包地址(下面用cosmos123abc示意),位置在 Liker ID 設定附近。
  • 開啟 https://likecoin.bigdipper.live/account/cosmos123abc

如何在like.co/in/settings加上連結點擊查閱bigdipper功能

先查是否有類似 issue 正在進行,沒有就可以先看看內容,可用「錢包地址」檢索會出現翻譯的字串「walletAddress」再找一次,目標 pages/in/settings/index.vue 就會出現,因為這只是前面文字,要修改的是內容 getUserInfo.cosmosWallet,要更動這個內容的工具可用 vue 的 JavaScript Expressions 支援與 JavaScript 的 Template literals。

vue 樣板大概的樣子,如果要其他測試鏈可選就要將 likecoin.bigdipper.live 也換成變數。

<template>
  <h1>Account: <a :href="`https://likecoin.bigdipper.live/account/${123+4}`">{{123+4}}</a></h1>
</template>

其實再查一下可以發現有個 view-bigdipper 內有輸出 likecoin.bigdipper.live 的變數可用,所以可以選擇直接用 view-bigdipper 或是引入該變數使用。

用view-bigdipper最方便,只要引入使用的版面符合會建議使用這種方式。

<view-bigdipper
  v-if="getUserInfo.cosmosWallet"
  :address="getUserInfo.cosmosWallet"
/>

打算要改之後先從 github fork 一版,然後改完按慣例是該加上測試再提 Pull Request(PR),不過要問一下專案需求,在快速更替的 UI 開發中是否要做這測試。

點讚交易查詢

📜 憲法 - LikeCoin有提到LIKE分配,但目前無相關計算實際範例可觀察來自行檢驗,造成讚賞公民自己對整個持有與交易歷史的狀態處於相當模糊的狀況。

就帳本觀察每個讚賞公民會有兩個關鍵錢包地址,錢包地址A用來收發代幣,另一個用來發送點讚代幣的錢包地址B,差別在A公民收發,後者B只能點讚發,另外B地址一開始會有一筆約1000LIKE轉入應是五鎂月贊助換來。使用B地址帳本紀錄可觀察到點讚代幣交易歷史,不過B地址並沒顯示在讚賞公民設定或管理介面裡,也許是變動綁定地址非固定?

問題回到讚賞公民點完讚就想立即看到這筆交易細節要如何查詢帳本?而不是被動等電郵的讚賞公民每日報告部分摘要。換句話說要去哪底查出B地址看帳本?關鍵是必須先有點讚對方的地址,在點讚之後馬上從對方的bigdipper反向看自己的B地址。可是第一步有對方 LikerID 會遇到 https://like.co/xxxx 看不到地址的問題。

因為目前網頁設計 maskedWallet 遮起來 like-co/index.vue at likecoin/like-co 不方便查閱,可用兩種做法查出來對方地址,一個是用A錢包地址發送小額即可查出,二是記下對方地址前後部分觀察bigdipper的最新交易得出。

DID

Decentralized Identifiers (DIDs) v0.13

TOC

New eID

工商社論》新式數位身分證(New eID)引發的疑慮

有關New eID的製作,在晶片資安管理的規格方面,是依據ISO 14443及ICAO之國際安全標準規範訂定。每個晶片都會有其專屬識別碼(Unique ID,簡稱UID);負責承製的中央印製廠,會在內政部核可下,以UID資訊記錄卡片的生產履歷,避免晶片外流、盜用或被不當使用,未來亦可用來辨識晶片卡是否是偽變造卡,是重要的管控機制。至於晶片寫入個人資料,則採用ICAO對隱私保護之建議,會啟動隨機亂數序號機制,每次感應都會重新產生隨機亂數,根本無法追蹤晶片的使用軌跡,這與現行晶片護照相同。

Doc 9303 Part 11: Security Mechanisms for MRTDs - ICAO

Table 10. Key agreement algorithms

Algorithm / FormatDHECDH
Key Agreement Algorithm[PKCS#3]ECKA [TR-03111]
X.509 Public Key Format[X9.42][TR-03111]
TLV Public Key FormatTLV, cf. Section 9.4.2TLV, cf. Section 9.4.3
Ephemeral Public Key Validation[RFC 2631][TR-03111]
  • [X9.42] ANSI: X9.42, Public Key Cryptography for the Financial Services Industry: Agreement of Symmetric Keys Using Discrete Logarithm Cryptography, 1999
  • [TR-03111] BSI: Technical Guideline TR-03111: Elliptic Curve Cryptography, Version 2.0, 2012
  • [RFC 2631] Rescorla, Eric: RFC 2631 Diffie-Hellman key agreement method, 1999

Basic access control - Wikipedia

There is a replay attack against the basic access control protocol that allows an individual passport to be traced.[3][4] The attack is based on being able to distinguish a failed nonce check from a failed MAC check and works against passports with randomized unique identifiers and hard to guess keys.The basic access control mechanism has been criticized as offering too little protection from unauthorized interception. Researchers claim [5] that because there are only limited numbers of passport issued, many theoretically possible passport numbers will not be in use in practice. The limited range of human age ranges further reduce the space of possibilities.In other words, the data used as an encryption key has low entropy, meaning that guessing the session key is possible via a modest brute force attack.

Security by Politics - Why it will never work. Lukas Grunwald DN-Systems GmbH Germany DefCon 15 Las Vegas USA

Basic Access Control
  Grants access to data after inspection systems are authorized
  Authorization through the Machine Readable Zone (MRZ)
    Nine digit document number
    In many countries: issuing authority + incrementing number
    Six digit date of birth Can be guessed or assumed to be a valid date
    Six digit expiry date 
    16 most significant bytes of SHA1-hash over MRZ_info are 
      used as 3DES key for S/M (ISO7816 secure messaging)
---
BAC 
  The access key is printed on the passport
  Many times the passport is put on a Xerox machine in:
    Hotels Rentals (cars, ski, ...) 
    Shops (cell phones, ...)
  The data from the MRZ is stored in many private databases (airlines, banks ...)
---
BAC And Traceability
  With the BAC handshake data known, 
    the random unique ID is worthless
    the MRTD is traceable
    access to the content (LDS-DG.1 &DG.2) is possible
    access to the SOD is possible

Privacy features for contactless cards - Privacy Features of European eID Card Specifications 2008

Contactless chip cards require additional security mechanisms. At least the following issues should be addressed:

  • Skimming: an attacker opens a clandestine connection to the chip and gains access to the data,
  • Eavesdropping: an attacker intercepts the communication between the chip and an authorised reader,
  • Location Tracking: an attacker generates person or card-specific movement profiles

As mentioned above, BAC protects electronic passports against skimming attacks while, for example, the passport holder carries his passport in the pocket. During the border control procedure, the reading device optically scans the document and authenticates to the chip using keys derived from the MRZ printed on the data page. Some European countries, like the Netherlands and Sweden, adopted BAC in the specifications of their national ID cards where the MRZ is printed on the back of the card.

The BAC mechanism only weakly addresses the issue of eavesdropping and it does not prevent reading (or copying) the data of a lost passport. However, in the second generation of European passports, this problem is addressed by the Extended Access Control (EAC) protocol which, besides the mutual authentication of card and reader, establishes a strongly encrypted communication channel. Similar techniques, some of them adapted to internet-authentication use-cases, can be found in the specifications for the German eID card and inclusion into the European Cititzen Card standard is currently under discussion.

Location tracking is an important privacy issue in contactless eID systems. An electronic passport with an RFID chip, if equipped with Basic Access Control, does not reveal any personal information of the passport holder as long as it is safely stored in a pocket and its MRZ is unknown to the attacker. However, the initialisation of wireless communication according to ISO 14443 requires the chip to send a unique identifier to the card reader. An attacker with several distributed reading devices (e.g. in door frames) could therefore distinguish the passport holder without actually having access to the files on the chip. Combined with other data sources, the attacker might be able to generate person or card-specific profiles. This particular attack is relatively easy to avoid – most electronic passports generate random UIDs for every session (see Supplement 9303, E11,) but as a general rule, privacy- protecting RFID systems should be designed very carefully.

林宗男、李忠憲/數位身分證的資安風險

晶片的公私鑰雖然是在晶片內產製,但是需將公鑰資料讀出才能產生個人憑證申請檔(CSR)。公鑰能匯出當然私鑰也能匯出。但是內政部卻告訴國人無法匯出,明顯與事實不符。全體國民公私鑰key pair只有廠商知道如何產生,公務機關無法驗證,憑空製造國家安全的治理危機。我們呼籲政府應當採取分散式架構建構我國數位國家政策,放棄這個不當政策,正面回應民間及學術界「一卡一用」的主張。

TODO

Hyperledgger Aries

Sidetree

DID Resolution

201909

DeFi

TOC

DeFi - Ethereum

The DeFi Series — An overview of the ecosystem and major protocols

Maker DAO

MakerDAO

Compound protocol

compound-finance/compound-protocol: The Compound On-Chain Protocol

What You Should Know Before Putting Half a Million DAI in Compound

That could leave a lot of cDAI holders ... holding cDAI for a long time.

 1. The smart contract security seems legit.
 2. Compound is a CUSTODIAL system, all lending pools can be trivially drained 
    if their admin private key is compromised.
 3. When you lend on Compound, you are NOT guaranteed to be able to withdraw 
    whenever you want. If you try to withdraw your funds and all the money is 
    locked up in outstanding loans, your withdrawal transaction will fail.

Compound Finance Audit Summary – OpenZeppelin blog

However, in the hands of a malicious or compromised administrator, these privileges contain the ability to trivially freeze markets, censor transactions or steal all assets from the system. Similarly, control of the price feed can be used to steal most, if not all, assets from the system. Currently, the same externally owned account is the administrator for all live markets.

ChainX

chainx-org/ChainX: Cross-chain hub for Crypto Asset on Polkadot

Centrifuge Chain

Centrifuge’s vision is to enable businesses worldwide to access and create the decentralized economy.

Berlin and the EU support building the Centrifuge Chain with 1.4 Million €

Even today our users experience the limitations of speed, throughput, and cost of the Ethereum blockchain, limiting the use of Centrifuge OS to very specific types of product lines, services, and transactions. Privacy-preserving features are not yet sufficiently available on Ethereum, additionally limiting business and enterprise use-cases.

Harberger Tax

simondlr/thisartworkisalwaysonsale: A digital art project on Ethereum that uses harberger tax to have an always-on auction. Tax is patronage to artist.

Total Time Held: 6 months The digital artwork above is always on sale. In order to own this artwork, you always have to specify a sale price. Anyone can buy it from the current patron at any time for the specified sale price. Whilst held, a 5% fee (pa) is levied as patronage towards the artist.

Harberger Ads

Events

defi.wtf

DeFi.WTF – Join the 1st DeFi Conf in Osaka.

Resources

TODO

Open Banking

Open banking - Wikipedia

  • The use of open APIs that enable third-party developers to build applications and services around the financial institution.
  • Greater financial transparency options for account holders ranging from open data to private data.
  • The use of open-source technology to achieve the above.

How to flourish in an uncertain future Open banking and PSD2 - Deloitte - PDF

TOC

相關專案

dukei/any-balance-providers

dukei/any-balance-providers: Collection of AnyBalance providers 開源專案的一大堆各式奇怪的登入與抓取內容方式正是 Open Banking 想要用通用 API 解決的,下面列舉幾個抓取餘額解析的範例。

Services

TOC

Accounting

Taiwan

木材

引述 國產材驗證制度11月上線 認明「台灣木材」標章不再錯買|農傳媒

林務局表示,只要是取得CAS,TAP或QR code中任何一項資格的木材原料或產品,都可以使用代表合法來源生產的「台灣木材」標章,消費者很容易就可以認明。QR code利用區塊鏈資料不可竄改的特性,確保木材來源端的合法性,山老鼠偷砍盜伐珍貴林木遭逮後,木材會標售,合法業者得標後裁切木材並做成幾項木製藝品,這些木製藝品的基座即可標上QR code以敘明來源,消費者只要掃描條碼,即可查到產品資料。

TODO

Amazon QLDB

TOC

Amazon QLDB 功能

SQL 支援 Amazon QLDB 類似 SQL 的 API 可讓您使用熟悉的 SQL 運算子輕鬆查詢、管理和更新資料。

腾讯可信区块链TrustSQL与传统的SQL语言有何区别?

Ledger Reliability Engineering (LRE)

Ledger Reliability Engineering (LRE) 與 Site Reliability Engineering (SRE) 應用的 DevOps 工具類似,差異在 dApp 的運作模式牽涉到與他人他社的共識互動機制,而且不太可能單一組織內所有應用都是 dApp,故 LRE 也需兼顧 App 維運需要。

LRE SRE

目前談到 LRE 這塊的資源較少,故先以收集 SRE 為主。

TODO

  • Error Budgets 跨組織代幣化設計,並改為 Consensus Budgets。
  • taichu-raw:443/metrics

Site Reliability Engineering

Implementing SLOs

tpl-sre-slos-v1.svg

參照 The Site Reliability Workbook Chapter 2 - Implementing SLOs 建議一開始設計 SLOs

  • 選一個想用來定義 SLOs 的應用程式就好,其他的可以後面加進來。
  • 確認使用者是誰,就是那個應用程式最佳化後會很高興的人。
  • 選那些使用者通用的系統任務或是關鍵活動 (上圖)。
  • 畫出高階架構圖,顯示關鍵組件、需求流、資料流與關鍵性的服務依賴,關鍵組件做成下列組合包(上圖分色)。
    • Request-driven 需求導向
    • Pipeline 管道
    • Storage 儲存
Type of serviceType of SLI
Request-drivenAvailability
Request-drivenLatency
Request-drivenQuality
PipelineFreshness
PipelineCorrectness
PipelineCoverage
StorageDurability

Google SRE Books

Site Reliability Engineering

The Site Reliability Workbook

Telemetry Projects

OpenTelemetry paritytech/substrate-telemetry OpenTelemetry implementation in rust

SRE Golden Signals

How to Monitor the SRE Golden Signals

  • From the Google SRE book:
    • Latency
    • Traffic
    • Errors
    • Saturation
  • USE Method (from Brendan Gregg):
    • Utilization
    • Saturation
    • Errors
  • RED Method (from Tom Wilkie):
    • Rate
    • Errors
    • Duration

5 Signals

  • Rate — Request rate, in requests/sec
  • Errors — Error rate, in errors/sec
  • Latency — Response time, including queue/wait time, in milliseconds.
  • Saturation — How overloaded something is, which is related to utilization but more directly measured by things like queue depth (or sometimes concurrency). As a queue measurement, this becomes non-zero when you are saturated, often not much before. Usually a counter.
  • Utilization — How busy the resource or system is. Usually expressed 0–100% and most useful for predictions (as Saturation is probably more useful).

Chaos Engineering

Chaos Engineering (混沌工程)

Transactions Per Second (TPS)

中央銀行數位貨幣(CBDC)芻議 | 名家評論 - 工商時報

將區塊鏈的去中介化、去中心化除去,成為一個強大的中心化私有區塊鏈,因此,人行CBDC每秒可處理300,000筆交易;在去年的「光棍節」期間,中國所有交易的峰值交易量為每秒92,771筆交易,仍落在人行的規劃範圍之內。傳聞人行的CBDC將在今年11月11日「光棍節」上路,接受最嚴苛的檢驗。

Facebook announces Libra cryptocurrency: All you need to know | TechCrunch

Every Libra payment is permanently written into the Libra Blockchain — a cryptographically authenticated database that acts as a public online ledger designed to handle 1,000 transactions per second.

Hedera Hashgraph, Touted as High-Speed Blockchain Alternative, Now Live - CoinDesk

Specifically, Hedera says the network can support up to 10,000 transactions per second, compared to 2.8 per second for bitcoin and 15 for ethereum, the two largest blockchains.

Hedera Hashgraph — Time for some FUD - Eric Wall - Medium

A dapp requires smart contracts and since Hedera is currently throttling 10 transactions per second with smart contracts, then it doesn’t make this any more interesting than ethereum

Web Tech

TOC

圖庫

Beautiful Free Images & Pictures | Unsplash

Email

Email provider

第三方寄信服務簡易分析 - 願い星 - Medium How to start sending email — Mailgun API documentation

Headless Browser

puppeteer 可以截圖存證

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.png'});

  await browser.close();
})();

Browser Extensiions

Firefox Add-ons(附加元件)

修改 webext-copy-title-url

對於常常需要剪貼成 markdown link 但是又不放心開權限的時候,可以考慮修改 marekjedlinski/webext-copy-title-url: Firefox/Chrome extension: Copy page title (or selection) and url to clipboard via context menu 來用。

修改的流程

如信得過可直接用有原始碼的專案,這些專案也可以改,只是複雜許多不適合入門。

TODO

201909

  • extension dev in mad-white docker image

Example Pages

測試頁及樣版

Transport Layer Security (TLS)

Transport Layer Security - Wikipedia

TOC

Protocol

DNS-over-HTTPS (DoH)

tpl-doh-dns-https-v1.svg

Liberating Web Data Using Decentralized Oracles for TLS (DECO)

At a high level, the prover commits to a piece of data D and proves to the verifier that D came from a TLS serverSand optionally a statement πD about D. E.g., in the exampleof proving age, the statement πD could be the predicate “D=y/m/dis Alice’s date of birth andy−2019>18.”

DECentralized Oracles DECO 目前還未開源,概念是 TLS 未完待續來個三方握手,這作法對網頁服務端透明不須做另外設置,代表網頁服務端須清楚確認內容並負責任,不過對於使用者的體驗來看可直接用滑鼠選擇要證明會更方便,因為這樣可同時將外來聚合 ajax 內容納入內容來源證明裡,只要最終引入合成在瀏覽器頁面裡面的都可用瀏覽器地址上面那個 TLS 鎖頭掛的網頁服務端憑證,來證明這網頁與連帶引入的資源都由該鎖頭而起。只是當時簽發服務端憑證範圍只是認 CN 對上網域有效性,現要衍生到後面的內容存在性簽章是否有其效力待觀察。

tls-certs-content-v190916.png

Liberating web data using DECO, a privacy-preserving oracle protocol電子簽章法§10-全國法規資料庫 的交互作用值得探索。

第 10 條 以數位簽章簽署電子文件者,應符合下列各款規定,始生前條第一項之效力:
  一、使用經第十一條核定或第十五條許可之憑證機構依法簽發之憑證。
  二、憑證尚屬有效並未逾使用範圍。

Tools

TODO

TLS Session Key Log

NSS Key Log Format - Mozilla | MDN

Key logs can be written by NSS so that external programs can decrypt TLS connections. Wireshark 1.6.0 and above can use these log files to decrypt packets. You can tell Wireshark where to find the key file via Edit→Preferences→Protocols→SSL→(Pre)-Master-Secret log filename.

Support for NSS's SSLKEYLOGFILE to be able to decrypt TLS traffic with TLS_ECDHE* ciphers · Issue #7795 · envoyproxy/envoy

OpenSSL/BoringSSL applications (browsers, curl, etc) often support logging the pre-master secrets into a file by setting the SSLKEYLOGFILE environment variable. The logfile can then be easily imported into tools like Wireshark to decrypt TLS on the fly.

Traffic tapping — envoy 1.12.0-dev-358793 documentation

The tap transport socket supports both buffered and streaming, controlled by the streaming setting. When buffering, SocketBufferedTrace messages are emitted. When streaming, a series of SocketStreamedTraceSegment are emitted.

Web Authentication (WebAuthn)

TOC

Web Authentication API navigator.credentials

Guide to Web Authentication


const publicKeyCredentialCreationOptions = {
    challenge: Uint8Array.from(randomStringFromServer, c => c.charCodeAt(0)),
    rp: {
        name: "Duo Security",
        id: "duosecurity.com",
    },
    user: {
        id: Uint8Array.from("UZSL85T9AFC", c => c.charCodeAt(0)),
        name: "lee@webauthn.guide",
        displayName: "Lee",
    },
    pubKeyCredParams: [{alg: -7, type: "public-key"}],
    authenticatorSelection: {
        authenticatorAttachment: "cross-platform",
    },
    timeout: 60000,
    attestation: "direct"
};

const credential = await navigator.credentials.create({
    publicKey: publicKeyCredentialCreationOptions
});

WebAuthn 硬體

SoloKeys - The first open source FIDO2 security key.

WebAuthn 參考專案

Google

Pretix 票務

pretix/pretix: Ticket shop application for conferences, festivals, concerts, tech events, shows, exhibitions, workshops, barcamps, etc.

Release 3.1.0 of pretix – pretix – Reinventing ticket sales for conferences, festivals, exhibitions, ...

WebAuthn We ported our two-factor authentication to support hardware tokens via WebAuthn instead of U2F. All your keys are still working, but they now work in Microsoft Edge, many more Firefox versions, as well as most mobile browsers, too.

pretix/webauthn.js at master · pretix/pretix

Okta SignIn widget 身份識別

Cryptovote

cryptovote/webauthn.js at master · cryptovoting/cryptovote

FIDO2/WebAuthn Resources

TODO

201909

WebAssembly

TOC

EVM ABI WebAssemble

solidity

contract Test {
    event Event(uint indexed a, bytes32 b);
    function foo(uint a) public { emit Event(a, b); }
    bytes32 b;
}

test-contract-output-abi.json

[
    {
        "type": "event",
        "inputs": [
            {
                "name": "a",
                "type": "uint256",
                "indexed": true
            },
            {
                "name": "b",
                "type": "bytes32",
                "indexed": false
            }
        ],
        "name": "Event"
    },
    {
        "type": "function",
        "inputs": [
            {
                "name": "a",
                "type": "uint256"
            }
        ],
        "name": "foo",
        "outputs": []
    }
]

Wasm for Blockchain 2019

Wasm for Blockchain 2019 - NEAR Protocol - Medium

Wasmer opens discussion of unifying APIs of smart contracts, by presenting two approaches: the first one is the one suggested by Oasis in this blog post, where they emulate blockchain interface through POSIX-like imports available in standard WASI modules; the second approach is to either use imports without WASI (Ewasm approach) or have a special WASI module for blockchains.

Wasmtime

CraneStation/wasmtime: Standalone JIT-style runtime for WebAssembly, using Cranelift relation to wasmtime? · Issue #142 · wasmerio/wasmer

WASI cowsay

wapm-packages/cowsay: Cowsay in WebAssembly

Cloudflare Worker , wrangler , Serverless Wasm

wasm32-wasi

目前 wasi net 部份未支援

// 
// cargo +nightly build --target wasm32-wasi
// 
fn main() {
    println!("Hello, WASM/WASI world!");
}
$ wasmer run target/wasm32-wasi/debug/hello-wasi.wasm
Hello, WASM/WASI world!

Links

OpenSSL

test ca

設定 TLS 測試服務的時候需要金鑰與簽發的憑證,利用 OpenSSL 可以快速生成這些憑證。下列資料從 test-ca - rustls 取得。

build-pki.sh

#!/bin/sh

set -xe

rm -rf rsa/ ecdsa/
mkdir -p rsa/ ecdsa/

openssl req -nodes \
          -x509 \
          -days 3650 \
          -newkey rsa:4096 \
          -keyout rsa/ca.key \
          -out rsa/ca.cert \
          -sha256 \
          -batch \
          -subj "/CN=ponytown RSA CA"

openssl req -nodes \
          -newkey rsa:3072 \
          -keyout rsa/inter.key \
          -out rsa/inter.req \
          -sha256 \
          -batch \
          -subj "/CN=ponytown RSA level 2 intermediate"

openssl req -nodes \
          -newkey rsa:2048 \
          -keyout rsa/end.key \
          -out rsa/end.req \
          -sha256 \
          -batch \
          -subj "/CN=testserver.com"

openssl rsa \
          -in rsa/end.key \
          -out rsa/end.rsa

openssl req -nodes \
          -newkey rsa:2048 \
          -keyout rsa/client.key \
          -out rsa/client.req \
          -sha256 \
          -batch \
          -subj "/CN=ponytown client"

openssl rsa \
          -in rsa/client.key \
          -out rsa/client.rsa

# ecdsa
openssl ecparam -name prime256v1 -out ecdsa/nistp256.pem
openssl ecparam -name secp384r1 -out ecdsa/nistp384.pem

openssl req -nodes \
          -x509 \
          -newkey ec:ecdsa/nistp384.pem \
          -keyout ecdsa/ca.key \
          -out ecdsa/ca.cert \
          -sha256 \
          -batch \
          -days 3650 \
          -subj "/CN=ponytown ECDSA CA"

openssl req -nodes \
          -newkey ec:ecdsa/nistp256.pem \
          -keyout ecdsa/inter.key \
          -out ecdsa/inter.req \
          -sha256 \
          -batch \
          -days 3000 \
          -subj "/CN=ponytown ECDSA level 2 intermediate"

openssl req -nodes \
          -newkey ec:ecdsa/nistp256.pem \
          -keyout ecdsa/end.key \
          -out ecdsa/end.req \
          -sha256 \
          -batch \
          -days 2000 \
          -subj "/CN=testserver.com"

openssl req -nodes \
          -newkey ec:ecdsa/nistp384.pem \
          -keyout ecdsa/client.key \
          -out ecdsa/client.req \
          -sha256 \
          -batch \
          -days 2000 \
          -subj "/CN=ponytown client"

for kt in rsa ecdsa ; do
  openssl x509 -req \
            -in $kt/inter.req \
            -out $kt/inter.cert \
            -CA $kt/ca.cert \
            -CAkey $kt/ca.key \
            -sha256 \
            -days 3650 \
            -set_serial 123 \
            -extensions v3_inter -extfile openssl.cnf

  openssl x509 -req \
            -in $kt/end.req \
            -out $kt/end.cert \
            -CA $kt/inter.cert \
            -CAkey $kt/inter.key \
            -sha256 \
            -days 2000 \
            -set_serial 456 \
            -extensions v3_end -extfile openssl.cnf

  openssl x509 -req \
            -in $kt/client.req \
            -out $kt/client.cert \
            -CA $kt/inter.cert \
            -CAkey $kt/inter.key \
            -sha256 \
            -days 2000 \
            -set_serial 789 \
            -extensions v3_client -extfile openssl.cnf

  cat $kt/inter.cert $kt/ca.cert > $kt/end.chain
  cat $kt/end.cert $kt/inter.cert $kt/ca.cert > $kt/end.fullchain

  cat $kt/inter.cert $kt/ca.cert > $kt/client.chain
  cat $kt/client.cert $kt/inter.cert $kt/ca.cert > $kt/client.fullchain

  openssl asn1parse -in $kt/ca.cert -out $kt/ca.der > /dev/null
done

openssl.cnf

[ v3_end ]
basicConstraints = critical,CA:false
keyUsage = nonRepudiation, digitalSignature
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
subjectAltName = @alt_names

[ v3_client ]
basicConstraints = critical,CA:false
keyUsage = nonRepudiation, digitalSignature
extendedKeyUsage = critical, clientAuth
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always

[ v3_inter ]
subjectKeyIdentifier = hash
extendedKeyUsage = critical, serverAuth, clientAuth
basicConstraints = CA:true
keyUsage = cRLSign, keyCertSign, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign

[ alt_names ]
DNS.1 = testserver.com
DNS.2 = second.testserver.com
DNS.3 = localhost

Kubernetes

Tools

cuelang

Kubernetes tutorial - cuelang - github

cuelang 算是下面這個 java 初學者對於分號問題的 JOSN 版本回應,忘記加單雙引號沒關係,人看的懂可以快速回應就好,尤其是一大包 yaml 設定要搞定的 kubernetes。

Today my 16yr old cousin asked me... "If the compiler knows that.. "semicolon is missing at line no 16 in Helloworld.java ", then why it can't simply put a ' ; ' there instead of telling us..."

tutorial kubernetes - cuelang - github 只要跑一次就大概知道用在哪裡,特別是設定檔很多的時候應該做有用,如果只有個位數引入 CUE 就要考慮多個工具的複雜度問題。

frontend/bartender

kubernetes 的佈署如果需要開服務需要另外寫,利用 cloud.cue 樣板加上目錄裡面的 kube.cue 可將下面常見的佈署模板變成只有一行。

$ cat ./frontend/bartender/kube.cue 
package kube

deployment bartender image: "gcr.io/myproj/bartender:v0.1.34"

生成

$ cue cmd dump ./frontend/bartender/
apiVersion: v1
kind: Service
metadata:
  labels:
    app: bartender
    component: frontend
    domain: prod
  name: bartender
spec:
  ports:
  - name: http
    port: 7080
    protocol: TCP
  selector:
    app: bartender
    component: frontend
    domain: prod
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    component: frontend
  name: bartender
spec:
  replicas: 1
  template:
    metadata:
      annotations:
        prometheus.io.port: "7080"
        prometheus.io.scrape: "true"
      labels:
        app: bartender
        component: frontend
        domain: prod
    spec:
      containers:
      - args: []
        image: gcr.io/myproj/bartender:v0.1.34
        name: bartender
        ports:
        - containerPort: 7080
          name: http

proxy/nginx 範例

以 nginx 為例寫 223 行來設定,產出 yaml 設定檔為 260 行,如果是 json 達 612 行。

$ cd doc/tutorial/kubernetes/manual/services
$ find ./proxy/nginx/ | xargs wc
      0       0       0 ./proxy/nginx/
     19      38     337 ./proxy/nginx/kube.cue
      6      12     108 ./proxy/nginx/service.cue
    198     495    7683 ./proxy/nginx/configmap.cue
    223     545    8128 總計
$ cue cmd dump ./proxy/nginx/ | wc
    260     606    9074
$ cue eval ./proxy/nginx | wc
    612    1365   23358

cue 檔案雖是 json 的超集合,加上共用樣板可寫的比 yaml 精簡。

package kube

deployment nginx: {
	image: "nginx:1.11.10-alpine"

	expose port http:  80
	expose port https: 443

	volume "secret-volume": {
		mountPath: "/etc/ssl"
		spec secret secretName: "proxy-secrets"
	}

	volume "config-volume": {
		mountPath: "/etc/nginx/nginx.conf"
		subPath:   "nginx.conf"
		spec configMap name: "nginx"
	}
}

置入 MAD WHITE

FROM golang:1.13 AS build-cue
RUN go get -u cuelang.org/go/cmd/cue

FROM codercom/code-server:2.preview.11-vsc1.37.0
COPY --from=build-cue /go/bin/cue /usr/bin/cue

Examples

TODO

Vault

hashicorp/vault: A tool for secrets management, encryption as a service, and privileged access management

banzaicloud/bank-vaults: A Vault swiss-army knife: a K8s operator, Go client with automatic token renewal, automatic configuration, multiple unseal options and more. A CLI tool to init, unseal and configure Vault (auth methods, secret engines). Direct secret injection into Pods.

Prometheus

Prometheus

Grafana

Grafana Labs

201909

P2P

TOC

California Assembly Bill 5 or AB 5

引用 Independent work: Choice, necessity, and the gig economy | McKinsey

The resulting report, Independent work: Choice, necessity, and the gig economy, finds that up to 162 million people in Europe and the United States—or 20 to 30 percent of the working-age population—engage in some form of independent work.

Uber

Kraken

效能

In our busiest cluster, Kraken distributes more than 1 million blobs per day, including 100k 1G+ blobs. At its peak production load, Kraken distributes 20K 100MB-1G blobs in under 30 sec.

與 BitTorrent 差異

Kraken's problem space is slightly different than what BitTorrent was designed for. Kraken's goal is to reduce global max download time and communication overhead in a stable environment, while BitTorrent was designed for an unpredictable and adversarial environment, so it needs to preserve more copies of scarce data and defend against malicious or bad behaving peers.

P2P File Providers

Publish to ipfs · ethereum/remix-ide

近日的以太坊網頁版開發工具 PR Publish to ipfs · ethereum/remix-ide 引入 ipfs 的合約儲存方式。

registry.get('fileproviders/swarm').api,
registry.get('fileproviders/ipfs').api,

Cybersecurity

CSF-WUQI (梧棲)

CSF-WUQI 是基於 Cybersecurity Framework | NISTargoproj/argo: Argo Workflows: Get stuff done with Kubernetes. 流程實驗專案,最終目的是作出應用 Operator pattern - Kubernetes 的 CSF 流程專案。

Cybersecurity Framework Version 1.1 主要分五個面向

  • IDENTIFY (ID)
  • PROTECT (PR)
  • DETECT (DE)
  • RESPOND (RS)
  • RECOVER (RC)

OKRs

Objective: Proof-Of-Concept

Tracking

DateKR#1KR#2KR#3KR#4KR#5Comments
19-09-280.200.000.050.000.00
yy-mm-dd-

yaml and json file base on 2018-04-16_framework_v1.1_core1.xlsx

argo workflow hello world version of ID.RA-5

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: csf-wuqi-
spec:
  entrypoint: whalesay
  templates:
  - name: whalesay
    container:
      image: docker/whalesay:latest
      command: [cowsay]
      args: ["ID.RA-5 Threats, vulnerabilities, likelihoods, and impacts are used to determine risk."]

WIP: DAG workflow

  • IDENTIFY (ID)
  • PROTECT (PR)
  • DETECT (DE)
  • RESPOND (RS)
  • RECOVER (RC)

Open source container-native workflow engine for Kubernetes. | argo

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: csf-wuqi-
spec:
  entrypoint: csf
  templates:
  - name: echo
    inputs:
      parameters:
      - name: message
    container:
      image: alpine:3.7
      command: [echo, "{{inputs.parameters.message}}"]
  - name: csf
    dag:
      tasks:
      - name: IDENTIFY
        template: echo
        arguments:
          parameters: [{name: message, value: IDENTIFY}]
      - name: PROTECT
        dependencies: [IDENTIFY]
        template: echo
        arguments:
          parameters: [{name: message, value: PROTECT}]
      - name: DETECT
        dependencies: [IDENTIFY]
        template: echo
        arguments:
          parameters: [{name: message, value: DETECT}]
      - name: RESPOND
        dependencies: [PROTECT, DETECT]
        template: echo
        arguments:
          parameters: [{name: message, value: RESPOND}]
      - name: RECOVER
        dependencies: [PESPOND]
        template: echo
        arguments:
          parameters: [{name: message, value: RECOVER}]

Objective: Introduce a minimum viable product (MVP) System

Tracking

DateKR#1KR#2KR#3KR#4KR#5Comments
20-01-010.000.000.000.000.00
yy-mm-dd-

Resources

Rust

TOC

Projects

monolith

rust 單一 html 文件的合成工具,主要用來將所有的 css, img, javascript 整合到單一 html 文件。

$ monolith https://dltdojo.github.io/taichu-crypto/taichu-raw/apache-big5.html > ~/smb/test/apache-big5.html
[ https://dltdojo.github.io/taichu-crypto/taichu-raw/apache-big5.html ]
[ https://dltdojo.github.io/taichu-crypto/favicon.png ]
[ https://dltdojo.github.io/taichu-crypto/css/variables.css ]
[ https://dltdojo.github.io/taichu-crypto/css/general.css ]
[ https://dltdojo.github.io/taichu-crypto/css/chrome.css ]
[ https://dltdojo.github.io/taichu-crypto/css/print.css ]
[ https://dltdojo.github.io/taichu-crypto/FontAwesome/css/font-awesome.css ]
[ https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800 ]
[ https://fonts.googleapis.com/css?family=Source+Code+Pro:500 ]
[ https://dltdojo.github.io/taichu-crypto/highlight.css ]
[ https://dltdojo.github.io/taichu-crypto/tomorrow-night.css ]
[ https://dltdojo.github.io/taichu-crypto/ayu-highlight.css ]
[ https://dltdojo.github.io/taichu-crypto/taichu-raw/puml/dltdojo3-seq-http.svg ]
[ https://dltdojo.github.io/taichu-crypto/taichu-raw/images/apache-big5.png ]
[ https://dltdojo.github.io/taichu-crypto/taichu-raw/images/apache-big5-html-src.png ]
[ https://dltdojo.github.io/taichu-crypto/ace.js ]
[ https://dltdojo.github.io/taichu-crypto/editor.js ]
[ https://dltdojo.github.io/taichu-crypto/mode-rust.js ]
[ https://dltdojo.github.io/taichu-crypto/theme-dawn.js ]
[ https://dltdojo.github.io/taichu-crypto/theme-tomorrow_night.js ]
[ https://dltdojo.github.io/taichu-crypto/elasticlunr.min.js ]
[ https://dltdojo.github.io/taichu-crypto/mark.min.js ]
[ https://dltdojo.github.io/taichu-crypto/searcher.js ]
[ https://dltdojo.github.io/taichu-crypto/clipboard.min.js ]
[ https://dltdojo.github.io/taichu-crypto/highlight.js ]
[ https://dltdojo.github.io/taichu-crypto/book.js ]

Post-quantum cryptography

Post-quantum cryptography - Wikipedia

TOC

News

2019

What Google’s Quantum Breakthrough Means for Blockchain Cryptography - Bitcoin News

I’m not very optimistic that quantum computers will have practical applications any time soon. I’m quite worried that quantum computing will go the same way as nuclear fusion: that it will remain forever promising but never quite work. Nevertheless, quantum supremacy is going to be a super exciting event.

PlantUML

如何使用模板

先看過 Preprocessing - PlantUML,模板採用 iuml 副檔名前面加上 tpl,引入語法如下。

!include tpl-web123-v1.iuml

使用 tpl-web123-v1 解說 DAO

web123 template v1

tpl-web123-v1.iuml 內容

@startuml
actor "消費者\nAlice" as Alice #red
participant "Browser\n瀏覽器\nBrowser"  as Browser
participant "Service\n那個平台\nSRV" as SRV
collections "HTTP Server\n超文本傳輸協定服務\nHTTPD" as HTTPD
actor "生產者\nBob" as Bob #yellow
== 100 寫 HTML ==
autonumber 101
Bob -> HTTPD : 上傳或產生 HTML
note left
文字創作、圖片、歌曲、影片、
人際關係、個資、身分識別
end note
== 200 給 HTTP RESPONSE ==
autonumber 201
HTTPD -> Browser : HTTP/1.1 200 OK\n內容 HTML 
Browser -> Alice : 解析HTML內容後\n展現在瀏覽器裡面
== 300 Web 1.0 免費白吃的午餐 ? 注意力與隱私商品化 ==
autonumber 301
Alice <-> SRV : 給我內容
SRV <-> Bob : 生產內容
Bob <-> SRV : $💰$ 誰來付錢 $💰$
== 400 Web 2.0 免費的商品 ==
autonumber 401
SRV <-> Alice : 消費者免費拿到內容\n給平台收賣個資
SRV -> SRV : 💰💰💰💰💰💰💰
Bob <-> SRV : 消費者變成生產者\n在平台販售內容。 
== 500 Web 3.0 去媒介平台 ==
autonumber 501
Bob -> Alice : 消費者變成生產者,買賣不經那個平台
Alice -> Bob : 生產者變成消費者,買賣不經那個平台
@enduml

套版加上 DAO 的說明

web123 result

web123-v1.puml 套用模板

@startuml
header DLTDOJO3
footer 
https://dltdojo.github.io/taichu-crypto/
Licensed under the Apache License Version 2.0
<img:../images/qr-taichu-crypto.png{scale=0.5}>
end footer
title dltdojo3-web123-v1
legend top
那個 Web x.0 的故事
endlegend
skinparam handwritten true
!include tpl-web123-v1.iuml
'這裡以下都是新增
== 600 Web 3.0 DAO ==
autonumber 601
participant "DAO"  as DAO
Alice -> DAO : 加入 DAO
Bob -> DAO : 加入 DAO
Bob <-> Alice : 消費者變成生產者,買賣不經那個平台。
DAO -> Alice : 💰💰💰
DAO -> Bob : 💰💰💰
@enduml

PlantUML Online Demo Service 效果

如要外部使用可以利用下列連結,利用線上服務 PlantUML Online Demo Service 利用下列方式加入模板。

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-web123-v1.iuml

pl

時序圖樣版 Sequence Diagram Template

Sequence Diagram - PlantUML

Web3.0 概念: tpl-web123-v1.iuml

web123 template v1

內容

@startuml
actor "消費者\nAlice" as Alice #red
participant "Browser\n瀏覽器\nBrowser"  as Browser
participant "Service\n那個平台\nSRV" as SRV
collections "HTTP Server\n超文本傳輸協定服務\nHTTPD" as HTTPD
actor "生產者\nBob" as Bob #yellow
== 100 寫 HTML ==
autonumber 101
Bob -> HTTPD : 上傳或產生 HTML
note left
文字創作、圖片、歌曲、影片、
人際關係、個資、身分識別
end note
== 200 給 HTTP RESPONSE ==
autonumber 201
HTTPD -> Browser : HTTP/1.1 200 OK\n內容 HTML 
Browser -> Alice : 解析HTML內容後\n展現在瀏覽器裡面
== 300 Web 1.0 免費白吃的午餐 ? 注意力與隱私商品化 ==
autonumber 301
Alice <-> SRV : 給我內容
SRV <-> Bob : 生產內容
Bob <-> SRV : $💰$ 誰來付錢 $💰$
== 400 Web 2.0 免費的商品 ==
autonumber 401
SRV <-> Alice : 消費者免費拿到內容\n給平台收賣個資
SRV -> SRV : 💰💰💰💰💰💰💰
Bob <-> SRV : 消費者變成生產者\n在平台販售內容。 
== 500 Web 3.0 去媒介平台 ==
autonumber 501
Bob -> Alice : 消費者變成生產者,買賣不經那個平台
Alice -> Bob : 生產者變成消費者,買賣不經那個平台
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-web123-v1.iuml

HTTP 概念: tpl-story-http-v1.iuml

story http template v1

內容

@startuml
actor "消費者\nAlice" as Alice #red
participant "瀏覽器\nBrowser"  as Browser
collections "超文本傳輸協定服務\nHTTPD" as HTTPD
participant "那個平台\nSRV" as SRV
actor "生產者\nBob" as Bob #yellow
== 100 寫 HTML ==
autonumber 101
Bob -> SRV : 註冊或架設
Bob -> HTTPD : 上傳或產生 HTML
note left
文字創作、圖片、歌曲、影片、
人際關係、個資、身分識別
end note
== 200 HTTP 協定 ==
autonumber 201
Alice -> Browser : http://example.com/foo
Browser -> HTTPD : GET /foo HTTP/1.1
HTTPD -> Browser : HTTP/1.1 200 OK\n內容 HTML 
Browser -> Alice : 解析HTML內容後\n展現在瀏覽器裡面
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-story-http-v1.iuml

Exit, Voice and Loyalty《叛離、抗議與忠誠》: tpl-evl-v1.iuml

Joystream - Github 的 DAO 治理結構針對組織的 Exit, Voice, and Loyalty - wikipedia 問題加以設計,希望探索或建構出可長久的組織結構。

evl v1

內容

@startuml
actor "個人甲\nAlice" as Alice #red
collections "原組織或企業\nORG" as ORG
collections "新組織或企業\nNORG" as NORG #red
actor "個人乙\nBob" as Bob #yellow
== 100 當個人甲乙對原組織的運作感到不滿時 ==
autonumber 101
Bob -> ORG: 🔥😠🔥
Alice -> ORG: 🔥😠🔥
== 200 Exit 叛離 ==
autonumber 201
Alice -> ORG : Bye
note right
脫離組織運作
end note
Alice -> NORG : 加入其他組織
Alice -> Bob : 或拉人分裂出新組織
== 300 Voice 抗議 ==
autonumber 301
Bob -> ORG : 抗議啦
note left
提出異議
end note
ORG -> Bob : 回應
Bob -> Bob : Loyalty 忠誠
ORG -> Bob : 不理會
Bob -> Bob : Exit 叛離
== 400 Loyalty 忠誠 ==
autonumber 401
Bob -> ORG : 組織運轉順暢
Alice -> ORG : 組織運作良好
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-evl-v1.iuml

The Site Reliability Workbook Ch2 - Implementing SLOs : tpl-sre-slos-v1.iuml

tpl-sre-slos-v1.svg

內容

' WIP
' The Site Reliability Workbook Chapter 2 - Implementing SLOs
' https://landing.google.com/sre/workbook/chapters/implementing-slos/
' Service Level Objectives/Service Level Indicators
@startuml
skinparam ParticipantPadding 10
skinparam BoxPadding 10

actor "使用者" as User #Yellow

box "Request-driven\n需求導向" #LightBlue
	participant "Web Site" as Web
	participant "API Service" as Api
end box

box "Pipeline\n管路" #LightCoral
	participant "Pipeline Job" as Job
	participant Log
end box

box "Storage\n儲存" #LightPink
	database "GameState" as DB
	database UserData
	participant UserFile
end box

note right of Web
  SLIs: 
  Availability
  Latency
  Quality
end note

User -> Web
Web -> DB
Api -> DB


Api -> Job

note right of Job
  SLIs: 
  Freshness
  Correctness
  Coverage
end note

DB -> UserData
UserData -> Api


note right of DB
  SLIs: 
  Durability
end note

actor "SRE\n網站可靠性工程師" as RE #Red
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-sre-slos-v1.iuml

Random Oracle tpl-random-oracle-v1.iuml

tpl-random-oracle-v1.svg

內容

' https://www.odaily.com/post/5133096
' https://www.jishuwen.com/d/2JWW
@startuml
' Random Oracle RO
actor Alice #yellow
participant "Random Oracle" as RO #yellow
actor Bob

== 100 Random Oracle ==
autonumber 101
Alice -> RO: 輸入值
Alice <- RO: 輸出隨機值
note left
隨機分佈在值域內
end note
Bob -> RO: 輸入值
Bob <- RO: 隨機值
note right
如 103 輸入值與 101 一樣
104 值會與 102 相同
end note
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-random-oracle-v1.iuml

DNS-over-HTTPS (DoH) tpl-doh-dns-https-v1.iuml

A cartoon intro to DNS over HTTPS

tpl-doh-dns-https-v1.svg

內容

' A cartoon intro to DNS over HTTPS
' https://hacks.mozilla.org/2018/05/a-cartoon-intro-to-dns-over-https/
@startuml
skinparam ParticipantPadding 5
skinparam BoxPadding 5
box "Alice Realm" #LightBlue
  actor "Alice\n瀏覽器" as Alice #yellow
  participant "DoB\nAlice" as ADOB #white
end box
box "The kingdom of far far away" #white
  participant "DNS善意\nPort 53" as GDNS #green
  participant "DNS惡意\nPort 53" as BDNS #red
  participant "DoH\nPort 443" as DOH #yellow
end box
box "Bob Realm" #LightCoral
  participant "DoB\nBob" as BDOB #white
  actor "Bob\n瀏覽器" as Bob
end box
== 100 Tracking 追蹤 ==
autonumber 101
Bob -> BDNS : register
Alice -> GDNS : DNS port 53
GDNS -> BDNS
BDNS -> BDNS : tracking 紀錄追蹤
BDNS -> GDNS : 給正確的地址
GDNS -> Alice
== 200  Spoofing 欺騙 ==
autonumber 201
BDNS -> GDNS : 給假造的地址
GDNS -> Alice
note over ADOB
要自保需確認每個查詢都是可信的。
一般人在公共場域無法確認。
end note
== 300 DNS over HTTPS (DoH) ==
autonumber 301
Alice -> DOH : 可設定可信的 DoH\nHTTPS port 443
DOH -> DOH : 紀錄
DOH -> Alice : 可信任的地址
note over DOH
隱私與內容過濾
1. DNS 個人紀錄被移出 ISP
2. DNS 紀錄(ISP端與用戶裝置端)的利用、加值、過濾
3. DNS 紀錄 ISP端法遵議題
4. 資料集中化不再分散各個 DNS
5. 牽涉不同司法管轄
6. 需信任 DoH 不做紀錄
end note
== 400 DNS over Blockchain (DoB) ==
autonumber 401
ADOB <-> BDOB: 同步
Alice -> ADOB: 只查自己節點
Bob -> BDOB: 無紀錄洩漏問題
note over DOH
1. DoB 不普及
2. DoB 節點成本需用客戶在乎隱私動機來支付,
   否則容易轉成中心化 API 服務架構,回到紀
   錄竄改100/200原點,還不如用 DoH。
end note
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-doh-dns-https-v1.iuml

Crypto Custody : tpl-custody-fork-v1.iuml

The Crypto Custody Conundrum: What Are We Even Talking About?

tpl-custody-fork-v1.svg

內容

' https://www.coindesk.com/the-crypto-custody-conundrum-what-are-we-even-talking-about
' The Crypto Custody Conundrum: What Are We Even Talking About?
' 借據、本票(民法債務不履行) 保管條(刑法侵占)
@startuml
skinparam ParticipantPadding 5
skinparam BoxPadding 5

actor "使用者" as User #Yellow
box "司法" #LightSalmon
	participant "民法\nCivil law" as CIVIL
	participant "刑法\nCriminal law" as CRIMINAL
end box
actor "SafeKeeping\n保管人" as SK #Red
== 100 C is for custody ==
autonumber 101
User -> SK: 保管申請
User -> SK: 交付保管物
SK -> User: 保管證明\n契約、借據、本票(民法債務不履行)\n保管條(刑法侵占)
User -> SK: 要求返還
SK -> SK: 無法返還
SK <-> User: 協調
User -> CIVIL: 最佳利益???
User -> CRIMINAL: 最佳利益???
== 200 C is for complication ==
autonumber 201
User <-> SK
note right
無記名資產
金鑰即所有權
交付金鑰與轉帳之保管差異
end note
== 300 C is for consent ==
autonumber 301
User <-> SK
note right #red
多簽之部分所有權保管
end note
== 400 C is for consumer ==
autonumber 401
User <-> SK
note right
金融消費者保護法
虛擬通貨適用
end note
== 500 C is for challenge ==
autonumber 501
User <-> SK
note right
有種東西稱為分叉 fork
ownership?
liability?
end note

@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-custody-fork-v1.iuml

法國大革命 : tpl-French-Revolution-v1.iuml

法國大革命

tpl-French-Revolution-v1.svg

內容

' Révolution française
' https://zh.wikipedia.org/zh-tw/%E6%B3%95%E5%9B%BD%E5%A4%A7%E9%9D%A9%E5%91%BD
' 法國大革命(法語:Révolution française, 1789年-1799年)是法國的一段社會激進與政治動盪的時期,對於法國歷史以及全歐洲都留下深刻廣泛影響。
'
@startuml
skinparam ParticipantPadding 5
skinparam BoxPadding 5

actor "法國國王\n路易十六" as King #Yellow

box "三級會議" #Red
	actor "代表甲" as A
	actor "代表乙" as B
end box

database "議會大樓" as BUILDING

box "國民議會\n室內網球場" #Blue
	actor "代表丙" as C
	actor "代表丁" as D
end box

participant "巴士底監獄" as Bastille

== 三級會議 ==
A <-> B : 衝突
King -> BUILDING: 整修關閉
== 附近網球場 ==
B -> C : 換地方
C <-> D : 繼續衝突
note right: 網球場宣言
D -> Bastille
== 法國大革命 ==
Bastille --> King : 三年後法蘭西第一共和國成立
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-French-Revolution-v1.iuml

組件圖樣板 Component Diagram Template

Component Diagram - PlantUML

State machine Replication SMR

There are only two hard problems in distributed systems: 2. Exactly-once delivery 1. Guaranteed order of messages 2. Exactly-once delivery @mathiasverraes

How Does Distributed Consensus Work?

tpl-state-machine-replication-v1.svg

內容

' How Does Distributed Consensus Work? https://medium.com/s/story/lets-take-a-crack-at-understanding-distributed-consensus-dad23d0dc95
' https://ethfans.org/posts/lets-take-a-crack-at-understanding-distributed-consensus-part-1
' https://www.chainnews.com/articles/879522545128.htm
' 
@startuml

agent "Client" as Client

rectangle "State Machine Replication" {

    rectangle "Server1" #LightBlue {
        frame SM1 [
            State Machine 
            ----
            balance(alice)=199
            balance(bob)=1
        ] 
        component "Consensus" as Consensus1
        component "Ledger" as Ledger1
    }

    rectangle "Server2" #LightCoral{
        frame SM2 [
            State Machine 
            ----
            balance(alice)=199
            balance(bob)=1
        ]

        component "Consensus" as Consensus2
        component "Ledger" as Ledger2
    }

    rectangle "ServerN+1" as ServerN1 #yellow

    stack TwoHardThins #LightGreen[
        Two hard problems in distributed systems:
        2. Exactly-once delivery 
        1. Guaranteed order of messages 
        2. Exactly-once delivery
        @mathiasverraes
    ]
}

Client --> Consensus1 : == 1
Consensus1 <--> TwoHardThins : == 2
TwoHardThins <--> Consensus2 : == 2
Consensus1 <--> ServerN1: == 2 問題:故障與時序
Consensus2 <-> ServerN1 : == 2
Consensus1 -> Ledger1 : == 3
Ledger1 --> SM1 : == 4
Consensus2 --> Ledger2: == 3
Ledger2 --> SM2 : == 4
SM2 -> Client: == 5
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-state-machine-replication-v1.iuml

TON tpl-ton-v1.iuml

TON Blockchain Test Network

tpl-ton-v1.svg

內容

' [ton-blockchain/ton github](https://github.com/ton-blockchain)
' 
@startuml

' TON有四个角色:验证员,合作者,提名者和渔夫(Validators, collators, nominators, and fisherman.)
actor "Validator\n驗證者" as Validator 
actor "Collator\n合作者" as Collator 
actor "Nominator\n提名者" as Nominator 
' 漁夫捕捉無效驗證者的無效交易
actor "Fisherman\n漁夫" as Fisherman #red


' 主鏈有 TON 的創世參數還有驗證節點紀錄
rectangle "TON Main Blockchain" {
    ' 可生成最多 2^32 條工作鏈条工作链,創工作鏈需 2/3 驗證節點支持。
    ' 每條工作鏈的虛擬機器可不同,地址帳戶代幣合約等也有差異。
    ' 每條工作鏈會有該工作鏈的基礎原生代幣。
    rectangle "Workchain 1\n工作鏈壹" as WC1 #LightBlue {
        ' 每條工作鏈可生成最多 2^60 條分片鏈
        ' 同一條工作鏈的分片鏈其帳戶合約地址格式相同。
        component "Shardchain\n分片鏈A1" as W1SA1
        component "Shardchain\n分片鏈A2" as W1SA2
        component "Shardchain\n分片鏈AN" as W1SAN
    }

    rectangle "Workchain 2\n工作鏈貳" as WC2 #LightCoral{
        component "Shardchain\n分片鏈B1" as W2SB1
        component "Shardchain\n分片鏈B2" as W2SB2
        component "Shardchain\n分片鏈BN" as W2SBN
    }

    rectangle "Workchain N\n工作鏈N"
}

W1SA1 <--> W1SA2: == 1 Hypercube routing 
W1SA2 <-> W1SAN: == 1 
W1SA1 <--> W1SAN: == 1 

Validator ..> WC1
Fisherman ..> WC1
Collator ..> WC2
Nominator ..> WC2

@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-ton-v1.iuml

TV Buddha by Nam June Paik tpl-tv-buddha

Looking at Buddha Watching TV

tv buddha

內容

@startuml
' TV Buddha by Nam June Paik
' “The future is now.” -Nam June Paik
package "You" {
  [👀] as U #Yellow
}

package "TV Buddha" as TVBuddha{
  folder "Buddha"{
    [👀] as BUDDHA #Green
  }
  folder "Tele - vision" {
	  [📺] as TV
	  [🎥] as Camera
  }
}

U -> TVBuddha
BUDDHA -> TV
Camera --> BUDDHA
TV - Camera
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-tv-buddha-v1.iuml

DLTDOJO3 v1 tpl-dltdojo3-v1.iuml

tpl-dltdojo3-v1.svg

內容

@startuml

actor "Developer" as Dev
actor "Operator" as Op
actor "學員\nUser" as User #red

rectangle "DLTDOJO3" {

    rectangle "cli" #LightBlue {
        component "taichu-raw" as TaichuRaw #yellow
        component mdbook
    }

    rectangle "Kubernetes" #LightCoral{
        rectangle "Services" {
            component "Git\nCICD" as drone
            component plantuml
            component registry
        }
        rectangle "MAD WHITE" as madwhite {
            component "code\nserver" as cs
        }
        rectangle "MAD RED" as madred {
            component "veloren\nserver" as vs
        }
    }
}

TaichuRaw -- mdbook
Op ..> TaichuRaw
Dev ..> plantuml
Dev ..> registry
Dev ..> cs
User ..> cs
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-dltdojo3-v1.iuml

WIP tpl-dltdojo3-x

Comp

@startuml
header DLTDOJO3
footer 
https://dltdojo.github.io/taichu-crypto/
Licensed under the Apache License Version 2.0
<img:../images/qr-taichu-crypto.png{scale=0.5}>
end footer
title dltdojo3-comp-template
skinparam handwritten false
left to right direction

package "Docker Container" {
    folder "Code Server container"{
      [Code\nServer] as CS #Yellow
      [mad-white\nprojects]
      folder "VS Code Extension"{
       [plantuml]
      }
    }
}

package "Kubernetes" {
  folder "microk8s" {
	[DNS]
	[Registry]
	[Storage]
  }
  folder "Gitops"{
    [GIT gogs] as GIT #Green
    [CI drone] as CI #Blue
  }
}

CS --> GIT : 1. push
GIT -> CI : 2. build and test
CI --> Registry : 3. push
CI <-- Registry : 4. pull image

@enduml

狀態圖樣版 State Diagram Template

tpl-state-machine-v1.iuml

tpl-state-machine-v1.svg

內容

@startuml
[*] -> Waiting
Waiting --> Started: Start
Waiting --> Finished : Done
Started --> Finished : Finish
Started --> Suspended : Suspend
Suspended --> Started : Resume
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-state-machine-v1.iuml

Hyperledger Fabric

安裝 tpl-hlf-cp-install-v1.iuml

Commercial paper tutorial

tpl-hlf-cp-install-v1.svg

內容

' Commercial paper tutorial
' https://hyperledger-fabric.readthedocs.io/en/release-1.4/tutorial/commercial_paper.html
'
@startuml
folder MagnetoCorp {
    agent "Admin\nConsole" as MAC
    artifact "Paper\nContract" as MPC
}

folder PaperNet {
    node CA 
    node Orderer
    folder "MagnetoCorp" as PNMC {
       package "Peer" as MPEER {
         node "Ledger\nDatabase" as LDB
         artifact "Paper\nContract" as PNPC
       } 
    }
}
MPC -> MAC
MAC --> MPEER: install
PNPC <-> LDB: getState/putState
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-cp-install-v1.iuml

實體化 tpl-hlf-cp-instantiate-v1.iuml

Commercial paper tutorial

tpl-hlf-cp-instantiate-v1.svg

內容

' Commercial paper tutorial
' https://hyperledger-fabric.readthedocs.io/en/release-1.4/tutorial/commercial_paper.html
'
@startuml
folder MagnetoCorp {
    agent "Admin\nConsole" as MAC
}

folder PaperNet {
    node CA 
    node Orderer
    folder "MagnetoCorp" as PNMC {
       package "Peer" as MPEER {
           artifact "Paper\nContract" as PNPC
       } 
       package "Chaincode\nContainer" as CC { 
         artifact "Paper\nContract" as PNPC_CC
       }
    }
}
MAC --> MPEER: = 1. Instantiate
MPEER --> CC : = 2. Create
PNPC --> PNPC_CC: = 3. Copy
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-cp-instantiate-v1.iuml

應用開發 tpl-hlf-cp-app-v1.iuml

Commercial paper tutorial

tpl-hlf-cp-app-v1.svg

內容

' Commercial paper tutorial
' https://hyperledger-fabric.readthedocs.io/en/release-1.4/tutorial/commercial_paper.html
'
@startuml
folder MagnetoCorp {
    actor Alice
    agent "Issue App" as IAPP
    agent "Gateway" as MGW
    agent "Wallet" as WALLET
}

folder PaperNet {
    node CA 
    node Orderer
    folder "MagnetoCorp" as PNMC {
       package "Peer" as MPEER {
           artifact "Paper\nContract" as PNPC
       } 
       package "Chaincode\nContainer" as CC { 
         artifact "Paper\nContract" as PNPC_CC
       }
    }
}

IAPP <- WALLET: = 1 retrieve
IAPP --> MGW: = 2 submit
MGW <--> MPEER: = 3 propose/endorse
MGW --> Orderer: = 4 order
Orderer --> MPEER: = 5 distribute
MPEER -> MGW: = 6 notify
MGW -> IAPP: = 7 response
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-cp-app-v1.iuml

系統說明 tpl-hlf-cp-seq-v1.iuml

tpl-hlf-cp-seq-v1.svg

內容

' Commercial paper tutorial
' https://hyperledger-fabric.readthedocs.io/en/release-1.4/tutorial/commercial_paper.html
'
@startuml
participant MagnetoCorp as COM
actor Alice as Alice #red
collections PaperNet as NET
actor Bob as Bob #Yellow
participant DigiBank as BANK
COM -> Alice: Authz
BANK -> Bob: Authz
Alice -> NET: Issue
Bob -> NET:  Buy 
Bob -> NET: Redeem
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-cp-seq-v1.iuml

狀態 tpl-hlf-cp-state-v1.iuml

tpl-hlf-cp-state-v1.svg

內容

' https://hyperledger-fabric.readthedocs.io/en/release-1.4/developapps/architecture.html
' Lifecycle
'
@startuml
'hide empty description
[*] --> issued : issue
note top
 Commercial papers transition between 
 issued, trading and redeemed states 
 by means of the issue, buy and redeem 
 transactions.
end note
issued -> trading : buy
trading -> trading: buy
trading -down-> redeemed: redeem
redeemed --> [*]
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-cp-state-v1.iuml

網路 tpl-hlf-pnet-seq-v1.iuml

tpl-hlf-pent-seq-v1.svg

內容

' https://hyperledger-fabric.readthedocs.io/en/release-1.4/developapps/scenario.html
' The PaperNet commercial paper network. Six organizations currently use PaperNet network to 
' issue, buy, sell, redeem and rate commercial paper. 
' MagentoCorp issues and redeems commercial paper. 
' DigiBank, BigFund, BrokerHouse and HedgeMatic all trade commercial paper with each other. 
' RateM provides various measures of risk for commercial paper.
'
@startuml

participant MagentoCorp #yellow
participant DigiBank
collections PaperNet #green
participant BigFund
participant BrokerHouse
participant HedgeMatic
participant RateM

== 100 PaperNet commercial paper network ==
MagentoCorp <-> PaperNet: issue/redeem
note right #aqua
  MagentoCorp issues and 
  redeems commercial paper. 
end note
DigiBank <-> PaperNet: buy/sell/redeem
note right
	DigiBank, BigFund, BrokerHouse and HedgeMatic 
    all trade commercial paper with each other. 
end note
BigFund <-> PaperNet: buy/sell/redeem
BrokerHouse <-> PaperNet: buy/sell/redeem
HedgeMatic <-> PaperNet: buy/sell/redeem
RateM <-> PaperNet: rate/notify
note left #red
	RateM provides various measures of risk 
    for commercial paper.
end note
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-hlf-pnet-seq-v1.iuml

Ethereum

WIP: tpl-eth-erc20-state-v1.iuml

tpl-eth-erc20-state-v1.svg

內容

' WIP
' https://eips.ethereum.org/EIPS/eip-20
'
@startuml
'hide empty description
[*] --> issued : issue
note top
 EIP 20: ERC-20 Token Standard
  mapping (address => uint256) private _balances;
  mapping (address => mapping (address => uint256)) private _allowances;
  
  transfer(address recipient, uint256 amount)
  allowance(address owner, address spender)
  approve(address spender, uint256 amount)
  transferFrom(address sender, address recipient, uint256 amount)
end note
issued -> active : deploy
active -> active: transfer
active -down-> allowance: allowance
allowance -> active: approve
@enduml

引用

!include https://dltdojo.github.io/taichu-crypto/puml/tpl-eth-erc20-state-v1.iuml

TODO

  • seq diagrams http://blockchainers.org/index.php/tag/erc-223/

Messaging

以開源即時加密通訊專案為主

Signal

Keybase

keybase 內建 Stellar 的錢包, 未來加密隱私即時通訊軟體掛錢包看來將變成標配,畢竟加解密或簽交易合約都需要金鑰,類似軟體 Telegram 電報的 TON 也正在測試中,採用以太坊架構的的 Status 也逐漸完備。

Status

Status

CoyIM

CoyIM messenger client

mdbook

安裝 mdbook

  1. 參考安裝 Rust說明將 rust 環境建立起來
  2. 先安裝 mdbook
  3. mdbook-toc
cargo install mdbook
cargo install mdbook-toc

如何編譯本書

bash tc.sh --build-book

編輯階段建議使用 serve 模式並開啟瀏覽器到 localhost:3000 加快開發。

bash tc.sh --serve-book

mdbook preprocessor

mdbook-toc

mdbook-toc 將 html 註解的 toc 轉成目錄格式

install

cargo install mdbook-toc

book.toml

[preprocessor.toc]
command = "mdbook-toc"
renderer = ["html"]

最簡單 python 版本

Preprocessor in Python? #975 - mdbook

#[preprocessor.minipp]
# 
#command = "src/mdbook/preprocessor.py"
#command = "src/mdbook/preprocessor.sh"
#renderer = ["html"]

A minimal preprocessor in Python

#!/usr/bin/env python

import json
import sys

if len(sys.argv) > 1:
    if sys.argv[1] == 'supports':
        # sys.argv[2] is the renderer name
        sys.exit(0)

context, book = json.load(sys.stdin)
json.dump(book, sys.stdout)

A minimal preprocessor in Bash

#!/bin/bash
#
jq . | tee /tmp/dump.json

rootbook : python add tabs

GooFit/rootbook

注意:這 tabs 新語法可將多個區塊用 tab 呈現比較精簡 UI,但列印成 PDF 模式無法全部列印內容出來。

{{#tabs}}
{{#tab Classic ROOT}}
  blah
{{#tab Modern ROOT}}
  blah
{{#tab Python}}
  def f(x):
    return y
{{#endtabs}}

book.toml

[output.html]
additional-css = ["includes/css/tabs.css"]
additional-js = ["includes/js/tabs.js"]

[preprocessor.tabs]
command = "python3 ./plugins/transform_tabs.py"
renderer = ["html", "epub"]

其他

playgen and Rust Playground

playpen 有限制 crate 列表如下,要支援 BIP39 之類工具包可能要 fork 出 rust-playground 來跑。

  • https://github.com/integer32llc/rust-playground/blob/master/compiler/base/Cargo.toml
extern crate chrono;
use chrono::Local;

fn main() {
    let date = Local::now();
    println!("{}", date.format("%Y-%m-%d %H:%M:%S"));
}

mathjax (無法生成待解決)

mdbook 可內嵌 mathjax

book.toml

[output.html]
mathjax-support = true

Elliptic-curve

\\( \mathbf y^2 = x^3 + ax + b\\) over \\(F_p\\)

呈現結果

\( \mathbf y^2 = x^3 + ax + b\) over \(F_p\)

secp256k1

\\( \mathbf y^2 = x^3 + 7 \\) over \\(F_p\\)

呈現結果

\( \mathbf y^2 = x^3 + 7 \) over \(F_p\)

不是人人都熟悉 mathjax 語法,如要測驗應該先提供參考語法。

學習資源

線上書籍

區塊鏈相關線上教學

另外 github 上面收集學習資源的專案

有些新的專案上面沒列出,可直接查詢關鍵字。

教學文章

Github/Gitlab 區塊鏈相關開源專案

cdr/code-server

microsoft/WebTemplateStudio 工具步驟 4 雖是選配倒是關鍵,快速建站模板後面應該會有人會寫 firebase 之類擴充,另外 cdr/code-server 是否能跑要找時間測試。

其他

網路資源

遊戲

交易市集

報告

Test Faucet

幣圈測試練功難免缺水,缺測試盤纏時通常前往開發社群留言打個招呼並不缺,不過自助水龍頭對一般人還是比較方便,可惜幣圈變化快,這類自助水龍頭壽命往往不長。

Voxel

書籍與文獻

TOC

報告

ITU - Focus Group on Application of Distributed Ledger Technology

Focus Group on Application of Distributed Ledger Technology

  • Technical Specification / DLT terms and definitions
  • Technical Specification / DLT reference architecture
  • Technical Specification / Assessment criteria for DLT platforms

ITU issues guidance on the adoption of blockchain - ITU News

These documents will support ITU standardization in working groups including Q22/16 (Distributed Ledger Technologies and e-Services) and Q14/17 (Security aspects of Distributed Ledger Technologies).

Blockchain Now And Tomorrow

Cambridge Judge Business School: Global Enterprise Blockchain Benchmarking Study

  Cambridge Judge Business School: 2nd Global Enterprise Blockchain Benchmarking Study

Hyperledger Fabric appears to be the platform of choice across all industries: Fourty-eight per cent of covered projects that are used in production have chosen Hyperledger Fabric as the core protocol framework underlying the network, followed by R3’s Corda platform (15 per cent) and Coin Sciences’ MultiChain framework (10 per cent).

法案

US NDAA proposes blockchain for national defense

Text - H.R.2500 - 116th Congress (2019-2020): National Defense Authorization Act for Fiscal Year 2020 | Congress.gov | Library of Congress

SEC. 255. Briefing on use of blockchain technology for defense purposes.

  • improve cybersecurity, beginning at the hardware level, of vulnerable assets such as energy, water and transport grids, through distributed versus centralized computing
  • reduce single points of failure in emergency and catastrophe decision-making by subjecting the decision to consensus validation through distributed ledger technologies
  • improve the efficiency of defense logistics and supply chain operations
  • enhance the transparency of procurement auditing
  • allow innovations to be adapted by the private sector for ancillary uses

金融監管

区块链技术在证券领域的应用与监管研究 - 上海证券交易所 www.sse.com.cn › publication › actofcourt › law

IRS 稅務指引

Virtual currency: IRS issues additional guidance on tax treatment and reminds taxpayers of reporting obligations | Internal Revenue Service

The new revenue ruling addresses common questions by taxpayers and tax practitioners regarding the tax treatment of a cryptocurrency hard fork.

Embedded supervision

In DLT-based markets, by contrast, data credibility is assured by economic incentives. In this world, the supervisor must examine the conditions under which the market’s economic consensus is strong enough to guarantee the quality of the data contained in the distributed ledger.

BIS Working Papers No 811 Embedded supervision: how to build regulation into blockchain finance by Raphael Auer

This challenge goes deeper than current discussions on under what circumstances cryptoassets should be considered as commodities, securities or other asset classes. Rather, it is how to embed the concept of economic finality in today’s legal system, and the adjacent question of how to treat such assets on balance sheets.

經濟

The coming of external intelligence

Where is technology taking the economy? | McKinsey

经济学家 Brian Arthur:当工作先于凯恩斯的预测成了稀缺资源,我们的人生意义何在? - 链闻 ChainNews

数字技术不仅仅是一种虚拟的经济体,也是外部化的智能。它极大地促进了这些领域的能力,却也在一点一点的抛弃人工劳作。

数字货币因数字经济诞生

经济学家朱嘉明:数字货币因数字经济诞生,绝非传统货币的简单移植 - 链闻 ChainNews

我的结论是,如果说 21 世纪是人类社会和经济社会生活全方位极具复杂化的世纪,那么数字货币将是这种复杂化的核心所在。

常用觀點連結

忒修斯之船(英語:ship of Theseus)

一九八四

book1984

「溫斯頓,你相信現實是客觀的、外界的和自我存在的。你相信現實是自明的。當你以為看到某件東西時,你假定別人也像你一樣看見這件東西,但是我告訴你,溫斯頓,現實並不是外界之物,是在人類思想中間。並不是在個人思想中間,因為個人是會犯錯的,是會滅亡的:現實是在黨的思想中,這是集體的,是不朽的。黨認為是真理,這便是真理。」 - 一九八四

蜷川實花 MIKA NINAGAWA

拍照不是一件從零到一的職業,而是把一的東西變成二,如果沒有一(被攝物),根本不會有二。

Giorgio Manganelli

Tutto documentato, tutto arbitrario.

工作

201909

附錄

命令列 tc.sh

如何生成 Google Protocol Buffers 文件

base on the pseudomuto/protoc-gen-doc: Documentation generator plugin for Google Protocol Buffers tool.

# libra example
git clone https://github.com/libra/libra.git /tmp/src/libra
bash tc.sh --gen-proto-doc /tmp/src/libra/types/src/proto /tmp/output.md

Source code

#!/bin/bash

need_cmd() {
    if ! check_cmd "$1"; then
        err "need '$1' (command not found)"
    fi
}

check_cmd() {
    command -v "$1" > /dev/null 2>&1
}

err() {
    say "$1" >&2
    exit 1
}

say() {
    printf "TRIER: %s\n" "$1"
}

drun_ddj3base(){
  docker run -it --rm -p 8443:8443 -v "${PWD}:/home/coder/project" dltdojo/ddj3base:mad-white --allow-http --no-auth 
}

check_all(){
  need_cmd jq
  need_cmd bash
}

build_book(){
    usage &> mdbook/src/cmd-help.txt
    pushd mdbook
    mdbook build --dest-dir ../docs 
    popd
}


serve_book(){
    pushd mdbook
    mdbook serve
    popd
}


#
# gen-proto-doc PROTOS_DIR DEST_FILE
# [grpc-ecosystem/grpc-gateway: gRPC to JSON proxy generator following the gRPC HTTP spec](https://github.com/grpc-ecosystem/grpc-gateway)
# go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
# go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
# go get -u github.com/golang/protobuf/protoc-gen-go
#
gen_proto_doc(){
    set -x
    PROTOS_DIR=$1
    MDFILE=md-proto-gen-tmp.md
    DEST_FILE=$2
    pushd $PROTOS_DIR
    rm /tmp/$MDFILE
    find . -type f \
       -not -path "./google/protobuf/*" \
       -not -path "./github.com/gogo/protobuf/gogoproto/*" \
       -not -path "./googleapis/google/api/*" \
       -name '*.proto' | xargs protoc -I. -I/usr/local/include \
       -I$GOPATH/src \
       -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
       --doc_out=/tmp --doc_opt=markdown,$MDFILE
    #sed -i "1i# ProtocolBuffer Doc\n## Generated Date:$(date --iso-8601=seconds)\n<!-- toc -->" /tmp/$MDFILE
    sed -i "1i# Generated Date:$(date --iso-8601=seconds)\n" /tmp/$MDFILE
    echo -e '\n# Protos File Tree\n```\n' >> /tmp/$MDFILE 
    tree -P "*.proto" . >> /tmp/$MDFILE
    echo -e '\n```\n' >> /tmp/$MDFILE 
    echo -e "# Protobuf sources\n" >> /tmp/$MDFILE
    find . -type f \
       -not -path "./google/protobuf/*" \
       -not -path "./github.com/gogo/protobuf/gogoproto/*" \
       -not -path "./googleapis/google/api/*" \
       -name '*.proto' \
       -exec echo -e '\n## src:{}\n```proto\n' \; -exec cat {} \; -exec echo -e '\n```\n' \; >> /tmp/$MDFILE
    cp -f /tmp/$MDFILE $DEST_FILE
    popd
}

usage() {
    cat 1>&2 <<EOF
DLTDOJO CLI Tool

USAGE:
    bash tc.sh [FLAGS] [OPTIONS]

FLAGS:
    --drun                  啟動 ddj3base 容器服務
    --build-book            使用 mdbook 編譯本書    
    --serve-book            使用 mdbook 啟動同步編輯網頁服務
    -c, --check             check need commands
    -h, --help              Prints help information
    -v, --version           Prints version information
EOF
}


case "$1" in
  --drun) shift; drun_ddj3base $@ ;;
  --build-book) shift; build_book $@ ;;
  --serve-book) shift; serve_book $@ ;;
  --gen-proto-doc) shift; gen_proto_doc $@ ;;
  -h|--help)
      usage
      exit 0
      ;;
  *) usage
     exit 0
     ;;
esac

授權條款

  • https://en.wikipedia.org/wiki/Apache_License
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2019 JOYE LIN

   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.

測試頁面

程式語言 Rust

Playpen with hello.rs file

extern crate chrono;
use chrono::Local;

fn main() {
    let date = Local::now();
    println!("{}", date.format("%Y-%m-%d %H:%M:%S"));
}

Playpen editable 即時修改功能不像 Jupyter Notebook 多元,目前適合用來學習簡易 Rust 語法。

fn main() {
    let number = 5;
    print!("{}", number);
}

可以探索其他語法的即時編輯功能如 java, golang, nodejs

其他