├── api ├── .keep ├── handlers │ ├── blockchainHandler.go │ └── transactionHandler.go ├── graphqlObj │ ├── infoABCI.go │ ├── extension.go │ ├── transaction.go │ ├── issueDetail.go │ ├── masterInfo.go │ ├── agentForMaster.go │ ├── agentForOwner.go │ ├── consol.go │ ├── shipment.go │ └── properties.go └── api │ └── api.go ├── assets └── .keep ├── deploy └── .keep ├── docs ├── .keep └── _config.yml ├── init └── .keep ├── pkg ├── .keep └── blockfreight │ └── .keep ├── plugins └── .keep ├── scripts └── .keep ├── tools └── .keep ├── web ├── app │ └── .keep ├── static │ └── .keep └── template │ └── .keep ├── bin ├── .gitignore └── bfn.sh ├── examples ├── .keep ├── BFTX_JSON_Validation.docx ├── config.yaml ├── Navia_pubkey.yaml ├── alice_pubkey.yaml ├── bf_tx_example.json ├── bf_tx_schema_pub_var_rfc2.json ├── carol_pri_key.json ├── alice_pri_key.json └── bob_pri_key.json ├── githooks └── .keep ├── third_party └── .keep ├── .vscode └── settings.json ├── logs └── .gitignore ├── cmd └── bftx │ └── install_bftx.sh ├── install_bftx.sh ├── .travis.yml ├── lib ├── pkg │ ├── tenderhelper │ │ └── tenderhelper.go │ ├── crypto │ │ ├── crypto.proto │ │ ├── crypto.pb.go │ │ └── crypto.go │ ├── saberservice │ │ ├── saber.proto │ │ ├── saberservice_test.go │ │ └── saberservice.go │ ├── common │ │ └── common.go │ └── leveldb │ │ └── leveldb.go └── app │ ├── blockchain │ └── blockchain.go │ ├── bftx_logger │ └── bftx_logger.go │ ├── validator │ └── validator.go │ ├── bft │ └── bft.go │ └── bf_tx │ └── bf_tx.go ├── .gitignore ├── Dockerfile.dev ├── blockfreight_node.sh ├── test ├── app │ ├── validator │ │ └── validator_test.go │ └── bf_tx │ │ └── bf_tx_test.go └── pkg │ └── common │ └── common_test.go ├── config.toml ├── LICENSE ├── Dockerfile ├── Gopkg.toml ├── blockfreight.go ├── config └── config.go ├── README.md └── Gopkg.lock /api/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /deploy/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /init/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pkg/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /plugins/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /scripts/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/app/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bin/.gitignore: -------------------------------------------------------------------------------- 1 | /*/ -------------------------------------------------------------------------------- /examples/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /githooks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /third_party/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/static/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/template/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pkg/blockfreight/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /logs/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /examples/BFTX_JSON_Validation.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blockfreight/go-bftx/HEAD/examples/BFTX_JSON_Validation.docx -------------------------------------------------------------------------------- /cmd/bftx/install_bftx.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | go get github.com/blockfreight/go-bftx 4 | cd $GOPATH/src/github.com/blockfreight/go-bftx 5 | dep ensure 6 | 7 | cd $GOPATH/src/github.com/blockfreight/go-bftx/cmd/bftx 8 | go install -v 9 | 10 | bftx node start -------------------------------------------------------------------------------- /install_bftx.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl 4 | chmod +x ./kubectl 5 | sudo mv ./kubectl /usr/local/bin/kubectl -------------------------------------------------------------------------------- /api/handlers/blockchainHandler.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import "github.com/blockfreight/go-bftx/lib/app/blockchain" 4 | 5 | func GetInfo() (interface{}, error) { 6 | info, err := blockchain.GetInfo() 7 | if err != nil { 8 | return nil, err 9 | } 10 | 11 | return info, nil 12 | } 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - 1.9.x 4 | before_install: 5 | # Setup dependency management tool 6 | - curl -L -s https://github.com/golang/dep/releases/download/v0.3.1/dep-linux-amd64 -o $GOPATH/bin/dep 7 | - chmod +x $GOPATH/bin/dep 8 | install: 9 | - dep ensure && go install ./cmd/... 10 | script: 11 | - go test ./test/... -------------------------------------------------------------------------------- /api/graphqlObj/infoABCI.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import ( 4 | "github.com/graphql-go/graphql" 5 | ) 6 | 7 | // InfoType object for GraphQL integration 8 | var InfoType = graphql.NewObject( 9 | graphql.ObjectConfig{ 10 | Name: "Info", 11 | Fields: graphql.Fields{ 12 | "Data": &graphql.Field{ 13 | Type: graphql.String, 14 | }, 15 | }, 16 | }, 17 | ) 18 | -------------------------------------------------------------------------------- /lib/pkg/tenderhelper/tenderhelper.go: -------------------------------------------------------------------------------- 1 | package tenderhelper 2 | 3 | import ( 4 | "github.com/tendermint/tendermint/abci/client" 5 | "github.com/tendermint/tendermint/abci/types" 6 | ) 7 | 8 | // GetBlockAppHash uses the abcicli to get the last block app hash 9 | func GetBlockAppHash(client abcicli.Client) ([]byte, error) { 10 | resInfo, err := client.InfoSync(types.RequestInfo{}) 11 | return resInfo.LastBlockAppHash, err 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Mac OS X files 2 | .DS_Store 3 | 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.dll 7 | *.so 8 | *.dylib 9 | *.csv 10 | *.log 11 | 12 | # Test binary, build with `go test -c` 13 | *.test 14 | 15 | # Output of the go coverage tool, specifically when used with LiteIDE 16 | *.out 17 | 18 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 19 | .glide/ 20 | 21 | # Folders 22 | bft-db/ 23 | vendor/ 24 | .idea 25 | data/ 26 | /LOG -------------------------------------------------------------------------------- /Dockerfile.dev: -------------------------------------------------------------------------------- 1 | FROM golang:latest 2 | 3 | RUN apt-get update && apt-get install -y jq 4 | 5 | RUN mkdir -p /go/src/github.com/blockfreight/blockfreight-alpha 6 | WORKDIR /go/src/github.com/blockfreight/blockfreight-alpha 7 | 8 | COPY Makefile /go/src/github.com/blockfreight/blockfreight-alpha/ 9 | COPY glide.yaml /go/src/github.com/blockfreight/blockfreight-alpha/ 10 | COPY glide.lock /go/src/github.com/blockfreight/blockfreight-alpha/ 11 | 12 | RUN make get_vendor_deps 13 | 14 | COPY . /go/src/github.com/blockfreight/blockfreight-alpha 15 | -------------------------------------------------------------------------------- /blockfreight_node.sh: -------------------------------------------------------------------------------- 1 | if [ -x "$(command -v docker)" ]; then 2 | echo 'Downloading Blockfreight Go-bftx docker image' 3 | docker pull blockfreight/go-bftx:rc1 4 | 5 | echo 'Initializing Blockfreight Node' 6 | docker run --entrypoint=bftx -p 46657:46657 -p 8080:8080 blockfreight/go-bftx:rc1 node start 7 | # command 8 | else 9 | echo "Go-bftx requires Docker but it appears not to be installed. Please check your system has Docker installed (https://docs.docker.com/install/) before installing Go-bftx. Aborting." 10 | exit 1; 11 | fi -------------------------------------------------------------------------------- /test/app/validator/validator_test.go: -------------------------------------------------------------------------------- 1 | package validator 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/blockfreight/go-bftx/lib/app/bf_tx" 7 | "github.com/blockfreight/go-bftx/lib/app/validator" 8 | ) 9 | 10 | func TestValidator(t *testing.T) { 11 | t.Log("Test on validator function") 12 | bftx, err := bf_tx.SetBFTX("../../../examples/bf_tx_example.json") 13 | if err != nil { 14 | t.Log(err.Error()) 15 | } 16 | result, err := validator.ValidateBFTX(bftx) 17 | if err != nil { 18 | t.Log(err.Error()) 19 | } 20 | 21 | if result != "Success! [OK]" { 22 | t.Error("Error on result of TestValidator") 23 | t.Error(result) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/pkg/common/common_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/blockfreight/go-bftx/lib/pkg/common" 8 | ) 9 | 10 | func TestHashByteArrays(t *testing.T) { 11 | t.Log("Test HashBytesArrays on Common Lib") 12 | firstHash := []byte("firstHash") 13 | secondHash := []byte("secondHash") 14 | resultExpected := []byte{35, 63, 72, 164, 129, 98, 5, 123, 77, 35, 41, 21, 136, 230, 199, 208, 195, 68, 188, 65, 198, 199, 175, 43, 113, 168, 46, 95, 93, 208, 85, 227} 15 | 16 | resultGenerated := common.HashByteArrays(firstHash, secondHash) 17 | 18 | if bytes.Compare(resultGenerated, resultExpected) != 0 { 19 | t.Error("Error on HashByteArrays!") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /api/graphqlObj/extension.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // ExtensionInput object for GraphQL integration 6 | var ExtensionInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "ExtensionInput", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "ServiceLevel": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | }, 14 | }, 15 | ) 16 | 17 | // Extension object for GraphQL integration 18 | var Extension = graphql.NewObject( 19 | graphql.ObjectConfig{ 20 | Name: "Extension", 21 | Fields: graphql.Fields{ 22 | "ServiceLevel": &graphql.Field{ 23 | Type: graphql.String, 24 | }, 25 | }, 26 | }, 27 | ) 28 | -------------------------------------------------------------------------------- /api/graphqlObj/transaction.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import ( 4 | "github.com/graphql-go/graphql" 5 | ) 6 | 7 | // TransactionType object for GraphQL integration 8 | var TransactionType = graphql.NewObject( 9 | graphql.ObjectConfig{ 10 | Name: "Transaction", 11 | Fields: graphql.Fields{ 12 | "Id": &graphql.Field{ 13 | Type: graphql.String, 14 | }, 15 | "Type": &graphql.Field{ 16 | Type: graphql.String, 17 | }, 18 | "Verified": &graphql.Field{ 19 | Type: graphql.Boolean, 20 | }, 21 | "Transmitted": &graphql.Field{ 22 | Type: graphql.Boolean, 23 | }, 24 | "Properties": &graphql.Field{ 25 | Type: PropertiesType, 26 | }, 27 | "Private": &graphql.Field{ 28 | Type: graphql.String, 29 | }, 30 | }, 31 | }, 32 | ) 33 | -------------------------------------------------------------------------------- /config.toml: -------------------------------------------------------------------------------- 1 | GenesisJSON_URL = "https://raw.githubusercontent.com/blockfreight/tools/master/blockfreightnet-kubernetes/examples/blockfreight/genesis.json" 2 | RPC_ListenAddress = "tcp://0.0.0.0:46657" 3 | P2P_ListenAddress = "tcp://0.0.0.0:8888" 4 | Validator_Domain = "blockfreight.net" 5 | P2P_PORT = "8888" 6 | CreateEmptyBlocks = false 7 | 8 | [validators] 9 | [validators.bftx0] 10 | NodeID = "42cba48e9c5a96ad876f04581e52c11fd501f96c" 11 | ValidatorName = "bftx0" 12 | 13 | [validators.bftx1] 14 | nodeID = "6af1628b40c1b8f84882c27df07d36e4a797921a" 15 | ValidatorName = "bftx1" 16 | 17 | [validators.bftx2] 18 | nodeID = "ab263e441107837fb46f41f3c65004040b9f3814" 19 | ValidatorName = "bftx2" 20 | 21 | [validators.bftx3] 22 | nodeID = "1beae9f29ad2b231841d7de1ae91e136b6abb87f" 23 | ValidatorName = "bftx3" -------------------------------------------------------------------------------- /api/graphqlObj/issueDetail.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // IssueDetailsInput object for GraphQL integration 6 | var IssueDetailsInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "IssueDetails", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "PlaceOfIssue": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "DateOfIssue": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | }, 17 | }, 18 | ) 19 | 20 | // IssueDetails object for GraphQL integration 21 | var IssueDetails = graphql.NewObject( 22 | graphql.ObjectConfig{ 23 | Name: "IssueDetails", 24 | Fields: graphql.Fields{ 25 | "PlaceOfIssue": &graphql.Field{ 26 | Type: graphql.String, 27 | }, 28 | "DateOfIssue": &graphql.Field{ 29 | Type: graphql.String, 30 | }, 31 | }, 32 | }, 33 | ) 34 | -------------------------------------------------------------------------------- /api/graphqlObj/masterInfo.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // MasterInfoInput object for GraphQL integration 6 | var MasterInfoInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "MasterInfo", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "FirstName": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "LastName": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | "Sig": &graphql.InputObjectFieldConfig{ 17 | Type: graphql.String, 18 | }, 19 | }, 20 | }, 21 | ) 22 | 23 | // MasterInfo object for GraphQL integration 24 | var MasterInfo = graphql.NewObject( 25 | graphql.ObjectConfig{ 26 | Name: "MasterInfo", 27 | Fields: graphql.Fields{ 28 | "FirstName": &graphql.Field{ 29 | Type: graphql.String, 30 | }, 31 | "LastName": &graphql.Field{ 32 | Type: graphql.String, 33 | }, 34 | "Sig": &graphql.Field{ 35 | Type: graphql.String, 36 | }, 37 | }, 38 | }, 39 | ) 40 | -------------------------------------------------------------------------------- /api/graphqlObj/agentForMaster.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // AgentForMasterInput object for GraphQL integration 6 | var AgentForMasterInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "AgentForMaster", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "FirstName": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "LastName": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | "Sig": &graphql.InputObjectFieldConfig{ 17 | Type: graphql.String, 18 | }, 19 | }, 20 | }, 21 | ) 22 | 23 | // AgentForMaster object for GraphQL integration 24 | var AgentForMaster = graphql.NewObject( 25 | graphql.ObjectConfig{ 26 | Name: "AgentForMaster", 27 | Fields: graphql.Fields{ 28 | "FirstName": &graphql.Field{ 29 | Type: graphql.String, 30 | }, 31 | "LastName": &graphql.Field{ 32 | Type: graphql.String, 33 | }, 34 | "Sig": &graphql.Field{ 35 | Type: graphql.String, 36 | }, 37 | }, 38 | }, 39 | ) 40 | -------------------------------------------------------------------------------- /lib/app/blockchain/blockchain.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "strconv" 9 | 10 | rpc "github.com/tendermint/tendermint/rpc/client" 11 | ) 12 | 13 | type Blockchain struct { 14 | LastBlockAppHash []byte 15 | Data string 16 | } 17 | 18 | func GetInfo() (Blockchain, error) { 19 | var result Blockchain 20 | rpcClient := rpc.NewHTTP(os.Getenv("LOCAL_RPC_CLIENT_ADDRESS"), "/websocket") 21 | err := rpcClient.Start() 22 | if err != nil { 23 | fmt.Println("Error when initializing rpcClient") 24 | fmt.Println(err.Error()) 25 | return result, errors.New(strconv.Itoa(http.StatusInternalServerError)) 26 | } 27 | defer rpcClient.Stop() 28 | 29 | abciInfo, err := rpcClient.ABCIInfo() 30 | if err != nil { 31 | fmt.Println("Error when initializing rpcClient") 32 | fmt.Println(err.Error()) 33 | return result, errors.New(strconv.Itoa(http.StatusInternalServerError)) 34 | } 35 | 36 | result.Data = abciInfo.Response.Data 37 | result.LastBlockAppHash = abciInfo.Response.LastBlockAppHash 38 | 39 | return result, nil 40 | } 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016-2017 Blockfreight, Inc. [BFT:XCP] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /api/graphqlObj/agentForOwner.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // AgentForOwnerInput object for GraphQL integration 6 | var AgentForOwnerInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "AgentForOwner", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "FirstName": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "LastName": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | "Sig": &graphql.InputObjectFieldConfig{ 17 | Type: graphql.String, 18 | }, 19 | "ConditionsForCarriage": &graphql.InputObjectFieldConfig{ 20 | Type: graphql.String, 21 | }, 22 | }, 23 | }, 24 | ) 25 | 26 | // AgentForOwner object for GraphQL integration 27 | var AgentForOwner = graphql.NewObject( 28 | graphql.ObjectConfig{ 29 | Name: "agentForOwner", 30 | Fields: graphql.Fields{ 31 | "FirstName": &graphql.Field{ 32 | Type: graphql.String, 33 | }, 34 | "LastName": &graphql.Field{ 35 | Type: graphql.String, 36 | }, 37 | "Sig": &graphql.Field{ 38 | Type: graphql.String, 39 | }, 40 | "ConditionsForCarriage": &graphql.Field{ 41 | Type: graphql.String, 42 | }, 43 | }, 44 | }, 45 | ) 46 | -------------------------------------------------------------------------------- /examples/config.yaml: -------------------------------------------------------------------------------- 1 | # YAML example for encrytion configuration 2 | --- 3 | version: v0.1 4 | group : SS512 # Default encryption setup 5 | recipients: 6 | # Define all the recipients who can see the encryption message 7 | # You can specify which user can see which part of information 8 | # in the following section 9 | - Alice 10 | - Bob 11 | - Carol 12 | - Navia 13 | encryptionfields: 14 | # Details of the encryption fields 15 | # The format of this part is: 16 | # =========================== 17 | # - FIELD_NAME: field_name 18 | # AUTHORIZEDUSER : 19 | # - user name 1 20 | # - user name 2 21 | # =========================== 22 | # the RECIPIENTS of the FIELD could see the information of 23 | # the particular field 24 | - fieldname : GrossWeight 25 | authorizeduser: 26 | - Alice 27 | - Navia 28 | - fieldname : PortOfLoading 29 | # Only Alice can reveal the Packages section 30 | authorizeduser: 31 | - all 32 | publickeys: 33 | # Link each recipient to their public key file 34 | - userid : Alice 35 | keyfile : alice_pubkey.yaml 36 | - userid : Bob 37 | keyfile : bob_pri_key.json 38 | - userid : Carol 39 | keyfile : carol_pri_key.json 40 | - userid : Navia 41 | keyfile : Navia_pubkey.yaml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.5 2 | 3 | # BFTXHOME is where your genesis.json, key.json and other files including state are stored. 4 | ENV BFTXHOME /go/src/github.com/blockfreight/go-bftx 5 | ENV LOCAL_RPC_CLIENT_ADDRESS tcp://localhost:46657 6 | ENV DOCKER_RPC_CLIENT_ADDRESS tcp://blockfreight:46657 7 | 8 | # Create a basecoin user and group first so the IDs get set the same way, even 9 | # as the rest of this may change over time. 10 | RUN addgroup blockfreight && \ 11 | adduser -S -G blockfreight blockfreight 12 | 13 | RUN mkdir -p $BFTXHOME && \ 14 | chown -R blockfreight:blockfreight $BFTXHOME 15 | WORKDIR $BFTXHOME 16 | 17 | # Expose the blockfreight home directory as a volume since there's mutable state in there. 18 | VOLUME $BFTXHOME 19 | 20 | # jq and curl used for extracting `pub_key` from private validator while 21 | # deploying tendermint with Kubernetes. It is nice to have bash so the users 22 | # could execute bash commands. 23 | RUN apk add --no-cache curl jq 24 | 25 | FROM golang:latest 26 | 27 | RUN apt-get update && apt-get install -y jq curl 28 | RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 29 | 30 | WORKDIR /go/src/github.com/blockfreight/go-bftx 31 | 32 | COPY . /go/src/github.com/blockfreight/go-bftx 33 | 34 | RUN dep ensure 35 | RUN go install ./cmd/... 36 | 37 | EXPOSE 8080 38 | 39 | ENTRYPOINT /go/bin/bftx 40 | -------------------------------------------------------------------------------- /examples/Navia_pubkey.yaml: -------------------------------------------------------------------------------- 1 | PublicKey: eJylVkGOFDEM/MpqzntIupPY4RF8AKHVgvbGbQEJIf5OqlxOt7hy6Jl0OnFc5bKd34+Pjw9Pvx8vL1+/vb6/v7yst8eXX9/f3h/PT2v25+u3H2+c/dT8+anjqes59Kz3WubzUzsxWD/OmfUz12ytrum23nxtHOvfBr609bIGtiYnV62Jviamrf/1+Bq39T8LVtd4qYcONlgva+BFA+yDZbjnOG3Nja7jcZJPGTKL1bWWMIRlOK6WNTsAscuhWFICHwzQs54fTOZrTQsbMHk4avAAXHRhbfKWmEpgStDDwiL9BIPkaGq2m+xhP7GNYLUWgD7jfGuBBrvgQS8ai2W/gC0TjYeMwDxcRFqSjtOMA3JctRXfxpQJRquEA9ZlDpySV5GFc4AUrl/IGFyPoPFLBdT0Iijt+qzNlkLZ51NPYOVUTIsEBqfsUEy5x8UxtuBc8IRVCEqX+BjiFt6HCDxIxQcy7mGW5qtooVsgyeVzk/4iPpbYeixlQCxWeMaChqYEmZIgCfSHjJzhC6UABuGh72gVwakResCKTLPN+iFyw4JSARtgFs7iHEBl8jL+p9ITwiY7Kfdap+iupSjlavhDay7oGyFAbZaGX1v6Tr8jSS2S89jCEyLEgFkNFyKNWibGVLb0K448j8JvwQ5XhkhbJukRML0Kpkksm326Qu66nCN4iGln4FDYgtasTkwNC/vBWpQLUT+UKPxkidNEZz800UUSVgA8fCGoEcJ325Go6SUr5ikGuGFKH1M6VeiHnu6f/6yS//a/7cBPSZWeqh4BZIR4SPdHfGR9KUp8T7n6VQU8pARPKVDFc2ocFaGkoXmLXtCgGjVlZ+6OMsNViokFDqJArNhAysU2QzDSeUapHpcHUBaI3v0u9wJi5FAXO1WF5lBPUUGiLzOrhAuMqfZFyszM/yNOyzrS9ZgiEZVO9S+SZGauwnrArbGYBbuop0CirG79lvVF/an5VeYZpSNrH6WULZo9W53S1KciQREMdq6meA1VWMvLQbtIYUqGcNstvXatJeDMx5adPHUmsOOmB0vUIy8GQ3xGymZcCbdLLeospshFLI5cvo0UJbWLx62wS5VnHNqV9SZCPfN05j2i1ywVymqyq/vLkFzifnAVlKmok8X8ll6zPiEClvcb33JKKaotYRyd5JCPWdIQgJm3pzFuXShqYfay3JytZ6jQw1DL1h1SyKuCZwUsyj5Xkoy512dHYOspeReKZjavgNmOeM/j/NYsmZuR+ueOZL9xvitzz77MYnymHwn+RvuR97AzK8q9CFAbnm6Ga1scp1KgJorjRl5Is0vTKnNNLZNYs533m0joIcsmL7S6vZlWRSql18yupnJtmfZy6N+28OcvUFg3PA== 2 | -------------------------------------------------------------------------------- /examples/alice_pubkey.yaml: -------------------------------------------------------------------------------- 1 | PublicKey: eJylVkuOHTcQu8rgrb2Q1PrmELlAEAzsYHbeTRIgMHz3iCxS3XsvXs+0WipVsUhKP16/v357+/F6f//r+9fPz/f3/fb69t/fH5+vL2979N+v3//54OgfdX55a/jl/Sv67fec236kut+u/U/JeOt4LL3O/c/cI33/HS3mVXxMWF4KYqTz2B/b/qcOj6S9ZMwIMffktQfXXt64L7Lo8VMoPioe+Tx2sLEDz6xv46xHznlpDoeQ8kCQsjcamDwcokX5rI84XC59z58jsubalB8B2ojMWRwjMa2F4eR5PeqO9GoMzCt2rwfKHDCySszoAKbFpsCZOBCU7GYgILBDIGIouNaMrIaLQC7IqRVlOWegLYBOM1bsxU8J1SROQrx6ZqOPVU3GFsiU2Z02Y6QqKYZAQZWU6g6DClAKCFCv2HdMJ50DIiQ81iMqUZma0Q1LVm1RUg8WRRFLPB6mDDpgPKOhTVCiKExDfCBG9Hs0OWYm0w7Y9B6BWA6KGykqiSyG+km+YOU0ihQHY7HxPQjGmGsI7qivKRCiEsKhuVi41mG50BrZLLYAxvQbVlSBx9GSRHfuCZz6OAGbNIcMABRoinohi2k5oYR+i9lh2q1QaRF8ZLbYc15KiZk0rYxFLdpYpUgiAXJTNcdSkm2JxGvWTQt4iWeKiGQK+b4kquWeJVPHeM2mBOs41fTIg31AaVMdpuT5dTpEOJR4Nc1DWcJ8oDxlUtQyNkVAaoNfi6jK6EmSvB1Gjjm6vaqoKWJRiOzub1EiKIEOcClX+o1+bf75cx8KH796YIyDblHyymyoF8iwz8OY8mzbaUh3C0qgD+nBP0NNilAvRakynyFpk5VrPGnIQCVGuiMH0SnO3G8vHm41gxNmWAO3SxL8OgRKIfZo5wqis1HBi+qEx23B/FwPYVNUT9Xmch8387i9eYWQiD98iPGgkSWypeRBcuVLa5EXKTaclsKjQVCPEbxNVzuMc/rmCNylNR62ybYsrV9CKXhnmgX3tUNTpbwuVE1rpxmxUockj9Ac5dJU14nYn/gW++g43XXKITkbkaR4wiB/XhaGjbZaUzkkR7MuakgXT+k3OjrCBXvECRPKPimlckytvhv4nAZv8D9q6pJFWFURMDyolg9DP27MLtN6KpNsDym+YLnVtgsydzwvBUPObA7WaD+NMHezWeLpIn7VxaXZgcILZ3SLiWWd4myd6e8bpBkb/r6US/V5ffrmO8e5c6EOKvhcSp1zerCj+X6KPH0tvQ+porYOl3ZERyLdYjNXUEfzMRzCl3T6ephWkmkt85L1QhPmcZwoJKpcK47kc+7KR4YB082SJ1d2RsW3n2QDuWL6EI2sAlJMxc7bjIShro+ac9qRHB6VPw+Hn/8Dhqo9zg== -------------------------------------------------------------------------------- /examples/bf_tx_example.json: -------------------------------------------------------------------------------- 1 | { 2 | "Properties":{ 3 | "Shipper":"VLX454323F", 4 | "BolNum":"15554", 5 | "RefNum":"154532165", 6 | "HouseBill":"testtest", 7 | "Vessel":"132153456", 8 | "PortOfLoading":"CNSHA", 9 | "PortOfDischarge":"AUADL", 10 | "UnitOfVolume":"", 11 | "NotifyAddress":"345 Bourke Street 4th floor, Melbourne VIC 3000, Australia", 12 | "DescOfGoods":"This is the goods description.", 13 | "GrossWeight":"15523", 14 | "FreightPayableAmt":"354534", 15 | "FreightAdvAmt":"35448552", 16 | "GeneralInstructions":"There are many general instructions.", 17 | "DateShipped":"20161128", 18 | "IssueDetails":{ 19 | "PlaceOfIssue":"Melbourne, Australia", 20 | "DateOfIssue":"20161128" 21 | }, 22 | "NumBol":"54684010805", 23 | "MasterInfo":{ 24 | "FirstName":"Master First Name", 25 | "LastName":"Master Last Name", 26 | "Sig":"" 27 | }, 28 | "AgentForMaster":{ 29 | "FirstName":"Agent First Name", 30 | "LastName":"Agent Last Name", 31 | "Sig":"" 32 | }, 33 | "AgentForOwner":{ 34 | "FirstName":"Owner First Name", 35 | "LastName":"Owner Last Name", 36 | "Sig":"", 37 | "ConditionsForCarriage":"There are the carriage conditions." 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /bin/bfn.sh: -------------------------------------------------------------------------------- 1 | #example parameter 0.15.0 2 | #rm ${VERSION}/tendermint_${VERSION}_darwin_386.zip 3 | #rm ${VERSION}/tendermint 4 | #wget https://github.com/tendermint/tendermint/releases/download/v${VERSION}/tendermint_${VERSION}_darwin_386.zip -P ${INSTALL_DIR} 5 | #wget https://github.com/blockfreight/go-bftx/releases/download/v0.5.15/bftnode -P ${INSTALL_DIR} 6 | #wget https://github.com/blockfreight/go-bftx/releases/download/v0.5.15/tendermint -P ${INSTALL_DIR} 7 | #--consensus.create_empty_blocks=false 8 | #--p2p.seeds="bftx0.blockfreight.net:888,bftx1.blockfreight.net:888,bftx2.blockfreight.net:888,bftx3.blockfreight.net:888" 9 | #--p2p.seeds=104.42.43.66:888 10 | #--consensus.create_empty_blocks=false 11 | #unzip ${VERSION}/tendermint_${VERSION}_darwin_386.zip -d ${INSTALL_DIR} 12 | $1=0.15.0 13 | VERSION=0.15.0 14 | INSTALL_DIR=~/.blockfreight 15 | pkill -9 "tendermint" 16 | pkill -9 "bftnode" 17 | rm -rf ${INSTALL_DIR} 18 | mkdir ${INSTALL_DIR} 19 | #wget https://github.com/blockfreight/go-bftx/releases/download/v0.5.15/blockfreight.zip -P ${INSTALL_DIR} 20 | curl -o ${INSTALL_DIR}/blockfreight.zip -L https://github.com/blockfreight/go-bftx/releases/download/v0.5.15/blockfreight.zip 21 | unzip ${INSTALL_DIR}/blockfreight.zip -d ${INSTALL_DIR} 22 | chmod +x ${INSTALL_DIR}/tendermint 23 | chmod +x ${INSTALL_DIR}/bftnode 24 | ${INSTALL_DIR}/tendermint version 25 | ${INSTALL_DIR}/tendermint unsafe_reset_all --home ${INSTALL_DIR} 26 | ${INSTALL_DIR}/tendermint init --home ./${INSTALL_DIR} 27 | ${INSTALL_DIR}/bftnode & ${INSTALL_DIR}/tendermint node --home ./${INSTALL_DIR} --consensus.create_empty_blocks=false --p2p.seeds="bftx0.blockfreight.net:888,bftx1.blockfreight.net:888,bftx2.blockfreight.net:888,bftx3.blockfreight.net:888" 28 | -------------------------------------------------------------------------------- /examples/bf_tx_schema_pub_var_rfc2.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | 5 | "shipper": { "type": "string" }, 6 | 7 | "BolNum": { "type": "number" }, 8 | 9 | "RefNum": { "type": "number"}, 10 | 11 | "consignee":{"type":"null"}, 12 | 13 | "vessel":{"type":"number"}, 14 | 15 | "PortOfLoading":{"type":"number"}, 16 | 17 | "PortOfDischarge":{"type":"number"}, 18 | 19 | "nofity_address":{"type":"string"}, 20 | 21 | "DescOfGoods":{"type":"string"}, 22 | 23 | "GrossWeight":{"type":"number"}, 24 | 25 | "FreightPayableAmt":{"type":"number"}, 26 | 27 | "FreightAdvAmt":{"type":"number"}, 28 | 29 | "GeneralInstructions":{"type":"string"}, 30 | 31 | "DateShipped":{"type":"number", "format":"date-time"}, 32 | 33 | "IssueDetails": { 34 | "type": "object", 35 | "properties": { 36 | "PlaceOfIssue": { "type": "string" }, 37 | "DateOfIssue": { "type": "number", "format":"date-time" } 38 | } 39 | }, 40 | 41 | "NumBol":{"type":"number"}, 42 | 43 | "MasterInfo": { 44 | "type": "object", 45 | "properties": { 46 | "FirstName": { "type": "string" }, 47 | "LastName": { "type": "string" }, 48 | "sig":{"type":"null"} 49 | } 50 | }, 51 | 52 | 53 | "AgentForMaster": { 54 | "type": "object", 55 | "properties": { 56 | "FirstName": { "type": "string" }, 57 | "LastName": { "type": "string" }, 58 | "sig":{"type":"null"} 59 | } 60 | }, 61 | 62 | 63 | 64 | "AgentForOwner": { 65 | "type": "object", 66 | "properties": { 67 | "FirstName": { "type": "string" }, 68 | "LastName": { "type": "string" }, 69 | "sig":{"type":"null"}, 70 | "ConditionsForCarriage":{"type":"string"} 71 | } 72 | } 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /test/app/bf_tx/bf_tx_test.go: -------------------------------------------------------------------------------- 1 | package bf_tx 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | bftx "github.com/blockfreight/go-bftx/lib/app/bf_tx" 8 | ) 9 | 10 | func TestSetBFTX(t *testing.T) { 11 | t.Log("Test on SetBFTX function") 12 | var prot bftx.BF_TX 13 | bftx, err := bftx.SetBFTX("../../../examples/bf_tx_example.json") 14 | if err != nil { 15 | t.Log(err.Error()) 16 | } 17 | if reflect.TypeOf(bftx) != reflect.TypeOf(prot) { 18 | t.Error("Error on type of result of SetBFTX") 19 | } 20 | } 21 | 22 | func TestTransmitedState(t *testing.T) { 23 | t.Log("Test on State function") 24 | newBftx, err := bftx.SetBFTX("../../../examples/bf_tx_example.json") 25 | if err != nil { 26 | t.Log(err.Error()) 27 | } 28 | 29 | newBftx.Transmitted = true 30 | result := bftx.State(newBftx) 31 | 32 | if result != "Transmitted!" { 33 | t.Error("Error on string result of bftx.State() when Transmitted = true") 34 | } 35 | 36 | } 37 | 38 | func TestSignedState(t *testing.T) { 39 | t.Log("Test on State function") 40 | newBftx, err := bftx.SetBFTX("../../../examples/bf_tx_example.json") 41 | if err != nil { 42 | t.Log(err.Error()) 43 | } 44 | 45 | newBftx.Verified = true 46 | result := bftx.State(newBftx) 47 | 48 | if result != "Signed!" { 49 | t.Error("Error on string result of bftx.State() when Verified = true") 50 | } 51 | 52 | } 53 | 54 | func TestConstructedState(t *testing.T) { 55 | t.Log("Test on State function") 56 | newBftx, err := bftx.SetBFTX("../../../examples/bf_tx_example.json") 57 | if err != nil { 58 | t.Log(err.Error()) 59 | } 60 | 61 | result := bftx.State(newBftx) 62 | 63 | if result != "Constructed!" { 64 | t.Error("Error on string result of bftx.State() when Transaction is Constructed") 65 | } 66 | 67 | } 68 | 69 | func TestReinitialize(t *testing.T) { 70 | t.Log("Test on Reinitialize function") 71 | var prop bftx.BF_TX 72 | 73 | newBftx := bftx.Reinitialize(prop) 74 | 75 | if newBftx.PrivateKey.Curve != nil || newBftx.PrivateKey.X != nil || newBftx.PrivateKey.D != nil || newBftx.Signhash != nil || newBftx.Signature != "" || newBftx.Verified != false || newBftx.Transmitted != false { 76 | t.Error("Error on BF_TX object returned by function bf_tx.Reinitialize()") 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://golang.github.io/dep/docs/Gopkg.toml.html 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | [[constraint]] 28 | name = "github.com/golang/protobuf" 29 | version = "=1.1.0" 30 | 31 | [[constraint]] 32 | branch = "master" 33 | name = "github.com/graphql-go/graphql" 34 | 35 | [[constraint]] 36 | branch = "master" 37 | name = "github.com/graphql-go/handler" 38 | 39 | [[constraint]] 40 | branch = "master" 41 | name = "github.com/mnmtanish/go-graphiql" 42 | 43 | [[constraint]] 44 | branch = "master" 45 | name = "github.com/syndtr/goleveldb" 46 | 47 | [[constraint]] 48 | name = "github.com/tendermint/tendermint" 49 | version = "0.22.4" 50 | 51 | [[constraint]] 52 | branch = "master" 53 | name = "github.com/urfave/cli" 54 | 55 | [[constraint]] 56 | name = "google.golang.org/grpc" 57 | version = "1.11.3" 58 | 59 | [[constraint]] 60 | name = "gopkg.in/yaml.v2" 61 | version = "2.2.1" 62 | 63 | [[constraint]] 64 | name = "github.com/BurntSushi/toml" 65 | version = "v0.3.0" 66 | 67 | [[override]] 68 | name = "google.golang.org/genproto" 69 | revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" 70 | 71 | [[override]] 72 | name = "github.com/rcrowley/go-metrics" 73 | revision = "e2704e165165ec55d062f5919b4b29494e9fa790" 74 | 75 | [[constraint]] 76 | name = "golang.org/x/net" 77 | revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" 78 | 79 | [[override]] 80 | name = "github.com/gogo/protobuf" 81 | version = "=1.1.0" 82 | 83 | [[override]] 84 | name = "github.com/golang/protobuf" 85 | version = "=1.1.0" 86 | 87 | [[override]] 88 | name = "github.com/tendermint/go-amino" 89 | version = "=v0.9.7" 90 | 91 | 92 | [prune] 93 | go-tests = true 94 | unused-packages = true 95 | -------------------------------------------------------------------------------- /lib/pkg/crypto/crypto.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package bfsaber; 4 | 5 | // service, encrypt a plain text into a cypertext using saber 6 | service BFSaberService { 7 | // request a service of encryption 8 | rpc BFTX_Encode(BFTX_Encode_request) returns (BFTX_transaction) {}; 9 | // request a service for decryption 10 | rpc BFTX_Decode(BFTX_Decode_request) returns (BFTX_transaction) {} 11 | } 12 | 13 | // The BFTX encryption transaction data structure (test version) 14 | message BFTX_Encode_request{ 15 | BFTX_transaction bftxtrans = 1; 16 | BFTX_encryptionConfig bftxconfig = 2; 17 | } 18 | // The BFTX decryption transaction data structure (test version) 19 | message BFTX_Decode_request{ 20 | BFTX_transaction bftxtrans = 1; 21 | string KeyName = 2; 22 | } 23 | 24 | message BFTX_transaction { 25 | BFTX_Payload properties = 1; 26 | } 27 | 28 | message BFTX_Payload{ 29 | string Shipper = 1; 30 | int32 BolNum = 2; 31 | int64 RefNum = 3; 32 | string Consignee = 4; 33 | int64 Vessel = 5; 34 | string PortOfLoading = 6; 35 | string PortOfDischarge = 7; 36 | string NotifyAddress = 8; 37 | string DescOfGoods = 9; 38 | int32 GrossWeight = 10; 39 | int32 FreightPayableAmt = 11; 40 | int64 FreightAdvAmt = 12; 41 | string GeneralInstructions = 13; 42 | string DateShipped = 14; 43 | int64 NumBol = 15; 44 | 45 | ISSUEDETAILS IssueDetails = 16; 46 | 47 | MASTERINFO MasterInfo = 17; 48 | 49 | AGENTFORMASTER AgentForMaster = 18; 50 | 51 | AGENTFOROWNER AgentForOwner = 19; 52 | string EncryptionMetaData = 20; 53 | } 54 | 55 | message ISSUEDETAILS{ 56 | string PlaceOfIssue = 1; 57 | string DateOfIssue = 2; 58 | } 59 | 60 | message MASTERINFO{ 61 | string FirstName = 1; 62 | string LastName = 2; 63 | string Sig = 3; 64 | } 65 | 66 | message AGENTFORMASTER{ 67 | string FirstName = 1; 68 | string LastName = 2; 69 | string Sig = 3; 70 | } 71 | 72 | message AGENTFOROWNER{ 73 | string FirstName = 1; 74 | string LastName = 2; 75 | string Sig = 3; 76 | string ConditionsForCarriage = 4; 77 | } 78 | 79 | message BFTX_encryptionConfig{ 80 | string Version = 1; 81 | string group = 2; 82 | repeated string Recipients = 3; 83 | repeated ENCRYPTIONFIELD EncryptionFields = 4; 84 | repeated PUBLICKEYS Publickeys = 5; 85 | 86 | } 87 | 88 | message ENCRYPTIONFIELD{ 89 | string FieldName = 1; 90 | repeated string AuthorizedUser= 2; 91 | } 92 | 93 | message PUBLICKEYS{ 94 | string UserID = 1; 95 | string keyfile = 2; 96 | } 97 | -------------------------------------------------------------------------------- /examples/carol_pri_key.json: -------------------------------------------------------------------------------- 1 | {"Carol":{"SK":"eJztWEGOHDcM/MpgznOQuiVRyiPygSAYOLEBB/AhwCYBAsN/T5NVJWlPPviYOXTibakpslgsivP1/ufnP54/33+6fb0/n79/+fD29nxef91/+/evT2/3x+16+8+HL39/ire/lP64VX/y9Rx8rr/zkR63fr3M6Xzc7Hpj10rOyd+Mx21cTy3X23Ztu1Z7xa58xLZrpTb+5UttmrxW/MycKj+qOMd8YWCxh43q/3F3zLf7q9Rk5aAb/kVzC74nD8RhA37ZNOUOG831RnciFrfmMbsL9aRf/sI/jgU/wb89MoxUfebH5GSEqOt1zk0IVHrpR9pEzghsVpQexELWw/EvPYKcEpx1qHO+viwGZMPK9f9yIuacCsw2TwhfBhjhUn8fpWU8OLkwdR4GAEnY1k/6BOSz0tVpEqgXucfsmdI7OtFw6gQdkp9riDFS2ofyVuZRJ6076u5Bm0QyruTU8amzKcCtND7G5MoAc4C7AYxguxGkDvOBQWS9yXemCyuZeEaImbkhD7pqwleDHEY3EcWhmNMGQDkFS4NXHklwLwAeNF1FMxViHN6YaudBm+GdsDoS3Sk78u5Pp4+WGWzURlZmAzEVVgBK83FWEzgsxgDZfW2qDWdmJZZ+TGelB5z5ZOCNXA9epLTJA+EaCo6V7eCMycwgcYN/AUYTKYcShWrLOk9lizIic923qJrGVROmJoloEjL/R4CaKpk+RL9BfoWGEftAWTujUgbhV1mAEUnursMSgYoqLYC2Cyt3pQoCuCrJmLkI9DwCd8YfT6WLqlv02FvGU/uv364u8PFHO8SgAKgTVAp5UXY7Fd49n27KCjLVCU0jMQgVymoKEOHAJ9JoiJBJywsyEAGzpCAIaR1DlG3mocqwkRInwqhE2ENZJ7MsohIKz8QZfTssTBtp5RUD/pDogxbbLIEs4YsGFT3NiEAUpC2daFwMGoSKJG6FkyzpKo6Fl0lFYMemu5O9knLWyewJ0qjoLeKfrOPsYys8X+nSzglDRBBnhvWsbgPC4t2JOp3i66QO1ac8V1tyguuAeqx70feShWQeFKrENFCWTEmC8+dKDir2XHcY3HSMItnoXIMf0mdkRyId6HA3sB+bc7gUBcsGi9OozbO3NWYxZ+lpRQaD8YfEDX3eyHZaqQp84hLbkNhMSXTmOP0KrxMh9QdPNN2sIIazORybGBeWzDuli3NwtNIPfRZ8ajoHXejzwlN5Eq4SfecqjQ2Cubp6ZFcKiwvRKaKnVbzLblwB8iJLJECRRAbUh0ZaddvbdDAJwmPLbufekDhWmpFSoXBF3UnODN4AOsWwKySUfdsKuq77g+23zIPedjK8KLsQV12QJYGVPbmubkO1jGLdGNDJkNUhXvPAax54zQOveeA1D/xv5oHXL0avDvHqEN/tEIPCqUoeyl/X3MLprtnSBFNY4eq8uZsQyiTPyZeaFkOdcdNtD05AicE0TS1rKiSJHcQ10+zXeJDwXAN3hNkmdTQZpFVU9dB9mcww3fXjRr1NptG5hHfsZELNttZZqZmRhyJECOZsU6F0umOnBW5nJRh10jh6Itz540OWm9LBrrkRg5gEpwtsWzMHh7jOlKKXarKLXBzsQm3Oz0kZKFIbNaGswXzRnInGvknfpJp4P+nNHzeQIHtoQDwB37B3YjCLij+uhLXOzEUDZufA1EF18PwO3jlMjXdvD9/+A96vaP4=","PK":"eJylVkFuGzEM/Irhsw/iriRKfUQ/UBRGWuSWW9oCRdC/V+TMyO65h0280i5FzgyH+3H9fP10+bje79/fXt7f7/d1d/32+8fr+/V2Wau/Xt5+vubqlzpulxaXrevgte7tKLfLWItWztvF14qvHbMSK/N2metqda329djaHQ1P2ZGPrZ3WeRdbfYdcO3GmlcaXGs7x2JjYHBmjxZ9Ix+PxWCpdUQ6mEW/0iBDP2EQdPpGX71CRsDPc6Ewna4loUXOk0E7mFQvxcm7ECfHuYQjS9FocY8UJ0dCyWRcCjVnGkb6RcwJrqjKKeCAb5cSbUYGVgmQDarP1ZnUgm1HW/3qiZisVYXsQwsUEI1Ma/1bphgsnV1IXZQCQgsfGyZyAvImuwZBAvSo9sueidw6iEdJJOZQ411FjUjqmeKv7qJPRA/XIoG8hOXesDLwaakpwG4PPubUyoRzg7gAj1e4Eaf2eBSdnLMd9Zhxs5tkT+EcuUxFVVqYar0RJ7kLIKJ6Ti4U94Ea0cELdpA8CYjywSswhgQCxaRcNeZC4FOGJx6rE2Ld0KJsoRU2Vwq4ioqipB3QUSAZKnX208c4nSWiUhMMM8WMxeahChGBW4RToJkxGYAnuYCdEEgFy7pvKNRmFKc1GWLKSIq8pMpwhsAH01knnVZhf5SK4yLaW2mQL1fd2AXlTQs2YD5mTaDy35VvUE4dtWVfZThVBzjJBbUVTP5nBbqrJ1A4C5DTS7KuT3lboDsFvSvWEOjJEN1xtfP2zRsDr/46HIT93GvRgjlMbSei5ba6Tsig1PUR4ysAq29LZkk532L4xVTQZSU+aHAZDOh40M6fLTVEGk6YPZlt3vaYmTNQKdqe0j6FwEv2mBmyyxszPZLLOyjOeS5nITM+Q+EMhOWjRP1JIml7ZsXMOdKXVaTkNAHSa0tjTp2y1ODGHUtvTxEGXEL9sPe06XXpoAnfy5Jt1opsdiKjsb7SHqxkqrS0HY3k0XaFRDfpRdpZpKiAajSwFov+nGkgTGWA06iVrVxlBZxpxoR85oIpqMNmMj2ffcd5FnFB9arHy48aB0tRk29M24wQILoVg4GuIitNBNSPDQ1wZXqycLo9JL/4afQ3fQA8PaigjI7T6+KjAtD8eaSOD+uRS9dxeSq9PNusmaPeFaYQPFktGAH6RSMkV6VP6zlZt2+oAXJNgHhZ4KinTD91Btepzw2+IQKQOApOFVJqLPqHOJ8vQHNNXys42CyDTyU1+gTH1djwBGjF3H6CrHBHnnlSVRea3mD/RP2mjnV3birSvEpLx7gLhoPH0IRTFStWwnBISe2R/h6Hvi6aeKC1TzmWgEhNpMt2nIfHnL0nIO98="}} 2 | -------------------------------------------------------------------------------- /examples/alice_pri_key.json: -------------------------------------------------------------------------------- 1 | {"Alice": {"SK":"eJztWEGOHDcM/MpiznuQ1KJI5RH5gBEMHNuADfgQYJMAhuG/WySr1D05Bcgxc+jZmW41RRaLRXG/3/74/OX+6+2Xl++3+/3D1/dvb/f7+nX7/dufn95ury/r7t/vv/71Ke6+6/b6In7VdTVc63etsj5KX7+O9aVV/zX8Y+KnrS+27oz1VyXXdX9Y/PXW3EbZH+uhrC9deaesV9TShK3Fc92c63WJfd2LkRdMxUf3j7o/ljFdhq3ime733ec6sSZuucvqRtraSH2x0oRk+BFf4HAw9LXeNL2Od0u9GBBNzyO4sBRuTb9duG5k3Olezxt25O59Q1kTxojSVwwHRnJTxzlwCFAqk+EGHTs3FBgCrmnplTII98V9kgYvzRJtALSTMXOveFQ8mhKL3F7fqz2PHUn2LdzT8G6n2e90OBUmPKAelBo04xF4KE6AfuS+anS6JkTusM6L1UDFsGIQlorYMqSRLMogJnispIxngHhmQoWxzEQqvI40lvQCrB8ZRzJr02saQNaSMfaDNHUfO1g/536z553YTvK9gDidLQ0LBwD0dbGvI3YpnpJLEt+GhAUkHRyWzckzeaDHSdgJNwLZAwhMfD/A4SG5KLYesonRCRAq2RGLiFFyHdXdkb5wIjI1kZJA38tb9JL74Fd4Z1kjGSCKMxN0oARLLjcy0JfbXoUn4Ywi0clllm0WFgkd3zoph2qHw1l1DRpGugRVhpCo5GOn9KAsKgtpJoMzO8JXGp+nCBgNuBKM3EipdUbCGrMygajlKqHZQRtBTEuU3de4al5iv/1YPeHjf+0XbnNCTMMLymdjMljeDqHnLWRoAj3mswGX1AuUUMTdEIznz19xE2NscCfzFRXG7KPoIInu01TYocxqYWUrqtCpqexCaqRLoag6N1jZ/rYDPpFcQSOM0A/GQWmnTjtDFWJz6gMl+dJpWsJkLLqQhAONsrKKSIkter5rRDGIEcCisVgwgAbV1KCUlwbQMppoH/XsK4xwgHYJGxtJZAd09U3n7n8QNAdvQrgmuk7KbKUgKHpAVoVkG/ZtB3v5KeGPIo0KC8HxINy/aOiOQRZM3QV+pGHjjzBYd39kxaehSqtsHAbOp6YacUZuUP/ycIJCRSglDuYhu30fJKJxk86ZjDq22wV8Gix1BhHc4KFqH38Ac2c3EK5C07rqbCQP0EZsCqLbWT8eYYgLO19KqbBaygapo73bKQiZUeBJyoHDNQmjbDZRUQdPUCha6oTUfxa6kGMoKYV2ZmohgNDx9pAkSLKhovk3TiDlovS2G9+DWKN7TgYhSIlu9tvZIpXHxt1FA750tLLDziQb4e/XBplywd0V2VKK4gRjKMdZ5FsIB8sAKm0sjhCfsy88Z4LnTPCcCZ4zwXMm+J/OBM//IT37xeuzX7z+q34R5+qOUy3O1oH+gJKdJ75Kad6HdI5s5ZyNwqVxTrUYmO2UpcLE47C5z3zoHTxKhvYcgFCxttVrB6pASytZzALI6Y7c7wAv7ubksofIye5zsPDbZZxwmnq8golL2DLGWcw0I2eFznO6Tr3dDVjgieDNfEkyjV05RED/omq2pBTK0oDsDibZUBDGHmLkO3ru4LjqLsv+9wOnwd0LEA2GmX2kN2TY2L2U/+eAQoFXRh6e88lG2SBSOUxKGuw8LlhjH8UgpPNBYaCYygOMYMQni/qeZdse46JxYJBIJW/Qm0vD+PET0h5vKA==","PK":"eJylVkuOHTcQu8rgrb2Q1PrmELlAEAzsYHbeTRIgMHz3iCxS3XsvXs+0WipVsUhKP16/v357+/F6f//r+9fPz/f3/fb69t/fH5+vL2979N+v3//54OgfdX55a/jl/Sv67fec236kut+u/U/JeOt4LL3O/c/cI33/HS3mVXxMWF4KYqTz2B/b/qcOj6S9ZMwIMffktQfXXt64L7Lo8VMoPioe+Tx2sLEDz6xv46xHznlpDoeQ8kCQsjcamDwcokX5rI84XC59z58jsubalB8B2ojMWRwjMa2F4eR5PeqO9GoMzCt2rwfKHDCySszoAKbFpsCZOBCU7GYgILBDIGIouNaMrIaLQC7IqRVlOWegLYBOM1bsxU8J1SROQrx6ZqOPVU3GFsiU2Z02Y6QqKYZAQZWU6g6DClAKCFCv2HdMJ50DIiQ81iMqUZma0Q1LVm1RUg8WRRFLPB6mDDpgPKOhTVCiKExDfCBG9Hs0OWYm0w7Y9B6BWA6KGykqiSyG+km+YOU0ihQHY7HxPQjGmGsI7qivKRCiEsKhuVi41mG50BrZLLYAxvQbVlSBx9GSRHfuCZz6OAGbNIcMABRoinohi2k5oYR+i9lh2q1QaRF8ZLbYc15KiZk0rYxFLdpYpUgiAXJTNcdSkm2JxGvWTQt4iWeKiGQK+b4kquWeJVPHeM2mBOs41fTIg31AaVMdpuT5dTpEOJR4Nc1DWcJ8oDxlUtQyNkVAaoNfi6jK6EmSvB1Gjjm6vaqoKWJRiOzub1EiKIEOcClX+o1+bf75cx8KH796YIyDblHyymyoF8iwz8OY8mzbaUh3C0qgD+nBP0NNilAvRakynyFpk5VrPGnIQCVGuiMH0SnO3G8vHm41gxNmWAO3SxL8OgRKIfZo5wqis1HBi+qEx23B/FwPYVNUT9Xmch8387i9eYWQiD98iPGgkSWypeRBcuVLa5EXKTaclsKjQVCPEbxNVzuMc/rmCNylNR62ybYsrV9CKXhnmgX3tUNTpbwuVE1rpxmxUockj9Ac5dJU14nYn/gW++g43XXKITkbkaR4wiB/XhaGjbZaUzkkR7MuakgXT+k3OjrCBXvECRPKPimlckytvhv4nAZv8D9q6pJFWFURMDyolg9DP27MLtN6KpNsDym+YLnVtgsydzwvBUPObA7WaD+NMHezWeLpIn7VxaXZgcILZ3SLiWWd4myd6e8bpBkb/r6US/V5ffrmO8e5c6EOKvhcSp1zerCj+X6KPH0tvQ+porYOl3ZERyLdYjNXUEfzMRzCl3T6ephWkmkt85L1QhPmcZwoJKpcK47kc+7KR4YB082SJ1d2RsW3n2QDuWL6EI2sAlJMxc7bjIShro+ac9qRHB6VPw+Hn/8Dhqo9zg=="}} 2 | -------------------------------------------------------------------------------- /examples/bob_pri_key.json: -------------------------------------------------------------------------------- 1 | {"Bob":{"SK":"eJztWEGOIzcM/Irh8xwktSRSeUQ+ECyMTbJAAuwhwCQBFov5e0Syit2+BcgxPrTHbkkUWSwWpfl+/+O33x8/3n+4fb8/Hr98/fz+/njsX/efv/355f3+dttv//789a8v/vanrm+3YU/dT8Ozf9c6325S9o9j/x1vt37Yy75f7IEp++V+aqv40D0izabYR9kL57YyB+eUFmZq3XZUwkwtZrQVe13wzZYtM79XSbc5i19sednL1PazqTP8djN9T9O9Vt1ux04+v9Ztrwv3s0HzYAnGPZK6zIEWGyt/uN9zInQtxGA/a8XfWj2svbWYCwPYjRKm5oJPtYalSUfGiFGDzZa5MfPHXa0JnW9oO5dKU7CpnGPJMbtD4Lc5JxMDI9Jj3820ZdVclQSjhykfPBLpCqfNT7MlGlPNtg+4H8YP5VTf28AzGtl+tk4FWXQ2lIaQfANzWpncQAYpsHwGGgtvDX3zZRzgixQguRh2JLiSnf5lBdfcRyOYMV4UTDX6yARZBKBFmiuyWgt5YglSJefaxcelQCOrJFlkjg6hsz12MYctjMHyWYU4lSuUQpwi3pn4jQsj3XKl7y3CdQJohG1WwtUSmXEsymBRdCwb4RysA23PHBLWIxQLchXg6/DMZP0RfKaUTN9WUylaEHdmTU94omDvJGadkA6Uhj7JhG+rB4AeEUFUoTzpjiIpBUxW6EvMnwjZZeW4UrAETIOmC434h4WfATiBKywYpLbIKOH+HWCsuRPMYQzamXSJzcxtIbBKAAI1hhe0LYGHi15/UjgWt2K+LbSRhQL0p8Yz9NPHbgi//tdm4ahZBQ3qrrSL6gWXeiCmcqbU/074tAgi6iNkZlGOKnpD8LGQcCE91HwDb7FCnbPxgZJ3ZZIUOAXahm/QbXDMWxoyN1n//tbsLFYcdp7X3hcRw+Ri1SedF97KPLXT2oIq6/KI3GoqLDqxoHOeLdaLm9MWSOScqOTFkYjVSwP2SAeauaL8DF1JYBQ+u3BrzOz4vkA7m+QFAinLipho4J6wdlKXebLFUQsCrlS2hx6BuiDyhTenBUThqXE6k6anKAq5MrmrZw0qbCst1kCCSKUc0P+FIFPldJ6Z8gYCibfHiRpNgqmPj+hIgmK0L1n/HULlua3IReJUqB3CUwG6STaxSH8L037uwBEoBQxIUDpiUUOueD6ZyaYVuwnlF1lrJ/2gRTWg13qp9gG2D7LHtpx5aCyXTjl5xnDP0BcHBb0fp1A4FIOwdp4fWMsBbLYPEH7grDQYvDPQFUnRvDt8jEJbKe2DeBQcQGl7naklpbM5RrKvvgWDx4VRXqEGsMVgI8EqdMfArJyHlND9ClRCTeRKChzvVE4h9tof6JEllTQVJF8X8NWrSXhwoQs4fcCZiCtbxeuO8LojvO4IrzvC647wf7wjvP6h9GoWr2bx75qF4mA5GOuB+rWZCn1x0UXSggYcaDEQh1xqX0c3CDoknA1VIDgre/UdEFDFWnnirV8zCjYTXl3LuiS8XOnFi4Is9jA0Hb+1zlNh/XibQHfiukDmBWaSKbzyDFyvhN0nyh+q7tc99CrFVcHtFv6XYaEyY7fJa2v234NmqTUGZTLD64XsT5mCNnc0MuFJuWW7KjxsK9nXeCPjvdbfWBMIfuOypoNSRV2L2s1LWsXdyf8HUthFy9k5ul7KLdVReOctjQV/8G7K+NhoLb6ZDbdA9XgPpQ51NMmR94GsiuebwaePj38ARKhtiQ==","PK":"eJylVkuOHTcMvMrDW89CUksilUPkAkEwsIPZeTdJgMDw3aMiq/Taay96pl9L4qdYLOr78/fnb4/vz/f3v759+fx8f9+/nl//+/vj8/n22F///fLtn4/4+kf3t8fAU/fT+Ozftc63h5X949r/x9ujX/jY94e9MG1/3E9tlX98r1jDFvwp++DcVubQntLSTK3bjluaqQVGW8HnwjccWzC/T1nHnqUXHC/7mMMfts6MO8z0vc33WQ+7nZ5if63bXjf5wyIiWMb1yKQuBNDSsetHxD0nU/ciDPazVv6vNdLarg0hDGI3SpqaizHVmpamAhkjVwEbjoUxxBOh1gNdOITnUmWKNl17UBzYHca4EZxNLowsD95hGlVFqHbA6GkqFq+DdGXQiBO2zHMrbMdCxAF+uLaGb4AHGsEfzrmxisGG0phSOEDQruImMiwB6ploLH4F+ohlXOSLFSK5lHYWuIqd8bKSaxEjCAbGm5OpoI9fjFm5BgSWO4FL0KrmAjYkDbTQciFMBtsKoQxkhkpZBA+6AJsHPcS2mcSPs/YTb0fjZziLMjTBqYKXO72CdzPzXkoT/YPFIM31AvgFdBeui2ReZKaYAnaGOFiascU+z/ZfCQ0qAUc4HfWigkRhjOSIzkxvMzFIdApJk2alNYDyMCP6Rew/MjUyVewM0hlTbzwRBqNqxcU+UMHJtah2fFlF/G4k/JBUSdeyd9sRrpbERuaLFoKdznbrfmu3o45G/cqkjaCE66L8FgNGfsGOVFKqHgK/61DgNAi52JNdgaLOms/wP3/sIfDxywOiEGlTRdONKWjSLDqgSN2dKJlKkH+OKGANJ8JwTyan9q273nBGpAo4SS86vBBaiXNno0QP+6mCJSMnh4NNfoSxkMRLftutnFqdZHjsrKc4RjLbT2yLFGIq3HN0aiNaF3y1qjHLUqamMMbc2u/8hdmcYj1ZAnA66Rmyv8g/WV2U4U7F6urC5Bfb5OSDqIbk2dTfaq3wJtS11ehhsUadohnDP1rMb1TJHq4Mym6yH3LHe8B6EYVBYdvQ2HYNhHxhH0UAL050OSMRUhOknKacsvtO0wvpabqEyEZOfI6ORT1/qY46miPhdEXXmpTzda0Z6ouQFBcje5qddjDg5E9ddVaYXT/UkeEyKNeEKmddVGclg4/PIkDzytE4/ThM4nZ3nUS6kBVh48u5ZHVunAemSjQiSpGE1wQNFhDEyQDj3TEG2kyhTsGhdC6N4KWx61TuMNVONTm2/Uj4q/5OGUeEr16vZNfkQAk7SHLpNtCYeRgf1GZEudTlQT8JFoIZqvGinJs07tKxi66cCjH9RNzPmxRDQyMG8ZEqtQGvuRziUXLNWN28F5XUFOV9PPz4H0ucO0w="}} 2 | -------------------------------------------------------------------------------- /lib/app/bftx_logger/bftx_logger.go: -------------------------------------------------------------------------------- 1 | package bftx_logger 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "time" 7 | ) 8 | 9 | // simpleLogger writes errors and the function name that generated the error to bftx.log 10 | func SimpleLogger(funcName string, currentError error) { 11 | // If the file doesn't exist, create it, or append to the file 12 | f, err := os.OpenFile(os.Getenv("GOPATH")+"/src/github.com/blockfreight/go-bftx/logs/bftx.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | if _, err := f.Write([]byte(time.Now().Format("2006/01/02 15:04") + ", " + funcName + ", " + currentError.Error() + "\n\n")); err != nil { 17 | log.Fatal(err) 18 | } 19 | if err := f.Close(); err != nil { 20 | log.Fatal(err) 21 | } 22 | } 23 | 24 | // queryLogger writes errors, the function name that generated the error, and the transaction body to bftx.log for cmdQuery only 25 | func StringLoggerString(text string) { 26 | // If the file doesn't exist, create it, or append to the file 27 | f, err := os.OpenFile(os.Getenv("GOPATH")+"/src/github.com/blockfreight/go-bftx/logs/bftx.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | if _, err := f.Write([]byte(time.Now().Format("2006/01/02 15:04") + ", " + text + "\n\n")); err != nil { 32 | log.Fatal(err) 33 | } 34 | if err := f.Close(); err != nil { 35 | log.Fatal(err) 36 | } 37 | } 38 | 39 | // queryLogger writes errors, the function name that generated the error, and the transaction body to bftx.log for cmdQuery only 40 | func StringLogger(funcName string, currentError string, id string) { 41 | // If the file doesn't exist, create it, or append to the file 42 | f, err := os.OpenFile(os.Getenv("GOPATH")+"/src/github.com/blockfreight/go-bftx/logs/bftx.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 43 | if err != nil { 44 | log.Fatal(err) 45 | } 46 | if _, err := f.Write([]byte(time.Now().Format("2006/01/02 15:04") + ", " + funcName + ", " + currentError + ", " + id + "\n\n")); err != nil { 47 | log.Fatal(err) 48 | } 49 | if err := f.Close(); err != nil { 50 | log.Fatal(err) 51 | } 52 | } 53 | 54 | // transLogger writes errors, the function name that generated the error, and the transaction body to bftx.log 55 | func TransLogger(funcName string, currentError error, id string) { 56 | // If the file doesn't exist, create it, or append to the file 57 | f, err := os.OpenFile(os.Getenv("GOPATH")+"/src/github.com/blockfreight/go-bftx/logs/bftx.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | if _, err := f.Write([]byte(time.Now().Format("2006/01/02 15:04") + ", " + funcName + ", " + currentError.Error() + ", " + id + "\n\n")); err != nil { 62 | log.Fatal(err) 63 | } 64 | if err := f.Close(); err != nil { 65 | log.Fatal(err) 66 | } 67 | } 68 | 69 | // apiListener writes the time and transaction ID generated by ConstructBfTx api calls to api.log 70 | func ApiListener(id string) { 71 | // If the file doesn't exist, create it, or append to the file 72 | f, err := os.OpenFile(os.Getenv("GOPATH")+"/src/github.com/blockfreight/go-bftx/logs/transaction_id.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 73 | if err != nil { 74 | log.Fatal(err) 75 | } 76 | if _, err := f.Write([]byte(time.Now().Format("2006/01/02 15:04") + ", " + id + "\n\n")); err != nil { 77 | log.Fatal(err) 78 | } 79 | if err := f.Close(); err != nil { 80 | log.Fatal(err) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /api/graphqlObj/consol.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // ConsolInput object for GraphQL integration 6 | var ConsolInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "Consol", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "Masterbill": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "ContainerMode": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | "PaymentMethod": &graphql.InputObjectFieldConfig{ 17 | Type: graphql.String, 18 | }, 19 | "PortOfDischarge": &graphql.InputObjectFieldConfig{ 20 | Type: graphql.String, 21 | }, 22 | "PortOfLoading": &graphql.InputObjectFieldConfig{ 23 | Type: graphql.String, 24 | }, 25 | "ShipmentType": &graphql.InputObjectFieldConfig{ 26 | Type: graphql.String, 27 | }, 28 | "TransportMode": &graphql.InputObjectFieldConfig{ 29 | Type: graphql.String, 30 | }, 31 | "VesselName": &graphql.InputObjectFieldConfig{ 32 | Type: graphql.String, 33 | }, 34 | "VoyageFlightNo": &graphql.InputObjectFieldConfig{ 35 | Type: graphql.String, 36 | }, 37 | "EstimatedTimeOfDeparture": &graphql.InputObjectFieldConfig{ 38 | Type: graphql.String, 39 | }, 40 | "EstimatedTimeOfArrival": &graphql.InputObjectFieldConfig{ 41 | Type: graphql.String, 42 | }, 43 | "Carrier": &graphql.InputObjectFieldConfig{ 44 | Type: graphql.String, 45 | }, 46 | "ContainerNumber": &graphql.InputObjectFieldConfig{ 47 | Type: graphql.String, 48 | }, 49 | "ContainerType": &graphql.InputObjectFieldConfig{ 50 | Type: graphql.String, 51 | }, 52 | "DeliveryMode": &graphql.InputObjectFieldConfig{ 53 | Type: graphql.String, 54 | }, 55 | "Seal": &graphql.InputObjectFieldConfig{ 56 | Type: graphql.String, 57 | }, 58 | }, 59 | }, 60 | ) 61 | 62 | // Consol object for GraphQL integration 63 | var Consol = graphql.NewObject( 64 | graphql.ObjectConfig{ 65 | Name: "Consol", 66 | Fields: graphql.Fields{ 67 | "Masterbill": &graphql.Field{ 68 | Type: graphql.String, 69 | }, 70 | "ContainerMode": &graphql.Field{ 71 | Type: graphql.String, 72 | }, 73 | "PaymentMethod": &graphql.Field{ 74 | Type: graphql.String, 75 | }, 76 | "PortOfDischarge": &graphql.Field{ 77 | Type: graphql.String, 78 | }, 79 | "PortOfLoading": &graphql.Field{ 80 | Type: graphql.String, 81 | }, 82 | "ShipmentType": &graphql.Field{ 83 | Type: graphql.String, 84 | }, 85 | "TransportMode": &graphql.Field{ 86 | Type: graphql.String, 87 | }, 88 | "VesselName": &graphql.Field{ 89 | Type: graphql.String, 90 | }, 91 | "VoyageFlightNo": &graphql.Field{ 92 | Type: graphql.String, 93 | }, 94 | "EstimatedTimeOfDeparture": &graphql.Field{ 95 | Type: graphql.String, 96 | }, 97 | "EstimatedTimeOfArrival": &graphql.Field{ 98 | Type: graphql.String, 99 | }, 100 | "Carrier": &graphql.Field{ 101 | Type: graphql.String, 102 | }, 103 | "ContainerNumber": &graphql.Field{ 104 | Type: graphql.String, 105 | }, 106 | "ContainerType": &graphql.Field{ 107 | Type: graphql.String, 108 | }, 109 | "DeliveryMode": &graphql.Field{ 110 | Type: graphql.String, 111 | }, 112 | "Seal": &graphql.Field{ 113 | Type: graphql.String, 114 | }, 115 | }, 116 | }, 117 | ) 118 | -------------------------------------------------------------------------------- /lib/pkg/saberservice/saber.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package saberservice; 4 | 5 | // service, encrypt a plain text into a cypertext using saber 6 | service BFSaberService { 7 | // request a service of encryption 8 | rpc BFTX_Encode(BFTX_Encode_request) returns (BFTX_transaction) {}; 9 | // request a service for decryption 10 | rpc BFTX_Decode(BFTX_Decode_request) returns (BFTX_transaction) {} 11 | } 12 | 13 | // The BFTX encryption transaction data structure (test version) 14 | message BFTX_Encode_request{ 15 | BFTX_transaction bftxtrans = 1; 16 | BFTX_encryptionConfig bftxconfig = 2; 17 | } 18 | // The BFTX decryption transaction data structure (test version) 19 | message BFTX_Decode_request{ 20 | BFTX_transaction bftxtrans = 1; 21 | string KeyName = 2; 22 | } 23 | 24 | message BFTX_transaction { 25 | BFTX_Payload Properties = 1; 26 | string Id = 2; 27 | SignKey PrivateKey = 3; 28 | string Signhash = 4; 29 | string Signature = 5; 30 | bool Verified = 6; 31 | bool Transmitted = 7; 32 | string Amendment = 8; 33 | string Private = 9; 34 | } 35 | 36 | message SignKey{ 37 | string Curve = 1; 38 | string X = 2; 39 | string Y = 3; 40 | string D = 4; 41 | } 42 | 43 | message BFTX_Payload{ 44 | string Shipper = 1; 45 | string BolNum = 2; 46 | string RefNum = 3; 47 | string Vessel = 4; 48 | string PortOfLoading = 5; 49 | string PortOfDischarge = 6; 50 | string UnitOfVolume = 7; 51 | string NotifyAddress = 8; 52 | string DescOfGoods = 9; 53 | string GrossWeight = 10; 54 | string FreightPayableAmt = 11; 55 | string FreightAdvAmt = 12; 56 | string GeneralInstructions = 13; 57 | string DateShipped = 14; 58 | ISSUEDETAILS IssueDetails = 15; 59 | string NumBol = 16; 60 | MASTERINFO MasterInfo = 17; 61 | AGENTFORMASTER AgentForMaster = 18; 62 | AGENTFOROWNER AgentForOwner = 19; 63 | string EncryptionMetaData = 20; 64 | string Consignee = 21; 65 | string HouseBill = 22; 66 | string ReceiveAgent = 23; 67 | string Destination = 24; 68 | string MarksAndNumbers = 25; 69 | string UnitOfWeight = 26; 70 | string Volume =27; 71 | string Container =28; 72 | string ContainerSeal =29; 73 | string Packages = 30; 74 | string PackType = 31; 75 | string INCOTerms = 32; 76 | string DeliverAgent = 33; 77 | string ContainerMode = 34; 78 | string ContainerType = 35; 79 | } 80 | 81 | message ISSUEDETAILS{ 82 | string PlaceOfIssue = 1; 83 | string DateOfIssue = 2; 84 | } 85 | 86 | message MASTERINFO{ 87 | string FirstName = 1; 88 | string LastName = 2; 89 | string Sig = 3; 90 | } 91 | 92 | message AGENTFORMASTER{ 93 | string FirstName = 1; 94 | string LastName = 2; 95 | string Sig = 3; 96 | } 97 | 98 | message AGENTFOROWNER{ 99 | string FirstName = 1; 100 | string LastName = 2; 101 | string Sig = 3; 102 | string ConditionsForCarriage = 4; 103 | } 104 | 105 | message BFTX_encryptionConfig{ 106 | string version = 1; 107 | string group = 2; 108 | repeated string recipients = 3; 109 | repeated ENCRYPTIONFIELD encryptionfields = 4; 110 | repeated PUBLICKEYS publickeys = 5; 111 | 112 | } 113 | 114 | message ENCRYPTIONFIELD{ 115 | string fieldname = 1; 116 | repeated string authorizeduser= 2; 117 | } 118 | 119 | message PUBLICKEYS{ 120 | string userid = 1; 121 | string keyfile = 2; 122 | } 123 | -------------------------------------------------------------------------------- /lib/pkg/saberservice/saberservice_test.go: -------------------------------------------------------------------------------- 1 | package saberservice 2 | 3 | import ( 4 | "encoding/json" 5 | "io" 6 | "io/ioutil" 7 | "os" 8 | "testing" 9 | 10 | "gopkg.in/yaml.v2" 11 | ) 12 | 13 | // TestLoadtransaction is the unit test of loadtransaction 14 | func TestLoadtransaction(t *testing.T) { 15 | var tx *BFTXTransaction 16 | _gopath := os.Getenv("GOPATH") 17 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 18 | txpath := "/examples/bftx.json" 19 | b, err := ioutil.ReadFile(_gopath + _bftxpath + txpath) 20 | 21 | err = json.Unmarshal(b, &tx) 22 | if err != nil { 23 | t.Errorf("%s", b) 24 | t.Errorf("the file %s cannot be unmarshaled.\n %v", _gopath+_bftxpath+txpath, err) 25 | } 26 | } 27 | 28 | // Unit test of the loadconfiguration funtion 29 | func TestLoadconfiguration(t *testing.T) { 30 | var tx *BFTXEncryptionConfig 31 | 32 | _gopath := os.Getenv("GOPATH") 33 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 34 | // txpath := "/examples/bftx.json" 35 | txpath := "/examples/config.yaml" 36 | b, err := ioutil.ReadFile(txpath) 37 | err = yaml.UnmarshalStrict(b, &tx) 38 | if err != nil { 39 | t.Errorf("%s", b) 40 | t.Errorf("================\n") 41 | t.Errorf("yaml file %s cannot be unmarshaled.\n %v", _gopath+_bftxpath+txpath, err) 42 | } 43 | } 44 | 45 | func TestSaberinputcli(t *testing.T) { 46 | var st, st2 Saberinput 47 | _gopath := os.Getenv("GOPATH") 48 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 49 | st.mode = "test" 50 | st.address = "localhost:22222" 51 | st.txpath = _gopath + _bftxpath + "/examples/bftx.json" 52 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 53 | st.KeyName = "./Data/carol_pri_key.json" 54 | 55 | st2.mode = "mm" 56 | st2.address = "add" 57 | st2.txpath = "path" 58 | st2.txconfigpath = "configpath" 59 | 60 | in, err := ioutil.TempFile("", "") 61 | check(err) 62 | defer in.Close() 63 | 64 | _, err = io.WriteString(in, "t\n") 65 | check(err) 66 | 67 | _, err = in.Seek(0, 0) 68 | r := Saberinputcli(in) 69 | if r != st { 70 | t.Errorf("result unmatch, %s,%s", st, r) 71 | } 72 | 73 | in, err = ioutil.TempFile("", "") 74 | check(err) 75 | 76 | _, err = io.WriteString(in, "mm\nadd\npath\nconfigpath\n") 77 | check(err) 78 | _, err = in.Seek(0, 0) 79 | r2 := Saberinputcli(in) 80 | if r2 != st2 { 81 | t.Errorf("result unmatch, %s,%s", st2, r2) 82 | } 83 | 84 | } 85 | 86 | func TestSaberEncoding(t *testing.T) { 87 | var st Saberinput 88 | 89 | _gopath := os.Getenv("GOPATH") 90 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 91 | 92 | st.mode = "test" 93 | st.address = "localhost:22222" 94 | st.txpath = _gopath + _bftxpath + "/examples/bftx.json" 95 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 96 | 97 | encr, err := SaberEncoding(st) 98 | if err != nil { 99 | t.Errorf("error: %v", err) 100 | t.Errorf("Returned message: %v", encr) 101 | } 102 | } 103 | 104 | func TestSaberDecoding(t *testing.T) { 105 | var st Saberinput 106 | 107 | _gopath := os.Getenv("GOPATH") 108 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 109 | 110 | st.mode = "test" 111 | st.address = "localhost:22222" 112 | st.txpath = _gopath + _bftxpath + "/examples/bftx.json" 113 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 114 | st.KeyName = _gopath + _bftxpath + "/examples/carol_pri_key.json" 115 | 116 | encr, err := SaberEncoding(st) 117 | if err != nil { 118 | t.Errorf("error: %v", err) 119 | t.Errorf("Returned message: %v", encr) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /blockfreight.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/blockfreight.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | package blockfreight 46 | 47 | // This file is only to make "go get" working 48 | 49 | import ( 50 | 51 | // ====================== 52 | // Blockfreight™ packages 53 | // ====================== 54 | 55 | // Defines the current version of the project. 56 | 57 | "github.com/blockfreight/go-bftx/build/package/version" // Defines the current version of the project. 58 | ) 59 | 60 | // const version = "0.8.1" 61 | -------------------------------------------------------------------------------- /api/graphqlObj/shipment.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // ShipmentInput object for GraphQL integration 6 | var ShipmentInput = graphql.NewInputObject( 7 | graphql.InputObjectConfig{ 8 | Name: "MasterInfo", 9 | Fields: graphql.InputObjectConfigFieldMap{ 10 | "Housebill": &graphql.InputObjectFieldConfig{ 11 | Type: graphql.String, 12 | }, 13 | "ContainerMode": &graphql.InputObjectFieldConfig{ 14 | Type: graphql.String, 15 | }, 16 | "GoodsDescription": &graphql.InputObjectFieldConfig{ 17 | Type: graphql.String, 18 | }, 19 | "MarksAndNumbers": &graphql.InputObjectFieldConfig{ 20 | Type: graphql.String, 21 | }, 22 | "HBLAWBChargesDisplay": &graphql.InputObjectFieldConfig{ 23 | Type: graphql.String, 24 | }, 25 | "PackQuantity": &graphql.InputObjectFieldConfig{ 26 | Type: graphql.String, 27 | }, 28 | "PackType": &graphql.InputObjectFieldConfig{ 29 | Type: graphql.String, 30 | }, 31 | "Weight": &graphql.InputObjectFieldConfig{ 32 | Type: graphql.String, 33 | }, 34 | "Volume": &graphql.InputObjectFieldConfig{ 35 | Type: graphql.String, 36 | }, 37 | "ShippedOnBoard": &graphql.InputObjectFieldConfig{ 38 | Type: graphql.String, 39 | }, 40 | "TransportMode": &graphql.InputObjectFieldConfig{ 41 | Type: graphql.String, 42 | }, 43 | "EstimatedTimeOfDeparture": &graphql.InputObjectFieldConfig{ 44 | Type: graphql.String, 45 | }, 46 | "EstimatedTimeOfArrival": &graphql.InputObjectFieldConfig{ 47 | Type: graphql.String, 48 | }, 49 | "Consignee": &graphql.InputObjectFieldConfig{ 50 | Type: graphql.String, 51 | }, 52 | "Consignor": &graphql.InputObjectFieldConfig{ 53 | Type: graphql.String, 54 | }, 55 | "PackingLineCommodity": &graphql.InputObjectFieldConfig{ 56 | Type: graphql.String, 57 | }, 58 | "ContainerNumber": &graphql.InputObjectFieldConfig{ 59 | Type: graphql.String, 60 | }, 61 | "INCOTERM": &graphql.InputObjectFieldConfig{ 62 | Type: graphql.String, 63 | }, 64 | "ShipmentType": &graphql.InputObjectFieldConfig{ 65 | Type: graphql.String, 66 | }, 67 | "ReleaseType": &graphql.InputObjectFieldConfig{ 68 | Type: graphql.String, 69 | }, 70 | }, 71 | }, 72 | ) 73 | 74 | // MasterInfo object for GraphQL integration 75 | var Shipment = graphql.NewObject( 76 | graphql.ObjectConfig{ 77 | Name: "MasterInfo", 78 | Fields: graphql.Fields{ 79 | "Housebill": &graphql.Field{ 80 | Type: graphql.String, 81 | }, 82 | "ContainerMode": &graphql.Field{ 83 | Type: graphql.String, 84 | }, 85 | "GoodsDescription": &graphql.Field{ 86 | Type: graphql.String, 87 | }, 88 | "MarksAndNumbers": &graphql.Field{ 89 | Type: graphql.String, 90 | }, 91 | "HBLAWBChargesDisplay": &graphql.Field{ 92 | Type: graphql.String, 93 | }, 94 | "PackQuantity": &graphql.Field{ 95 | Type: graphql.String, 96 | }, 97 | "PackType": &graphql.Field{ 98 | Type: graphql.String, 99 | }, 100 | "Weight": &graphql.Field{ 101 | Type: graphql.String, 102 | }, 103 | "Volume": &graphql.Field{ 104 | Type: graphql.String, 105 | }, 106 | "ShippedOnBoard": &graphql.Field{ 107 | Type: graphql.String, 108 | }, 109 | "TransportMode": &graphql.Field{ 110 | Type: graphql.String, 111 | }, 112 | "EstimatedTimeOfDeparture": &graphql.Field{ 113 | Type: graphql.String, 114 | }, 115 | "EstimatedTimeOfArrival": &graphql.Field{ 116 | Type: graphql.String, 117 | }, 118 | "Consignee": &graphql.Field{ 119 | Type: graphql.String, 120 | }, 121 | "Consignor": &graphql.Field{ 122 | Type: graphql.String, 123 | }, 124 | "PackingLineCommodity": &graphql.Field{ 125 | Type: graphql.String, 126 | }, 127 | "ContainerNumber": &graphql.Field{ 128 | Type: graphql.String, 129 | }, 130 | "INCOTERM": &graphql.Field{ 131 | Type: graphql.String, 132 | }, 133 | "ShipmentType": &graphql.Field{ 134 | Type: graphql.String, 135 | }, 136 | "ReleaseType": &graphql.Field{ 137 | Type: graphql.String, 138 | }, 139 | }, 140 | }, 141 | ) 142 | -------------------------------------------------------------------------------- /api/graphqlObj/properties.go: -------------------------------------------------------------------------------- 1 | package graphqlObj 2 | 3 | import "github.com/graphql-go/graphql" 4 | 5 | // PropertiesType object for GraphQL integration 6 | var PropertiesType = graphql.NewObject( 7 | graphql.ObjectConfig{ 8 | Name: "Properties", 9 | Fields: graphql.Fields{ 10 | "Consol": &graphql.Field{ 11 | Type: Consol, 12 | }, 13 | "Shipment": &graphql.Field{ 14 | Type: Shipment, 15 | }, 16 | "Extension": &graphql.Field{ 17 | Type: Extension, 18 | }, 19 | "Shipper": &graphql.Field{ 20 | Type: graphql.String, 21 | }, 22 | "BolNum": &graphql.Field{ 23 | Type: graphql.String, 24 | }, 25 | "NumBol": &graphql.Field{ 26 | Type: graphql.String, 27 | }, 28 | "RefNum": &graphql.Field{ 29 | Type: graphql.String, 30 | }, 31 | "Consignee": &graphql.Field{ 32 | Type: graphql.String, 33 | }, 34 | "Vessel": &graphql.Field{ 35 | Type: graphql.String, 36 | }, 37 | "PortOfLoading": &graphql.Field{ 38 | Type: graphql.String, 39 | }, 40 | "PortOfDischarge": &graphql.Field{ 41 | Type: graphql.String, 42 | }, 43 | "NotifyAddress": &graphql.Field{ 44 | Type: graphql.String, 45 | }, 46 | "DescOfGoods": &graphql.Field{ 47 | Type: graphql.String, 48 | }, 49 | "GrossWeight": &graphql.Field{ 50 | Type: graphql.String, 51 | }, 52 | "FreightPayableAmt": &graphql.Field{ 53 | Type: graphql.String, 54 | }, 55 | "FreightAdvAmt": &graphql.Field{ 56 | Type: graphql.String, 57 | }, 58 | "GeneralInstructions": &graphql.Field{ 59 | Type: graphql.String, 60 | }, 61 | "DateShipped": &graphql.Field{ 62 | Type: graphql.String, 63 | }, 64 | "IssueDetails": &graphql.Field{ 65 | Type: IssueDetails, 66 | }, 67 | "MasterInfo": &graphql.Field{ 68 | Type: MasterInfo, 69 | }, 70 | "AgentForMaster": &graphql.Field{ 71 | Type: AgentForMaster, 72 | }, 73 | "AgentForOwner": &graphql.Field{ 74 | Type: AgentForOwner, 75 | }, 76 | }, 77 | }, 78 | ) 79 | 80 | // PropertiesInput object for GraphQL integration 81 | var PropertiesInput = graphql.NewInputObject( 82 | graphql.InputObjectConfig{ 83 | Name: "Properties", 84 | Fields: graphql.InputObjectConfigFieldMap{ 85 | "Consol": &graphql.InputObjectFieldConfig{ 86 | Type: ConsolInput, 87 | }, 88 | "Shipment": &graphql.InputObjectFieldConfig{ 89 | Type: ShipmentInput, 90 | }, 91 | "Extension": &graphql.InputObjectFieldConfig{ 92 | Type: ExtensionInput, 93 | }, 94 | "Shipper": &graphql.InputObjectFieldConfig{ 95 | Type: graphql.String, 96 | }, 97 | "BolNum": &graphql.InputObjectFieldConfig{ 98 | Type: graphql.String, 99 | }, 100 | "NumBol": &graphql.InputObjectFieldConfig{ 101 | Type: graphql.String, 102 | }, 103 | "RefNum": &graphql.InputObjectFieldConfig{ 104 | Type: graphql.String, 105 | }, 106 | "Consignee": &graphql.InputObjectFieldConfig{ 107 | Type: graphql.String, 108 | }, 109 | "Vessel": &graphql.InputObjectFieldConfig{ 110 | Type: graphql.String, 111 | }, 112 | "PortOfLoading": &graphql.InputObjectFieldConfig{ 113 | Type: graphql.String, 114 | }, 115 | "PortOfDischarge": &graphql.InputObjectFieldConfig{ 116 | Type: graphql.String, 117 | }, 118 | "NotifyAddress": &graphql.InputObjectFieldConfig{ 119 | Type: graphql.String, 120 | }, 121 | "DescOfGoods": &graphql.InputObjectFieldConfig{ 122 | Type: graphql.String, 123 | }, 124 | "GrossWeight": &graphql.InputObjectFieldConfig{ 125 | Type: graphql.String, 126 | }, 127 | "FreightPayableAmt": &graphql.InputObjectFieldConfig{ 128 | Type: graphql.String, 129 | }, 130 | "FreightAdvAmt": &graphql.InputObjectFieldConfig{ 131 | Type: graphql.String, 132 | }, 133 | "GeneralInstructions": &graphql.InputObjectFieldConfig{ 134 | Type: graphql.String, 135 | }, 136 | "DateShipped": &graphql.InputObjectFieldConfig{ 137 | Type: graphql.String, 138 | }, 139 | "IssueDetails": &graphql.InputObjectFieldConfig{ 140 | Type: IssueDetailsInput, 141 | }, 142 | "MasterInfo": &graphql.InputObjectFieldConfig{ 143 | Type: MasterInfoInput, 144 | }, 145 | "AgentForMaster": &graphql.InputObjectFieldConfig{ 146 | Type: AgentForMasterInput, 147 | }, 148 | "AgentForOwner": &graphql.InputObjectFieldConfig{ 149 | Type: AgentForOwnerInput, 150 | }, 151 | }, 152 | }, 153 | ) 154 | -------------------------------------------------------------------------------- /lib/pkg/crypto/crypto.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | /* 5 | Package helloworld is a generated protocol buffer package. 6 | 7 | It is generated from these files: 8 | helloworld.proto 9 | 10 | It has these top-level messages: 11 | HelloRequest 12 | HelloReply 13 | */ 14 | package crypto 15 | 16 | import ( 17 | fmt "fmt" 18 | "log" 19 | 20 | proto "github.com/golang/protobuf/proto" 21 | 22 | math "math" 23 | 24 | context "golang.org/x/net/context" 25 | 26 | grpc "google.golang.org/grpc" 27 | ) 28 | 29 | // Reference imports to suppress errors if they are not otherwise used. 30 | var _ = proto.Marshal 31 | var _ = fmt.Errorf 32 | var _ = math.Inf 33 | 34 | // This is a compile-time assertion to ensure that this generated file 35 | // is compatible with the proto package it is being compiled against. 36 | // A compilation error at this line likely means your copy of the 37 | // proto package needs to be updated. 38 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 39 | 40 | type BFTX_Payload struct { 41 | Shipper string 42 | BolNum int 43 | RefNum int 44 | Consignee string 45 | Vessel int 46 | PortOfLoading int 47 | PortOfDischarge int 48 | NotifyAddress string 49 | DescOfGoods string 50 | GrossWeight int 51 | FreightPayableAmt int 52 | FreightAdvAmt int 53 | GeneralInstructions string 54 | DateShipped string 55 | NumBol int 56 | ISSUEDETAILS IssueDetails 57 | 58 | MASTERINFO MasterInfo 59 | 60 | AGENTFORMASTER AgentForMaster 61 | 62 | AGENTFOROWNER AgentForOwner 63 | EncryptionMetaData string 64 | } 65 | 66 | type EncryptionField struct { 67 | FieldName string 68 | AuthorizedUser string 69 | } 70 | 71 | type Publickeys struct { 72 | UserID string 73 | keyfile string 74 | } 75 | 76 | type BFTX_encryptionConfig struct { 77 | Version string 78 | group string 79 | Recipients string 80 | EncryptionFields EncryptionField 81 | Publickeys Publickeys 82 | } 83 | 84 | type AgentForMaster struct { 85 | FirstName string 86 | LastName string 87 | Sig string 88 | } 89 | 90 | type AgentForOwner struct { 91 | FirstName string 92 | LastName string 93 | Sig string 94 | ConditionsForCarriage string 95 | } 96 | 97 | type MasterInfo struct { 98 | FirstName string 99 | LastName string 100 | Sig string 101 | } 102 | 103 | type BFTX_Decode_request struct { 104 | bftxtrans BFTX_transaction 105 | KeyName string 106 | } 107 | 108 | func (m *BFTX_Decode_request) Reset() { *m = BFTX_Decode_request{} } 109 | func (m *BFTX_Decode_request) String() string { return proto.CompactTextString(m) } 110 | func (*BFTX_Decode_request) ProtoMessage() {} 111 | 112 | // IssueDetails struct 113 | type IssueDetails struct { 114 | PlaceOfIssue string 115 | DateOfIssue string 116 | } 117 | 118 | type BFTX_transaction struct { 119 | BFTX_Payload BFTX_Payload 120 | } 121 | 122 | type BFTX_Encode_request struct { 123 | bftxtrans BFTX_transaction 124 | bftxconfig BFTX_encryptionConfig 125 | } 126 | 127 | func (m *BFTX_Encode_request) Reset() { *m = BFTX_Encode_request{} } 128 | func (m *BFTX_Encode_request) String() string { return proto.CompactTextString(m) } 129 | func (*BFTX_Encode_request) ProtoMessage() {} 130 | 131 | func init() { 132 | proto.RegisterType((*BFTX_Encode_request)(nil), "crypto.BFTX_Encode_request") 133 | proto.RegisterType((*BFTX_Decode_request)(nil), "crypto.BFTX_Decode_request") 134 | } 135 | 136 | // Reference imports to suppress errors if they are not otherwise used. 137 | var _ context.Context 138 | var _ grpc.ClientConn 139 | 140 | // This is a compile-time assertion to ensure that this generated file 141 | // is compatible with the grpc package it is being compiled against. 142 | const _ = grpc.SupportPackageIsVersion4 143 | 144 | // Client API for Greeter service 145 | 146 | type EncryptClient interface { 147 | BFTX_Encode(ctx context.Context, in *BFTX_Encode_request) *BFTX_transaction 148 | } 149 | 150 | type encryptClient struct { 151 | cc *grpc.ClientConn 152 | } 153 | 154 | func NewEncryptionClient(cc *grpc.ClientConn) EncryptClient { 155 | return &encryptClient{cc} 156 | } 157 | 158 | func (c *encryptClient) BFTX_Encode(ctx context.Context, in *BFTX_Encode_request) *BFTX_transaction { 159 | out := new(BFTX_transaction) 160 | err := grpc.Invoke(ctx, "/crypto.BFSaberService/BFTX_Encode", in, out, c.cc) 161 | if err != nil { 162 | log.Fatalf("did not connect: %v", err) 163 | } 164 | return out 165 | } 166 | -------------------------------------------------------------------------------- /lib/pkg/common/common.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/common/common.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB````BBBB lll kkk fff `` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package common provides some useful functions to work with the Blockfreight project. 46 | package common 47 | 48 | import ( 49 | 50 | // ======================= 51 | // Golang Standard library 52 | // ======================= 53 | "crypto/sha256" // Implements the SHA256 Algorithm for Hash. 54 | "errors" // Implements functions to manipulate errors. 55 | "fmt" // Implements formatted I/O with functions analogous to C's printf and scanf. 56 | "io/ioutil" // Implements some I/O utility functions. 57 | ) 58 | 59 | const ORIGIN_API = "API" 60 | const ORIGIN_CMD = "CMD" 61 | 62 | // ReadJSON is a function that receives the path of a file encapsulates the native Golang process of reading a file. 63 | func ReadJSON(path string) ([]byte, error) { 64 | fmt.Println("\nReading " + path + "\n") 65 | file, e := ioutil.ReadFile(path) 66 | if e != nil { 67 | return file, errors.New("File error: " + e.Error()) 68 | } 69 | return file, nil 70 | } 71 | 72 | // HashByteArrays hashes two byte arrays and returns a new one 73 | func HashByteArrays(firstArray, secondArray []byte) []byte { 74 | sha := sha256.New() 75 | sha.Write(append(firstArray[:], secondArray[:]...)) 76 | return sha.Sum(nil) 77 | } 78 | 79 | // ================================================= 80 | // Blockfreight™ | The blockchain of global freight. 81 | // ================================================= 82 | 83 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 84 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 85 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 86 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 87 | // BBBBBBB BBBBBBBBBBBBBBBB 88 | // BBBBBBB BBBBBBBBBBBBBBB 89 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 90 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 91 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 92 | // BBBBBBB BBBBBBBBBBBBBBBBBB 93 | // BBBBBBB BBBBBBBBBBBBBBB 94 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 95 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 96 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 97 | // BBBBBBB BBBBBBBBB BBB BBBBB 98 | // BBBBBBB BBBB BBBBB 99 | // BBBBBBB BBBBBBB BBBBB 100 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 101 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 102 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 103 | 104 | // ================================================== 105 | // Blockfreight™ | The blockchain for global freight. 106 | // ==================================================` 107 | -------------------------------------------------------------------------------- /api/handlers/transactionHandler.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "log" 7 | "strconv" 8 | 9 | "net/http" // Provides HTTP client and server implementations. 10 | 11 | "github.com/blockfreight/go-bftx/lib/app/bf_tx" 12 | "github.com/blockfreight/go-bftx/lib/app/bftx_logger" 13 | "github.com/blockfreight/go-bftx/lib/pkg/common" 14 | "github.com/blockfreight/go-bftx/lib/pkg/leveldb" 15 | "github.com/blockfreight/go-bftx/lib/pkg/saberservice" 16 | // Provides HTTP client and server implementations. 17 | // =============== 18 | // Tendermint Core 19 | // =============== 20 | ) 21 | 22 | func ConstructBfTx(transaction bf_tx.BF_TX) (interface{}, error) { 23 | 24 | log.Println("trying") 25 | if err := transaction.GenerateBFTX(common.ORIGIN_API); err != nil { 26 | return nil, err 27 | } 28 | bftx_logger.ApiListener(transaction.Id) 29 | return transaction, nil 30 | } 31 | 32 | func SignBfTx(idBftx string) (interface{}, error) { 33 | var transaction bf_tx.BF_TX 34 | if err := transaction.SignBFTX(idBftx, common.ORIGIN_API); err != nil { 35 | return nil, err 36 | } 37 | 38 | return transaction, nil 39 | } 40 | 41 | func EncryptBFTX(idBftx string) (interface{}, error) { 42 | var transaction bf_tx.BF_TX 43 | data, err := leveldb.GetBfTx(idBftx) 44 | if err != nil { 45 | if err.Error() == "LevelDB Get function: BF_TX not found." { 46 | bftx_logger.StringLogger("EncryptBFTX", "LevelDB Get function: BF_TX not found.", idBftx) 47 | return nil, errors.New(strconv.Itoa(http.StatusNotFound)) 48 | } 49 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 50 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 51 | } 52 | 53 | json.Unmarshal(data, &transaction) 54 | if err != nil { 55 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 56 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 57 | } 58 | 59 | if transaction.Verified { 60 | return nil, errors.New(strconv.Itoa(http.StatusNotAcceptable)) 61 | } 62 | 63 | nwbftx, err := saberservice.BftxStructConverstionON(&transaction) 64 | if err != nil { 65 | log.Fatalf("Conversion error, can not convert old bftx to new bftx structure") 66 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 67 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 68 | } 69 | st := saberservice.SaberDefaultInput() 70 | saberbftx, err := saberservice.SaberEncoding(nwbftx, st) 71 | if err != nil { 72 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 73 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 74 | } 75 | bftxold, err := saberservice.BftxStructConverstionNO(saberbftx) 76 | //update the encoded transaction to database 77 | // Get the BF_TX content in string format 78 | content, err := bf_tx.BFTXContent(*bftxold) 79 | if err != nil { 80 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 81 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 82 | } 83 | 84 | // Update on DB 85 | err = leveldb.RecordOnDB(string(bftxold.Id), content) 86 | if err != nil { 87 | bftx_logger.TransLogger("EncryptBFTX", err, idBftx) 88 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 89 | } 90 | 91 | return bftxold, nil 92 | } 93 | 94 | func DecryptBFTX(idBftx string) (interface{}, error) { 95 | var transaction bf_tx.BF_TX 96 | data, err := leveldb.GetBfTx(idBftx) 97 | if err != nil { 98 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 99 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 100 | } 101 | 102 | json.Unmarshal(data, &transaction) 103 | 104 | if err != nil { 105 | if err.Error() == "LevelDB Get function: BF_TX not found." { 106 | bftx_logger.StringLogger("DecryptBFTX", "LevelDB Get function: BF_TX not found.", idBftx) 107 | return nil, errors.New(strconv.Itoa(http.StatusNotFound)) 108 | } 109 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 110 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 111 | } 112 | 113 | if transaction.Verified { 114 | return nil, errors.New(strconv.Itoa(http.StatusNotAcceptable)) 115 | } 116 | 117 | nwbftx, err := saberservice.BftxStructConverstionON(&transaction) 118 | if err != nil { 119 | log.Fatalf("Conversion error, can not convert old bftx to new bftx structure") 120 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 121 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 122 | } 123 | st := saberservice.SaberDefaultInput() 124 | saberbftx, err := saberservice.SaberDecoding(nwbftx, st) 125 | if err != nil { 126 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 127 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 128 | } 129 | bftxold, err := saberservice.BftxStructConverstionNO(saberbftx) 130 | //update the encoded transaction to database 131 | // Get the BF_TX content in string format 132 | content, err := bf_tx.BFTXContent(*bftxold) 133 | if err != nil { 134 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 135 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 136 | } 137 | 138 | // Update on DB 139 | err = leveldb.RecordOnDB(string(bftxold.Id), content) 140 | if err != nil { 141 | bftx_logger.TransLogger("DecryptBFTX", err, idBftx) 142 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 143 | } 144 | 145 | return bftxold, nil 146 | } 147 | 148 | // BroadcastBfTx function to broadcast a BFTX via API 149 | func BroadcastBfTx(idBftx string) (interface{}, error) { 150 | var transaction bf_tx.BF_TX 151 | 152 | err := transaction.BroadcastBFTX(idBftx, common.ORIGIN_API) 153 | 154 | if err != nil { 155 | return nil, err 156 | } 157 | 158 | return transaction, nil 159 | } 160 | 161 | func GetTotal() (interface{}, error) { 162 | var bftx bf_tx.BF_TX 163 | 164 | total, err := bftx.GetTotal() 165 | if err != nil { 166 | return nil, err 167 | } 168 | 169 | return total, nil 170 | } 171 | 172 | func GetTransaction(idBftx string) (interface{}, error) { 173 | var transaction bf_tx.BF_TX 174 | if err := transaction.GetBFTX(idBftx, common.ORIGIN_API); err != nil { 175 | return nil, err 176 | } 177 | 178 | return transaction, nil 179 | } 180 | 181 | func QueryTransaction(idBftx string) (interface{}, error) { 182 | var transaction bf_tx.BF_TX 183 | bftxs, err := transaction.QueryBFTX(idBftx, common.ORIGIN_API) 184 | 185 | if err != nil { 186 | return nil, err 187 | } 188 | 189 | return bftxs, nil 190 | } 191 | -------------------------------------------------------------------------------- /lib/pkg/crypto/crypto.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/crypto/crypto.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package crypto provides useful functions to sign BF_TX. 46 | package crypto 47 | 48 | import ( 49 | // ======================= 50 | // Golang Standard library 51 | // ======================= 52 | "context" // Implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3. 53 | "log" 54 | // Implements several standard elliptic curves over prime fields. 55 | // Implements the MD5 hash algorithm as defined in RFC 1321. 56 | // Implements a cryptographically secure pseudorandom number generator. 57 | // Provides interfaces for hash functions. 58 | // Provides basic interfaces to I/O primitives. 59 | // Implements arbitrary-precision arithmetic (big numbers). 60 | // Implements conversions to and from string representations of basic data types. 61 | // ====================== 62 | // Blockfreight™ packages 63 | // ====================== 64 | // Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX. 65 | "google.golang.org/grpc" 66 | ) 67 | 68 | const ( 69 | address = "localhost:22222" 70 | ) 71 | 72 | func CryptoTransaction(content string) []byte { 73 | // Set up a connection to the server. 74 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 75 | if err != nil { 76 | log.Fatalf("did not connect: %v", err) 77 | } 78 | defer conn.Close() 79 | c := NewEncryptionClient(conn) 80 | 81 | bftxtrans := BFTX_transaction{ 82 | BFTX_Payload{ 83 | Shipper: "test", 84 | }, 85 | } 86 | 87 | bftxconfig := BFTX_encryptionConfig{ 88 | EncryptionFields: EncryptionField{ 89 | FieldName: "test", 90 | AuthorizedUser: "Carol", 91 | }, 92 | group: "1", 93 | Publickeys: Publickeys{ 94 | UserID: "UserID", 95 | keyfile: "keyfile", 96 | }, 97 | Recipients: "Recipients test", 98 | Version: "version", 99 | } 100 | 101 | r := c.BFTX_Encode(context.Background(), &BFTX_Encode_request{bftxtrans, bftxconfig}) 102 | if err != nil { 103 | log.Fatalf("could not greet: %v", err) 104 | } 105 | log.Printf("The result is: %+v\n", r) 106 | 107 | return []byte("") 108 | } 109 | 110 | // ================================================= 111 | // Blockfreight™ | The blockchain of global freight. 112 | // ================================================= 113 | 114 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 115 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 116 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 117 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 118 | // BBBBBBB BBBBBBBBBBBBBBBB 119 | // BBBBBBB BBBBBBBBBBBBBBB 120 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 121 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 122 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 123 | // BBBBBBB BBBBBBBBBBBBBBBBBB 124 | // BBBBBBB BBBBBBBBBBBBBBB 125 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 126 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 127 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 128 | // BBBBBBB BBBBBBBBB BBB BBBBB 129 | // BBBBBBB BBBB BBBBB 130 | // BBBBBBB BBBBBBB BBBBB 131 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 132 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 133 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 134 | 135 | // ================================================== 136 | // Blockfreight™ | The blockchain for global freight. 137 | // ================================================== 138 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/config/config.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Blockfreight™ App Configuration 46 | 47 | // Package config is a package that handles with the application configutarions. 48 | package config 49 | 50 | import ( 51 | "fmt" 52 | "os" 53 | 54 | // Implements common functions for Blockfreight™ 55 | "github.com/BurntSushi/toml" 56 | tmConfig "github.com/tendermint/tendermint/config" 57 | "github.com/tendermint/tendermint/libs/log" 58 | ) 59 | var GOPATH = os.Getenv("GOPATH") 60 | var configTomlLocation = GOPATH + "/src/github.com/blockfreight/go-bftx/config.toml" 61 | var homeDir = os.Getenv("HOME") 62 | var GenesisJSONURL = "https://raw.githubusercontent.com/blockfreight/tools/master/blockfreightnet-kubernetes/examples/blockfreight/genesis.json" 63 | var ConfigDir = homeDir + "/.blockfreight/config" 64 | var Logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) 65 | var config = tmConfig.DefaultConfig() 66 | var index = &tmConfig.TxIndexConfig{ 67 | Indexer: "kv", 68 | IndexTags: "bftx.id", 69 | IndexAllTags: false, 70 | } 71 | 72 | func GetBlockfreightConfig(verbose bool) *tmConfig.Config { 73 | 74 | fmt.Println(configTomlLocation) 75 | var blockfreightConfig Config 76 | 77 | if _, err := toml.DecodeFile(configTomlLocation, &blockfreightConfig); err != nil { 78 | fmt.Println(err) 79 | return config 80 | } 81 | 82 | config.P2P.Seeds = blockfreightConfig.getValidatorsSeedString() 83 | config.Consensus.CreateEmptyBlocks = blockfreightConfig.CreateEmptyBlocks 84 | config.RPC.ListenAddress = blockfreightConfig.RPC_ListenAddress 85 | config.TxIndex = index 86 | config.DBPath = ConfigDir + "/data" 87 | config.Genesis = ConfigDir + "/genesis.json" 88 | config.PrivValidator = ConfigDir + "/priv_validator.json" 89 | config.NodeKey = ConfigDir + "/node_key.json" 90 | config.P2P.AddrBook = ConfigDir + "/addrbook.json" 91 | config.P2P.ListenAddress = blockfreightConfig.P2P_ListenAddress 92 | 93 | if !verbose { 94 | config.LogLevel = fmt.Sprintf("*:%s", tmConfig.DefaultLogLevel()) 95 | } 96 | 97 | fmt.Printf("%+v\n", config) 98 | fmt.Printf("%+v\n", config.P2P) 99 | fmt.Printf("%+v\n", config.RPC) 100 | 101 | return config 102 | } 103 | 104 | type Config struct { 105 | GenesisJSON_URL string 106 | RPC_ListenAddress string 107 | P2P_ListenAddress string 108 | Validator_Domain string 109 | P2P_PORT string 110 | CreateEmptyBlocks bool 111 | Validators map[string]Validator 112 | } 113 | 114 | func (config Config) getValidatorsSeedString() string { 115 | bftx0 := config.Validators["bftx0"] 116 | bftx1 := config.Validators["bftx1"] 117 | bftx2 := config.Validators["bftx2"] 118 | bftx3 := config.Validators["bftx3"] 119 | 120 | seedsString := fmt.Sprintf("%s,%s,%s,%s", bftx0.getValidatorSeedString(config), bftx1.getValidatorSeedString(config), bftx2.getValidatorSeedString(config), bftx3.getValidatorSeedString(config)) 121 | return seedsString 122 | } 123 | 124 | type Validator struct { 125 | NodeID string 126 | ValidatorName string 127 | } 128 | 129 | func (validator Validator) getValidatorSeedString(config Config) string { 130 | seedString := fmt.Sprintf("%s@%s.%s:%s", validator.NodeID, validator.ValidatorName, config.Validator_Domain, config.P2P_PORT) 131 | return seedString 132 | } 133 | 134 | // ================================================= 135 | // Blockfreight™ | The blockchain of global freight. 136 | // ================================================= 137 | 138 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 139 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 140 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 141 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 142 | // BBBBBBB BBBBBBBBBBBBBBBB 143 | // BBBBBBB BBBBBBBBBBBBBBB 144 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 145 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 146 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 147 | // BBBBBBB BBBBBBBBBBBBBBBBBB 148 | // BBBBBBB BBBBBBBBBBBBBBB 149 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 150 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 151 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 152 | // BBBBBBB BBBBBBBBB BBB BBBBB 153 | // BBBBBBB BBBB BBBBB 154 | // BBBBBBB BBBBBBB BBBBB 155 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 156 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 157 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 158 | 159 | // ================================================== 160 | // Blockfreight™ | The blockchain for global freight. 161 | // ================================================== 162 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Blockfreight](https://raw.githubusercontent.com/blockfreight/brandmarks/master/blockfreight_logo_m.png) 2 | # **Blockfreight™ the blockchain of global freight** 3 | 4 | [![](https://img.shields.io/badge/made%20by-Blockfreight,%20Inc.-blue.svg?style=flat-square)](https://blockfreight.com) 5 | [![StackShare](https://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](https://stackshare.io/blockfreight-inc/blockfreight-inc) 6 | [![](https://img.shields.io/badge/Slack-%23blockfreight-blue.svg?style=flat-square)](http://slack.blockfreight.com) 7 | [![Build Status](https://travis-ci.org/blockfreight/go-bftx.svg?branch=v0.2.0-dev)](https://travis-ci.org/blockfreight/go-bftx) 8 | 9 | [![Go Report Card](https://goreportcard.com/badge/github.com/blockfreight/go-bftx)](https://goreportcard.com/report/github.com/blockfreight/go-bftx) 10 | [![Go Doc](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat-square)](http://godoc.org/github.com/blockfreight/go-bftx) 11 | [![Release](https://img.shields.io/github/release/golang-standards/project-lawet.svg?style=flat-square)](https://github.com/blockfreight/go-bftx) 12 | 13 | Package: go-blockfreight - Blockfreight™ v0.3.0 14 | 15 | ***Description:*** go-blockfreight is the reference full node implementation and cli-tool for Blockfreight™ the blockchain of global freight. 16 | 17 | A network for the free trade of physical goods so transformative it is part of the most advanced project in global shipping today. 18 | 19 | go-blockfreight is a powerful, reliable, efficient and handy Go app for communicating with the Blockfreight™ blockchain. 20 | 21 | ## Requirements: 22 | 23 | ### Golang runtime and build environment 24 | Go version 1.8+ or above. 25 | 26 | Quick command line test: 27 | 28 | ``` 29 | $ go version 30 | ``` 31 | Validate you have [Go installed](https://golang.org/doc/install) and have defined [`$GOPATH/bin`](https://github.com/tendermint/tendermint/wiki/Setting-GOPATH) in your `$PATH`. For full instructions see [golang.org site](http://golang.org/doc/install.html). 32 | 33 | ### Dependencie Manager 34 | Golang/dep version 0.1.0+ or above. 35 | Golang/dep - https://github.com/golang/dep 36 | 37 | To manage all dependencies for **go-bftx**, it is necessary to have [Golang/dep](https://github.com/golang/dep). 38 | ``` 39 | $ dep version 40 | ``` 41 | 42 | ## Installation 43 | 44 | To install **go-bftx**, (experimental) one-line install, may not work yet!: 45 | ``` 46 | wget https://raw.githubusercontent.com/blockfreight/go-bftx/master/cmd/bftx/install_bftx.sh -v -O install_bftx.sh; chmod +x install_bftx.sh; ./install_bftx.sh; 47 | ``` 48 | 49 | ## Step-by-step Installation 50 | 51 | To install **go-bftx**, you can do it through: 52 | ``` 53 | $ go get github.com/blockfreight/go-bftx 54 | ``` 55 | 56 | Then, you need to update all dependencies by Golang/dep. First go to **go-bftx** and update them: 57 | ``` 58 | $ cd $GOPATH/src/github.com/blockfreight/go-bftx 59 | $ dep ensure 60 | ``` 61 | 62 | ### BFT-Node 63 | Install BFT-Node through 64 | ``` 65 | $ cd $GOPATH/src/github.com/blockfreight/go-bftx/cmd/bftx 66 | $ go install 67 | ``` 68 | 69 | Then, you can execute `bftx` to check the options or extra information. 70 | ``` 71 | $ bftx 72 | ``` 73 | 74 | ## Use 75 | To start using go-bftx, you will have to start a node: 76 | ``` 77 | $ bftx node start 78 | ``` 79 | 80 | Then the Blockfreight API will start listening to transaction on `localhost:8080/bftx-api`. You can create, sign, broadcast and query transactions from the API. 81 | 82 | After that step, you can read the menu of bftx. 83 | 84 | If you’d like to leave feedback, please [open an issue on GitHub](https://github.com/blockfreight/blockfreight/issues). 85 | 86 | 87 | # Blockfreight™ Project Layout 88 | 89 | Blockfreight™ application code follows this convention: 90 | 91 | ``` 92 | ├──.gitignore 93 | ├──.travis.yml 94 | ├──glide.lock 95 | ├──glide.yaml 96 | ├──LICENSE 97 | ├──Makefile 98 | ├──README.md 99 | ├──api 100 | ├──assets 101 | ├──bin 102 | ├──build 103 | │ ├──ci 104 | │ └──package 105 | │ └──version 106 | ├──cmd 107 | │ ├──bftnode 108 | │ └──bftx 109 | ├──config 110 | ├──deploy 111 | ├──docs 112 | ├──examples 113 | ├──githooks 114 | ├──init 115 | ├──lib 116 | │ ├──app 117 | │ │ ├──bf_tx 118 | │ │ ├──bft 119 | │ │ └──validator 120 | │ └──pkg 121 | │ ├──common 122 | │ ├──crytpo 123 | │ └──leveldb 124 | ├──pkg 125 | │ └──blockfreight 126 | ├──plugins 127 | ├──scripts 128 | ├──test 129 | ├──third_party 130 | ├──tools 131 | ├──vendor 132 | │ ├──github.com 133 | │ ├──golang.org 134 | │ └──google.golang.org 135 | └──web 136 | ├──app 137 | ├──static 138 | └──template 139 | ``` 140 | 141 | ## Blockfreight™ Application Code 142 | 143 | ### `/api` 144 | 145 | OpenAPI/Swagger specs, JSON schema files, protocol definition files. 146 | 147 | ### `/assets` 148 | 149 | Other assets to go along with our repository. 150 | 151 | ### `/build` 152 | 153 | Packaging and Continous Integration. 154 | 155 | Put our cloud (AMI), container (Docker), OS (deb, rpm, pkg) package configurations and scripts in the `/build/package` directory. 156 | 157 | Put our CI (travis, circle, drone) configurations and scripts in the `/build/ci` directory. 158 | 159 | ### `/bin` 160 | 161 | Application and binary files required. 162 | 163 | ### `/cmd` 164 | 165 | Main application code. 166 | 167 | The directory name for each application matches the name of the executable we want to have (e.g., `/cmd/bftx`). 168 | 169 | Don't put a lot of code in the application directory unless we think that code can be imported and used in other projects. If this is the case then the code should live in the `/pkg` directory. 170 | 171 | It's common to have a small main function that imports and invokes the code from the `/lib` and `/pkg` directories. 172 | 173 | ### `/config` 174 | 175 | Configuration file templates or default configs. 176 | 177 | Put our `confd` or `consule-template` template files here. 178 | 179 | ### `/deploy` 180 | 181 | IaaS, PaaS, system and container orchestration deployment configurations and templates (docker-compose, kubernetes/helm, mesos, terraform, bosh). 182 | 183 | ### `/docs` 184 | 185 | Design and user documents (in addition to our godoc generated documentation). 186 | 187 | ### `/examples` 188 | 189 | Examples for our applications and/or public libraries. 190 | 191 | ### `/githooks` 192 | 193 | Git hooks. 194 | 195 | ### `/init` 196 | 197 | System init (systemd, upstart, sysv) and process manager/supervisor (runit, supervisord) configs. 198 | 199 | ### `/lib` 200 | 201 | Private application and library code. 202 | 203 | Put our actual application code in the `/lib/app` directory (e.g., `/lib/app/bftx`) and the code shared by those apps in the `/lib/pkg` directory (e.g., `/lib/pkg/bftxnode`). 204 | 205 | ### `/pkg` 206 | 207 | Library code that's safe to use by third party applications (e.g., `/pkg/bftpubliclib`). 208 | 209 | Other projects will import these libraries expecting them to work, so think twice before we put something here :-) 210 | 211 | ### `/plugins` 212 | 213 | Blockfreight™ pluggable architechture support for third-party plugins. 214 | 215 | ### `/scripts` 216 | 217 | Scripts to perform various build, install, analysis, etc operations. 218 | 219 | These scripts keep the root level Makefile small and simple. 220 | 221 | ### `/test` 222 | 223 | Additional external test apps and test data. 224 | 225 | ### `/third_party` 226 | 227 | External helper tools, forked code and other 3rd party utilities (e.g., Swagger UI). 228 | 229 | ### `/tools` 230 | 231 | Supporting tools for this project. Note that these tools can import code from the `/pkg` and `/lib` directories. 232 | 233 | ### `/vendor` 234 | 235 | Application dependencies (managed manually or by our favorite dependency management tool). 236 | 237 | Don't commit our application dependencies if we are building a library. 238 | 239 | ## Web Application Directories 240 | 241 | ### `/web` 242 | 243 | Web application specific components: static web assets, server side templates and SPAs. 244 | 245 | ## Notes 246 | 247 | Feedback to this project via Github Issues or email 248 | -------------------------------------------------------------------------------- /api/api/api.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "log" 8 | "net/http" // Provides HTTP client and server implementations. 9 | "strconv" 10 | 11 | "os" 12 | 13 | "github.com/blockfreight/go-bftx/api/graphqlObj" 14 | apiHandler "github.com/blockfreight/go-bftx/api/handlers" 15 | "github.com/blockfreight/go-bftx/lib/app/bf_tx" // Provides some useful functions to work with LevelDB. 16 | "github.com/graphql-go/graphql" 17 | "github.com/graphql-go/handler" 18 | graphiql "github.com/mnmtanish/go-graphiql" 19 | ) 20 | 21 | var schema, _ = graphql.NewSchema( 22 | graphql.SchemaConfig{ 23 | Query: queryType, 24 | Mutation: mutationType, 25 | }, 26 | ) 27 | 28 | var queryType = graphql.NewObject( 29 | graphql.ObjectConfig{ 30 | Name: "Query", 31 | Fields: graphql.Fields{ 32 | "getTransaction": &graphql.Field{ 33 | Type: graphqlObj.TransactionType, 34 | Args: graphql.FieldConfigArgument{ 35 | "Id": &graphql.ArgumentConfig{ 36 | Type: graphql.String, 37 | }, 38 | }, 39 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 40 | bftxID, isOK := p.Args["id"].(string) 41 | if !isOK { 42 | return nil, errors.New(strconv.Itoa(http.StatusBadRequest)) 43 | } 44 | 45 | return apiHandler.GetTransaction(bftxID) 46 | }, 47 | }, 48 | "queryTransaction": &graphql.Field{ 49 | Type: graphql.NewList(graphqlObj.TransactionType), 50 | Args: graphql.FieldConfigArgument{ 51 | "Id": &graphql.ArgumentConfig{ 52 | Type: graphql.String, 53 | }, 54 | }, 55 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 56 | bftxID, isOK := p.Args["Id"].(string) 57 | if !isOK { 58 | return nil, errors.New(strconv.Itoa(http.StatusBadRequest)) 59 | } 60 | 61 | return apiHandler.QueryTransaction(bftxID) 62 | }, 63 | }, 64 | "getInfo": &graphql.Field{ 65 | Type: graphqlObj.InfoType, 66 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 67 | return apiHandler.GetInfo() 68 | }, 69 | }, 70 | "getTotal": &graphql.Field{ 71 | Type: graphql.String, 72 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 73 | log.Println("getTotal") 74 | return apiHandler.GetTotal() 75 | }, 76 | }, 77 | }, 78 | }) 79 | 80 | var mutationType = graphql.NewObject( 81 | graphql.ObjectConfig{ 82 | Name: "Mutation", 83 | Fields: graphql.Fields{ 84 | "constructBFTX": &graphql.Field{ 85 | Type: graphqlObj.TransactionType, 86 | Args: graphql.FieldConfigArgument{ 87 | "Properties": &graphql.ArgumentConfig{ 88 | Description: "Transaction properties.", 89 | Type: graphqlObj.PropertiesInput, 90 | }, 91 | }, 92 | // Args: graphql.FieldConfigArgument{ 93 | // "Properties": &graphql.ArgumentConfig{ 94 | // Type: graphql.NewNonNull(graphql.Int), 95 | // }, 96 | // }, 97 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 98 | log.Println("constructBFTX") 99 | bftx := bf_tx.BF_TX{} 100 | jsonProperties, err := json.Marshal(p.Args) 101 | if err = json.Unmarshal([]byte(jsonProperties), &bftx); err != nil { 102 | return nil, errors.New(strconv.Itoa(http.StatusInternalServerError)) 103 | } 104 | 105 | return apiHandler.ConstructBfTx(bftx) 106 | }, 107 | }, 108 | "encryptBFTX": &graphql.Field{ 109 | Type: graphqlObj.TransactionType, 110 | Args: graphql.FieldConfigArgument{ 111 | "Id": &graphql.ArgumentConfig{ 112 | Type: graphql.String, 113 | }, 114 | }, 115 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 116 | bftxID, isOK := p.Args["Id"].(string) 117 | if !isOK { 118 | return nil, nil 119 | } 120 | 121 | return apiHandler.EncryptBFTX(bftxID) 122 | }, 123 | }, 124 | "decryptBFTX": &graphql.Field{ 125 | Type: graphqlObj.TransactionType, 126 | Args: graphql.FieldConfigArgument{ 127 | "Id": &graphql.ArgumentConfig{ 128 | Type: graphql.String, 129 | }, 130 | }, 131 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 132 | bftxID, isOK := p.Args["Id"].(string) 133 | if !isOK { 134 | return nil, nil 135 | } 136 | 137 | return apiHandler.DecryptBFTX(bftxID) 138 | }, 139 | }, 140 | "signBFTX": &graphql.Field{ 141 | Type: graphqlObj.TransactionType, 142 | Args: graphql.FieldConfigArgument{ 143 | "Id": &graphql.ArgumentConfig{ 144 | Type: graphql.String, 145 | }, 146 | }, 147 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 148 | bftxID, isOK := p.Args["Id"].(string) 149 | if !isOK { 150 | return nil, nil 151 | } 152 | 153 | return apiHandler.SignBfTx(bftxID) 154 | }, 155 | }, 156 | "broadcastBFTX": &graphql.Field{ 157 | Type: graphqlObj.TransactionType, 158 | Args: graphql.FieldConfigArgument{ 159 | "Id": &graphql.ArgumentConfig{ 160 | Type: graphql.String, 161 | }, 162 | }, 163 | Resolve: func(p graphql.ResolveParams) (interface{}, error) { 164 | bftxID, isOK := p.Args["Id"].(string) 165 | if !isOK { 166 | return nil, nil 167 | } 168 | 169 | return apiHandler.BroadcastBfTx(bftxID) 170 | }, 171 | }, 172 | }, 173 | }, 174 | ) 175 | 176 | //Start start the API 177 | func Start() error { 178 | http.HandleFunc("/bftx-api", httpHandler(&schema)) 179 | http.HandleFunc("/", graphiql.ServeGraphiQL) 180 | http.HandleFunc("/graphql", serveGraphQL(schema)) 181 | ex, err := os.Executable() 182 | if err != nil { 183 | fmt.Println(err) 184 | } 185 | file, err := os.Stat(ex) 186 | fmt.Println("Compiled: " + file.ModTime().String()) 187 | fmt.Println("Now server is running on: http://localhost:8080") 188 | fmt.Println("Started") 189 | return http.ListenAndServe(":8080", nil) 190 | } 191 | 192 | func httpHandler(schema *graphql.Schema) func(http.ResponseWriter, *http.Request) { 193 | fmt.Println("In handler") 194 | return func(rw http.ResponseWriter, r *http.Request) { 195 | fmt.Println("In httpHandler") 196 | rw.Header().Set("Content-Type", "application/json") 197 | httpStatusResponse := http.StatusOK 198 | // parse http.Request into handler.RequestOptions 199 | opts := handler.NewRequestOptions(r) 200 | 201 | // inject context objects http.ResponseWrite and *http.Request into rootValue 202 | // there is an alternative example of using `net/context` to store context instead of using rootValue 203 | rootValue := map[string]interface{}{ 204 | "response": rw, 205 | "request": r, 206 | "viewer": "john_doe", 207 | } 208 | 209 | // execute graphql query 210 | // here, we passed in Query, Variables and OperationName extracted from http.Request 211 | params := graphql.Params{ 212 | Schema: *schema, 213 | RequestString: opts.Query, 214 | VariableValues: opts.Variables, 215 | OperationName: opts.OperationName, 216 | RootObject: rootValue, 217 | } 218 | fmt.Println(params.OperationName) 219 | fmt.Println("graphql.Do(params)") 220 | fmt.Println(params) 221 | result := graphql.Do(params) 222 | js, err := json.Marshal(result) 223 | if err != nil { 224 | fmt.Println(err.Error()) 225 | http.Error(rw, err.Error(), http.StatusInternalServerError) 226 | 227 | } 228 | if result.HasErrors() { 229 | httpStatusResponse, err = strconv.Atoi(result.Errors[0].Error()) 230 | if err != nil { 231 | fmt.Println(err.Error()) 232 | httpStatusResponse = http.StatusInternalServerError 233 | } 234 | } 235 | fmt.Println(httpStatusResponse) 236 | fmt.Println(js) 237 | rw.WriteHeader(httpStatusResponse) 238 | 239 | rw.Write(js) 240 | 241 | } 242 | 243 | } 244 | 245 | func serveGraphQL(s graphql.Schema) http.HandlerFunc { 246 | 247 | return func(w http.ResponseWriter, r *http.Request) { 248 | fmt.Println("In serveGraphQL") 249 | sendError := func(err error) { 250 | w.WriteHeader(500) 251 | w.Write([]byte(err.Error())) 252 | } 253 | 254 | req := &graphiql.Request{} 255 | if err := json.NewDecoder(r.Body).Decode(req); err != nil { 256 | sendError(err) 257 | return 258 | } 259 | 260 | res := graphql.Do(graphql.Params{ 261 | Schema: s, 262 | RequestString: req.Query, 263 | }) 264 | 265 | if err := json.NewEncoder(w).Encode(res); err != nil { 266 | sendError(err) 267 | } 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /lib/app/validator/validator.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/validator/validator.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package validator is a package that provides functions to assure the input JSON is correct. 46 | package validator 47 | 48 | import ( 49 | "errors" 50 | "reflect" 51 | 52 | "github.com/blockfreight/go-bftx/lib/app/bf_tx" 53 | ) 54 | 55 | // Implements run-time reflection, allowing a program to manipulate objects with arbitrary types. 56 | // ====================== 57 | // Blockfreight™ packages 58 | // ====================== 59 | // Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX. 60 | 61 | // ValidateBFTX is a function that receives the BF_TX and return the proper message according with the result of ValidateFields function. 62 | func ValidateBFTX(bftx bf_tx.BF_TX) (string, error) { 63 | var espErr error 64 | 65 | valid, err := ValidateFields(bftx) 66 | if valid { 67 | return "Success! [OK]", nil 68 | } 69 | 70 | if err != "" { 71 | espErr = errors.New(` 72 | Specific Error [01]: 73 | ` + err) 74 | } 75 | return ` 76 | Blockfreight, Inc. © 2017. Open Source (MIT) License. 77 | 78 | Error [01]: 79 | 80 | Invalid structure in JSON provided. JSON 结构无效. 81 | Struttura JSON non valido. هيكل JSON صالح. 無効なJSON構造. 82 | Estructura inválida en el JSON dado. 83 | Estrutura inválida no JSON enviado. 84 | 85 | support: support@blockfreight.com`, espErr 86 | } 87 | 88 | // ValidateFields is a function that receives the BF_TX, validates every field in the BF_TX and return true or false, and a message if some field is wrong. 89 | func ValidateFields(bftx bf_tx.BF_TX) (bool, string) { 90 | if reflect.TypeOf(bftx.Properties.Shipment.Consignee) != reflect.TypeOf("s") { 91 | return false, "bftx.Properties.Consignee is not a string." 92 | } 93 | // if reflect.TypeOf(bftx.Properties.Vessel).Kind() != reflect.Int { 94 | // return false, "bftx.Properties.Vessel is not a number." 95 | // } 96 | if reflect.TypeOf(bftx.Properties.Consol.PortOfLoading) != reflect.TypeOf("s") { 97 | return false, "bftx.Properties.PortOfLoading is not a number." 98 | } 99 | if reflect.TypeOf(bftx.Properties.Consol.PortOfDischarge) != reflect.TypeOf("s") { 100 | return false, "bftx.Properties.PortOfDischarge is not a number." 101 | } 102 | if reflect.TypeOf(bftx.Properties.Shipment.GoodsDescription) != reflect.TypeOf("s") { 103 | return false, "bftx.Properties.GoodsDescription is not a string." 104 | } 105 | if reflect.TypeOf(bftx.Properties.Shipment.Housebill).Kind() != reflect.String { 106 | return false, "bftx.Properties.HouseBill is not a string." 107 | } 108 | if reflect.TypeOf(bftx.Properties.Shipment.MarksAndNumbers).Kind() != reflect.String { 109 | return false, "bftx.Properties.MarksAndNumbers is not a string." 110 | } 111 | if reflect.TypeOf(bftx.Properties.Shipment.PackType).Kind() != reflect.String { 112 | return false, "bftx.Properties.PackType is not a string." 113 | } 114 | if reflect.TypeOf(bftx.Properties.Shipment.INCOTERM).Kind() != reflect.String { 115 | return false, "bftx.Properties.INCOTerms is not a string." 116 | } 117 | if reflect.TypeOf(bftx.Properties.Consol.ContainerMode).Kind() != reflect.String { 118 | return false, "bftx.Properties.ContainerMode is not a string." 119 | } 120 | if reflect.TypeOf(bftx.Properties.Consol.ContainerType).Kind() != reflect.String { 121 | return false, "bftx.Properties.ContainerType is not a string." 122 | } 123 | 124 | return true, "" 125 | } 126 | 127 | // ================================================= 128 | // Blockfreight™ | The blockchain of global freight. 129 | // ================================================= 130 | 131 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 132 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 133 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 134 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 135 | // BBBBBBB BBBBBBBBBBBBBBBB 136 | // BBBBBBB BBBBBBBBBBBBBBB 137 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 138 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 139 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 140 | // BBBBBBB BBBBBBBBBBBBBBBBBB 141 | // BBBBBBB BBBBBBBBBBBBBBB 142 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 143 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 144 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 145 | // BBBBBBB BBBBBBBBB BBB BBBBB 146 | // BBBBBBB BBBB BBBBB 147 | // BBBBBBB BBBBBBB BBBBB 148 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 149 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 150 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 151 | 152 | // ================================================== 153 | // Blockfreight™ | The blockchain for global freight. 154 | // ================================================== 155 | -------------------------------------------------------------------------------- /lib/pkg/leveldb/leveldb.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/leveldb/leveldb.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package leveldb provides some useful functions to work with LevelDB. 46 | // It has common database functions as OpenDB, CloseDB, Insert and Iterate. 47 | package leveldb 48 | 49 | import ( 50 | // ======================= 51 | // Golang Standard library 52 | // ======================= 53 | // Implements encoding and decoding of JSON as defined in RFC 4627. 54 | "errors" // Implements functions to manipulate errors. 55 | "os" 56 | 57 | // ==================== 58 | // Third-party packages 59 | // ==================== 60 | 61 | "github.com/syndtr/goleveldb/leveldb" // Implementation of the LevelDB key/value database in the Go programming language. 62 | ) 63 | 64 | var homeDir = os.Getenv("HOME") 65 | var dbPath = homeDir + "/.blockfreight/config/bft-db" //Folder name where is going to be the LevelDB 66 | 67 | // OpenDB is a function that receives the path of the DB, creates or opens that DB and return ir with a possible error if that occurred. 68 | func OpenDB(dbPath string) (db *leveldb.DB, err error) { 69 | db, err = leveldb.OpenFile(dbPath, nil) 70 | return db, err 71 | } 72 | 73 | // CloseDB is a function that receives a DB pointer that closes the connection to DB. 74 | func CloseDB(db *leveldb.DB) { 75 | db.Close() 76 | } 77 | 78 | // InsertBFTX is a function that receives the key and value strings to insert a tuple in determined DB, the final parameter. As result, it returns a true or false bool. 79 | func InsertBFTX(key string, value string, db *leveldb.DB) error { 80 | return db.Put([]byte(key), []byte(value), nil) 81 | } 82 | 83 | // Total is a function that returns the total of BF_TX stored in the DB. 84 | func Total() (int, error) { 85 | db, err := OpenDB(dbPath) 86 | defer CloseDB(db) 87 | if err != nil { 88 | return 0, err 89 | } 90 | 91 | iter := db.NewIterator(nil, nil) 92 | n := 0 93 | for iter.Next() { 94 | n += 1 95 | } 96 | iter.Release() 97 | return n, iter.Error() 98 | } 99 | 100 | // RecordOnDB is a function that receives the content of the BF_RX JSON to insert it into the DB and return true or false according to the result. 101 | func RecordOnDB(id string, json string) error { 102 | db, err := OpenDB(dbPath) 103 | defer CloseDB(db) 104 | if err != nil { 105 | return err 106 | } 107 | err = InsertBFTX(id, json, db) 108 | if err != nil { 109 | return err 110 | } 111 | return nil 112 | } 113 | 114 | // GetBfTx is a function that receives a bf_tx id, and returns the BF_TX if it exists. 115 | func GetBfTx(id string) ([]byte, error) { 116 | var data []byte 117 | db, err := OpenDB(dbPath) 118 | defer CloseDB(db) 119 | if err != nil { 120 | return data, err 121 | } 122 | 123 | data, err = db.Get([]byte(id), nil) 124 | if err != nil { 125 | if err.Error() == "leveldb: not found" { 126 | return data, errors.New("LevelDB Get function: BF_TX not found.") 127 | } 128 | return data, errors.New("LevelDB Get function: " + err.Error()) 129 | } 130 | 131 | return data, nil 132 | } 133 | 134 | // Verify is a function that receives a content and look for a BF_TX that has the same content. 135 | /* func Verify(jcontent string) ([]byte, error) { 136 | var bftx bf_tx.BF_TX 137 | db, err := OpenDB(dbPath) 138 | defer CloseDB(db) 139 | if err != nil { 140 | return nil, err 141 | } 142 | 143 | iter := db.NewIterator(nil, nil) 144 | for iter.Next() { 145 | key := iter.Key() 146 | value := iter.Value() 147 | 148 | // Get a BF_TX by id 149 | json.Unmarshal(value, &bftx) 150 | 151 | // Reinitialize the BF_TX 152 | bftx = bf_tx.Reinitialize(bftx) 153 | 154 | // Get the BF_TX old_content in string format 155 | content, err := bf_tx.BFTXContent(bftx) 156 | if err != nil { 157 | return nil, err 158 | } 159 | 160 | if jcontent == content { 161 | iter.Release() 162 | //strconv.Atoi(string(buf)) 163 | return key, nil 164 | } 165 | } 166 | iter.Release() 167 | 168 | return nil, iter.Error() 169 | } */ 170 | 171 | // ================================================= 172 | // Blockfreight™ | The blockchain of global freight. 173 | // ================================================= 174 | 175 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 176 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 177 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 178 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 179 | // BBBBBBB BBBBBBBBBBBBBBBB 180 | // BBBBBBB BBBBBBBBBBBBBBB 181 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 182 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 183 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 184 | // BBBBBBB BBBBBBBBBBBBBBBBBB 185 | // BBBBBBB BBBBBBBBBBBBBBB 186 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 187 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 188 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 189 | // BBBBBBB BBBBBBBBB BBB BBBBB 190 | // BBBBBBB BBBB BBBBB 191 | // BBBBBBB BBBBBBB BBBBB 192 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 193 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 194 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 195 | 196 | // ================================================== 197 | // Blockfreight™ | The blockchain for global freight. 198 | // ================================================== 199 | -------------------------------------------------------------------------------- /lib/app/bft/bft.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/bft.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package bft implements the main functions to work with the Blockfreight™ Network. 46 | package bft 47 | 48 | import ( 49 | "encoding/binary" 50 | "encoding/json" 51 | 52 | // ======================= 53 | // Golang Standard library 54 | // ======================= 55 | // Implements simple functions to manipulate UTF-8 encoded strings. 56 | 57 | // =============== 58 | // Tendermint Core 59 | // =============== 60 | 61 | "bytes" 62 | "fmt" 63 | 64 | "github.com/blockfreight/go-bftx/lib/app/bf_tx" 65 | "github.com/tendermint/tendermint/abci/example/code" 66 | "github.com/tendermint/tendermint/abci/types" 67 | cmn "github.com/tendermint/tendermint/libs/common" 68 | dbm "github.com/tendermint/tendermint/libs/db" 69 | ) 70 | 71 | var ( 72 | stateKey = []byte("stateKey") 73 | kvPairPrefixKey = []byte("kvPairKey:") 74 | ) 75 | 76 | func loadState(db dbm.DB) State { 77 | stateBytes := db.Get(stateKey) 78 | var state State 79 | if len(stateBytes) != 0 { 80 | err := json.Unmarshal(stateBytes, &state) 81 | if err != nil { 82 | panic(err) 83 | } 84 | } 85 | state.db = db 86 | return state 87 | } 88 | 89 | func saveState(state State) { 90 | stateBytes, err := json.Marshal(state) 91 | if err != nil { 92 | panic(err) 93 | } 94 | state.db.Set(stateKey, stateBytes) 95 | } 96 | 97 | func prefixKey(key []byte) []byte { 98 | return append(kvPairPrefixKey, key...) 99 | } 100 | 101 | var _ types.Application = (*BftApplication)(nil) 102 | 103 | // BftApplication struct 104 | type BftApplication struct { 105 | types.BaseApplication 106 | 107 | state State 108 | } 109 | 110 | // NewBftApplication creates a new application 111 | func NewBftApplication() *BftApplication { 112 | state := loadState(dbm.NewMemDB()) 113 | return &BftApplication{state: state} 114 | } 115 | 116 | // Info returns information 117 | func (app *BftApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) { 118 | return types.ResponseInfo{Data: fmt.Sprintf("{\"size\":%v}", app.state.Size), LastBlockAppHash: app.state.AppHash} 119 | } 120 | 121 | // DeliverTx delivers transactions.Transactions are either "key=value" or just arbitrary bytes 122 | func (app *BftApplication) DeliverTx(tx []byte) types.ResponseDeliverTx { 123 | 124 | var key, value []byte 125 | parts := bytes.Split(tx, []byte("=")) 126 | if len(parts) == 2 { 127 | key, value = parts[0], parts[1] 128 | } else { 129 | key, value = tx, tx 130 | } 131 | app.state.db.Set(prefixKey(key), value) 132 | app.state.Size += 1 133 | 134 | var bftx bf_tx.BF_TX 135 | err := json.Unmarshal(tx, &bftx) 136 | if err != nil { 137 | panic(err) 138 | } 139 | 140 | tags := []cmn.KVPair{ 141 | {[]byte("bftx.id"), []byte(bftx.Id)}, 142 | } 143 | return types.ResponseDeliverTx{Code: code.CodeTypeOK, Tags: tags} 144 | } 145 | 146 | // CheckTx checks a transaction 147 | func (app *BftApplication) CheckTx(tx []byte) types.ResponseCheckTx { 148 | return types.ResponseCheckTx{Code: code.CodeTypeOK} 149 | //if cpcash.validate("BFTXafe2242d45cc5e54041b2b52913ef9a1aede4998a32e3fee128cf7d1e7575a41") { 150 | // return types.ResponseCheckTx{Code: code.CodeTypeOK} 151 | //} 152 | //return types.ResponseCheckTx{Code: code.NotPaid} 153 | 154 | } 155 | 156 | type State struct { 157 | db dbm.DB 158 | Size int64 `json:"size"` 159 | Height int64 `json:"height"` 160 | AppHash []byte `json:"app_hash"` 161 | } 162 | 163 | // Commit commits transactions 164 | func (app *BftApplication) Commit() types.ResponseCommit { 165 | // Using a memdb - just return the big endian size of the db 166 | appHash := make([]byte, 8) 167 | binary.PutVarint(appHash, app.state.Size) 168 | app.state.AppHash = appHash 169 | app.state.Height += 1 170 | saveState(app.state) 171 | return types.ResponseCommit{Data: appHash} 172 | } 173 | 174 | //Query retrieves a transaction from the network 175 | func (app *BftApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) { 176 | if reqQuery.Prove { 177 | value := app.state.db.Get(prefixKey(reqQuery.Data)) 178 | resQuery.Index = -1 // TODO make Proof return index 179 | resQuery.Key = reqQuery.Data 180 | resQuery.Value = value 181 | if value != nil { 182 | resQuery.Log = "exists" 183 | } else { 184 | resQuery.Log = "does not exist" 185 | } 186 | return 187 | } else { 188 | value := app.state.db.Get(prefixKey(reqQuery.Data)) 189 | resQuery.Value = value 190 | if value != nil { 191 | resQuery.Log = "exists" 192 | } else { 193 | resQuery.Log = "does not exist" 194 | } 195 | return 196 | } 197 | } 198 | 199 | // ================================================= 200 | // Blockfreight™ | The blockchain of global freight. 201 | // ================================================= 202 | 203 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 204 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 205 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 206 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 207 | // BBBBBBB BBBBBBBBBBBBBBBB 208 | // BBBBBBB BBBBBBBBBBBBBBB 209 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 210 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 211 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 212 | // BBBBBBB BBBBBBBBBBBBBBBBBB 213 | // BBBBBBB BBBBBBBBBBBBBBB 214 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 215 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 216 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 217 | // BBBBBBB BBBBBBBBB BBB BBBBB 218 | // BBBBBBB BBBB BBBBB 219 | // BBBBBBB BBBBBBB BBBBB 220 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 221 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 222 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 223 | 224 | // ================================================== 225 | // Blockfreight™ | The blockchain for global freight. 226 | // ================================================== 227 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/BurntSushi/toml" 6 | packages = ["."] 7 | revision = "3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005" 8 | version = "v0.3.1" 9 | 10 | [[projects]] 11 | branch = "master" 12 | name = "github.com/beorn7/perks" 13 | packages = ["quantile"] 14 | revision = "3a771d992973f24aa725d07868b467d1ddfceafb" 15 | 16 | [[projects]] 17 | branch = "master" 18 | name = "github.com/btcsuite/btcd" 19 | packages = ["btcec"] 20 | revision = "7d2daa5bfef28c5e282571bc06416516936115ee" 21 | 22 | [[projects]] 23 | name = "github.com/davecgh/go-spew" 24 | packages = ["spew"] 25 | revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" 26 | version = "v1.1.1" 27 | 28 | [[projects]] 29 | name = "github.com/ebuchman/fail-test" 30 | packages = ["."] 31 | revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" 32 | 33 | [[projects]] 34 | name = "github.com/go-kit/kit" 35 | packages = [ 36 | "log", 37 | "log/level", 38 | "log/term", 39 | "metrics", 40 | "metrics/discard", 41 | "metrics/internal/lv", 42 | "metrics/prometheus" 43 | ] 44 | revision = "4dc7be5d2d12881735283bcab7352178e190fc71" 45 | version = "v0.6.0" 46 | 47 | [[projects]] 48 | name = "github.com/go-logfmt/logfmt" 49 | packages = ["."] 50 | revision = "07c9b44f60d7ffdfb7d8efe1ad539965737836dc" 51 | version = "v0.4.0" 52 | 53 | [[projects]] 54 | name = "github.com/go-stack/stack" 55 | packages = ["."] 56 | revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a" 57 | version = "v1.8.0" 58 | 59 | [[projects]] 60 | name = "github.com/gogo/protobuf" 61 | packages = [ 62 | "gogoproto", 63 | "jsonpb", 64 | "proto", 65 | "protoc-gen-gogo/descriptor", 66 | "sortkeys", 67 | "types" 68 | ] 69 | revision = "7d68e886eac4f7e34d0d82241a6273d6c304c5cf" 70 | version = "v1.1.0" 71 | 72 | [[projects]] 73 | name = "github.com/golang/protobuf" 74 | packages = [ 75 | "proto", 76 | "ptypes", 77 | "ptypes/any", 78 | "ptypes/duration", 79 | "ptypes/timestamp" 80 | ] 81 | revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" 82 | version = "v1.1.0" 83 | 84 | [[projects]] 85 | branch = "master" 86 | name = "github.com/golang/snappy" 87 | packages = ["."] 88 | revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" 89 | 90 | [[projects]] 91 | name = "github.com/gorilla/websocket" 92 | packages = ["."] 93 | revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" 94 | version = "v1.2.0" 95 | 96 | [[projects]] 97 | name = "github.com/graphql-go/graphql" 98 | packages = [ 99 | ".", 100 | "gqlerrors", 101 | "language/ast", 102 | "language/kinds", 103 | "language/lexer", 104 | "language/location", 105 | "language/parser", 106 | "language/printer", 107 | "language/source", 108 | "language/typeInfo", 109 | "language/visitor" 110 | ] 111 | revision = "08943645bf265d192b32f2100cdff2428f7ae7c5" 112 | version = "v0.7.7" 113 | 114 | [[projects]] 115 | branch = "master" 116 | name = "github.com/graphql-go/handler" 117 | packages = ["."] 118 | revision = "12f536ef9f005a2c790e199e80f1eff2b276cab9" 119 | 120 | [[projects]] 121 | branch = "master" 122 | name = "github.com/jmhodges/levigo" 123 | packages = ["."] 124 | revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" 125 | 126 | [[projects]] 127 | branch = "master" 128 | name = "github.com/kr/logfmt" 129 | packages = ["."] 130 | revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" 131 | 132 | [[projects]] 133 | name = "github.com/matttproud/golang_protobuf_extensions" 134 | packages = ["pbutil"] 135 | revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" 136 | version = "v1.0.1" 137 | 138 | [[projects]] 139 | branch = "master" 140 | name = "github.com/mnmtanish/go-graphiql" 141 | packages = ["."] 142 | revision = "cef5a61bd62b996aa67029c6c858f673d6e51718" 143 | 144 | [[projects]] 145 | name = "github.com/pkg/errors" 146 | packages = ["."] 147 | revision = "645ef00459ed84a119197bfb8d8205042c6df63d" 148 | version = "v0.8.0" 149 | 150 | [[projects]] 151 | name = "github.com/prometheus/client_golang" 152 | packages = [ 153 | "prometheus", 154 | "prometheus/promhttp" 155 | ] 156 | revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" 157 | 158 | [[projects]] 159 | branch = "master" 160 | name = "github.com/prometheus/client_model" 161 | packages = ["go"] 162 | revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" 163 | 164 | [[projects]] 165 | branch = "master" 166 | name = "github.com/prometheus/common" 167 | packages = [ 168 | "expfmt", 169 | "internal/bitbucket.org/ww/goautoneg", 170 | "model" 171 | ] 172 | revision = "4724e9255275ce38f7179b2478abeae4e28c904f" 173 | 174 | [[projects]] 175 | branch = "master" 176 | name = "github.com/prometheus/procfs" 177 | packages = [ 178 | ".", 179 | "internal/util", 180 | "nfs", 181 | "xfs" 182 | ] 183 | revision = "1dc9a6cbc91aacc3e8b2d63db4d2e957a5394ac4" 184 | 185 | [[projects]] 186 | name = "github.com/rcrowley/go-metrics" 187 | packages = ["."] 188 | revision = "e2704e165165ec55d062f5919b4b29494e9fa790" 189 | 190 | [[projects]] 191 | branch = "master" 192 | name = "github.com/syndtr/goleveldb" 193 | packages = [ 194 | "leveldb", 195 | "leveldb/cache", 196 | "leveldb/comparer", 197 | "leveldb/errors", 198 | "leveldb/filter", 199 | "leveldb/iterator", 200 | "leveldb/journal", 201 | "leveldb/memdb", 202 | "leveldb/opt", 203 | "leveldb/storage", 204 | "leveldb/table", 205 | "leveldb/util" 206 | ] 207 | revision = "b001fa50d6b27f3f0bb175a87d0cb55426d0a0ae" 208 | 209 | [[projects]] 210 | branch = "master" 211 | name = "github.com/tendermint/ed25519" 212 | packages = [ 213 | ".", 214 | "edwards25519", 215 | "extra25519" 216 | ] 217 | revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" 218 | 219 | [[projects]] 220 | name = "github.com/tendermint/go-amino" 221 | packages = ["."] 222 | revision = "c7424fdd930314cc4c344b331e112dac004718ef" 223 | version = "0.9.7" 224 | 225 | [[projects]] 226 | name = "github.com/tendermint/tendermint" 227 | packages = [ 228 | "abci/client", 229 | "abci/example/code", 230 | "abci/example/kvstore", 231 | "abci/types", 232 | "blockchain", 233 | "config", 234 | "consensus", 235 | "consensus/types", 236 | "crypto", 237 | "crypto/ed25519", 238 | "crypto/encoding/amino", 239 | "crypto/merkle", 240 | "crypto/secp256k1", 241 | "crypto/tmhash", 242 | "evidence", 243 | "libs/autofile", 244 | "libs/clist", 245 | "libs/common", 246 | "libs/db", 247 | "libs/events", 248 | "libs/flowrate", 249 | "libs/log", 250 | "libs/pubsub", 251 | "libs/pubsub/query", 252 | "mempool", 253 | "node", 254 | "p2p", 255 | "p2p/conn", 256 | "p2p/pex", 257 | "p2p/upnp", 258 | "privval", 259 | "proxy", 260 | "rpc/client", 261 | "rpc/core", 262 | "rpc/core/types", 263 | "rpc/grpc", 264 | "rpc/lib", 265 | "rpc/lib/client", 266 | "rpc/lib/server", 267 | "rpc/lib/types", 268 | "state", 269 | "state/txindex", 270 | "state/txindex/kv", 271 | "state/txindex/null", 272 | "types", 273 | "version" 274 | ] 275 | revision = "d542d2c3945116697f60451e6a407082c41c3cc9" 276 | version = "v0.22.8" 277 | 278 | [[projects]] 279 | branch = "master" 280 | name = "github.com/urfave/cli" 281 | packages = ["."] 282 | revision = "b67dcf995b6a7b7f14fad5fcb7cc5441b05e814b" 283 | 284 | [[projects]] 285 | branch = "master" 286 | name = "golang.org/x/crypto" 287 | packages = [ 288 | "curve25519", 289 | "internal/subtle", 290 | "nacl/box", 291 | "nacl/secretbox", 292 | "poly1305", 293 | "ripemd160", 294 | "salsa20/salsa" 295 | ] 296 | revision = "505ab145d0a99da450461ae2c1a9f6cd10d1f447" 297 | 298 | [[projects]] 299 | name = "golang.org/x/net" 300 | packages = [ 301 | "context", 302 | "http/httpguts", 303 | "http2", 304 | "http2/hpack", 305 | "idna", 306 | "internal/timeseries", 307 | "netutil", 308 | "trace" 309 | ] 310 | revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" 311 | 312 | [[projects]] 313 | name = "golang.org/x/text" 314 | packages = [ 315 | "collate", 316 | "collate/build", 317 | "internal/colltab", 318 | "internal/gen", 319 | "internal/tag", 320 | "internal/triegen", 321 | "internal/ucd", 322 | "language", 323 | "secure/bidirule", 324 | "transform", 325 | "unicode/bidi", 326 | "unicode/cldr", 327 | "unicode/norm", 328 | "unicode/rangetable" 329 | ] 330 | revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" 331 | version = "v0.3.0" 332 | 333 | [[projects]] 334 | name = "google.golang.org/genproto" 335 | packages = ["googleapis/rpc/status"] 336 | revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" 337 | 338 | [[projects]] 339 | name = "google.golang.org/grpc" 340 | packages = [ 341 | ".", 342 | "balancer", 343 | "balancer/base", 344 | "balancer/roundrobin", 345 | "codes", 346 | "connectivity", 347 | "credentials", 348 | "encoding", 349 | "encoding/proto", 350 | "grpclog", 351 | "internal", 352 | "internal/backoff", 353 | "internal/channelz", 354 | "internal/grpcrand", 355 | "keepalive", 356 | "metadata", 357 | "naming", 358 | "peer", 359 | "resolver", 360 | "resolver/dns", 361 | "resolver/passthrough", 362 | "stats", 363 | "status", 364 | "tap", 365 | "transport" 366 | ] 367 | revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" 368 | version = "v1.13.0" 369 | 370 | [[projects]] 371 | name = "gopkg.in/yaml.v2" 372 | packages = ["."] 373 | revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" 374 | version = "v2.2.2" 375 | 376 | [solve-meta] 377 | analyzer-name = "dep" 378 | analyzer-version = 1 379 | inputs-digest = "7fa79f769cea096fa8e78a65630928e6aa14a8ef80663ab314cbc769dd3f0cb9" 380 | solver-name = "gps-cdcl" 381 | solver-version = 1 382 | -------------------------------------------------------------------------------- /lib/pkg/saberservice/saberservice.go: -------------------------------------------------------------------------------- 1 | package saberservice 2 | 3 | import ( 4 | "bufio" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "os" 10 | "strings" 11 | 12 | btx "github.com/blockfreight/go-bftx/lib/app/bf_tx" 13 | "google.golang.org/grpc" 14 | yaml "gopkg.in/yaml.v2" 15 | ) 16 | 17 | // Saberinput structure for go-bftx use and test 18 | type Saberinput struct { 19 | mode string 20 | address string 21 | txpath string 22 | txconfigpath string 23 | KeyName string 24 | } 25 | 26 | func check(e error) { 27 | if e != nil { 28 | panic(e) 29 | } 30 | } 31 | 32 | func loadtransaction(s string) *BFTXTransaction { 33 | var bftx *BFTXTransaction 34 | 35 | jsmsg, err := ioutil.ReadFile(s) 36 | check(err) 37 | 38 | err = json.Unmarshal(jsmsg, &bftx) 39 | check(err) 40 | return bftx 41 | } 42 | 43 | func loadconfiguration(s string) *BFTXEncryptionConfig { 44 | var bfconfig *BFTXEncryptionConfig 45 | 46 | ylconfig, err := ioutil.ReadFile(s) 47 | check(err) 48 | 49 | err = yaml.UnmarshalStrict(ylconfig, &bfconfig) 50 | check(err) 51 | return bfconfig 52 | } 53 | 54 | // NVCsvConverterNew is a function that 55 | // convert an array of bftx parameters to BFTXTransaction structure. 56 | // This is used for the converting the Lading.csv to bftx.BFTX 57 | //-------------------------------------------------------------------------------- 58 | func NVCsvConverterNew(line []string) *BFTXTransaction { 59 | msg := BFTXTransaction{ 60 | Properties: &BFTX_Payload{ 61 | Shipper: line[0], 62 | Consignee: line[1], 63 | ReceiveAgent: line[2], 64 | HouseBill: line[3], 65 | PortOfLoading: line[4], 66 | PortOfDischarge: line[5], 67 | Destination: line[6], 68 | MarksAndNumbers: line[7], 69 | DescOfGoods: nvparsedesc(line[8]), 70 | GrossWeight: line[9], 71 | UnitOfWeight: line[10], 72 | Volume: line[11], 73 | UnitOfVolume: line[12], 74 | Container: line[13], 75 | ContainerSeal: line[14], 76 | ContainerMode: line[15], 77 | ContainerType: line[16], 78 | Packages: line[17], 79 | PackType: line[18], 80 | INCOTerms: line[19], 81 | DeliverAgent: line[20], 82 | }, 83 | } 84 | return &msg 85 | } 86 | 87 | // NVCsvConverterOld is a function that 88 | // convert an array of bftx parameters to BF_TX structure. 89 | // This is used for the converting the Lading.csv to bftx.BFTX 90 | //-------------------------------------------------------------------------------- 91 | /*func NVCsvConverterOld(line []string) btx.BF_TX { 92 | msg := btx.BF_TX{ 93 | Properties: btx.Properties{ 94 | Shipper: line[0], 95 | Consignee: line[1], 96 | ReceiveAgent: line[2], 97 | HouseBill: line[3], 98 | PortOfLoading: line[4], 99 | PortOfDischarge: line[5], 100 | Destination: line[6], 101 | MarksAndNumbers: line[7], 102 | DescOfGoods: nvparsedesc(line[8]), 103 | GrossWeight: line[9], 104 | UnitOfWeight: line[10], 105 | Volume: line[11], 106 | UnitOfVolume: line[12], 107 | Container: line[13], 108 | ContainerSeal: line[14], 109 | ContainerMode: line[15], 110 | ContainerType: line[16], 111 | Packages: line[17], 112 | PackType: line[18], 113 | INCOTerms: line[19], 114 | DeliverAgent: line[20], 115 | }, 116 | } 117 | return msg 118 | }*/ 119 | 120 | // NVCsvConverter helper functions 121 | // nvparseasfloat provides error handling necessary for bf_tx.Properties single-value float context 122 | // func nvparseasfloat(num string) float32 { 123 | // c, err := strconv.ParseFloat(num, 32) 124 | // if err != nil { 125 | // log.Fatal(err) 126 | // } 127 | // return float32(c) 128 | // } 129 | 130 | // nvparseasint provides error handling necessary for bf_tx.Properties single-value int context 131 | // func nvparseasint(num string) int64 { 132 | // c, err := strconv.Atoi(num) 133 | // if err != nil { 134 | // log.Fatal(err) 135 | // } 136 | // return int64(c) 137 | // } 138 | 139 | // nvparseasint provides error handling necessary for bf_tx.Properties single-value string context 140 | func nvparsedesc(desc string) string { 141 | item := desc 142 | item = strings.Replace(item, "\n", " ", -1) 143 | item = strings.Replace(item, "\t", " ", -1) 144 | item = strings.Replace(item, "\r", " ", -1) 145 | return item 146 | } 147 | 148 | //-------------------------------------------------------------------------------- 149 | 150 | // BftxStructConverstionNO (New to Old) is a function that convert the new *BFTXTransaction 151 | // structure to old struct *BF_TX. These two structure is duplicated somehow. This function is used 152 | // for temporal conversion. 153 | // since this is just for temporal usage, I will just use json marshal and unmarshal 154 | // to convert structures 155 | func BftxStructConverstionNO(tx *BFTXTransaction) (*btx.BF_TX, error) { 156 | var oldbftx btx.BF_TX 157 | bfjs, err := json.Marshal(*tx) 158 | if err != nil { 159 | return &oldbftx, err 160 | } 161 | err = json.Unmarshal(bfjs, &oldbftx) 162 | if err != nil { 163 | return &oldbftx, err 164 | } 165 | return &oldbftx, nil 166 | } 167 | 168 | // BftxStructConverstionON (Old to New) is a function that convert the old structure 169 | // *BF_TX to new structure *BFTXTransaction. These two structure is duplicated somehow. This function is used 170 | // for temporal conversion. 171 | // since this is just for temporal usage, I will just use json marshal and unmarshal 172 | // to convert structures 173 | func BftxStructConverstionON(tx *btx.BF_TX) (*BFTXTransaction, error) { 174 | var newbftx BFTXTransaction 175 | bfjs, err := json.Marshal(tx) 176 | if err != nil { 177 | return &newbftx, err 178 | } 179 | err = json.Unmarshal(bfjs, &newbftx) 180 | if err != nil { 181 | return &newbftx, err 182 | } 183 | return &newbftx, nil 184 | } 185 | 186 | // SaberDefaultInput provides the saberinput structure with default value 187 | func SaberDefaultInput() Saberinput { 188 | var st Saberinput 189 | _gopath := os.Getenv("GOPATH") 190 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 191 | 192 | st.address = "localhost:22222" 193 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 194 | st.KeyName = "./Data/carol_pri_key.json" 195 | 196 | return st 197 | } 198 | 199 | // Saberinputcli provides interactive interaction for user to use bftx interface 200 | func Saberinputcli(in *os.File) (st Saberinput) { 201 | fmt.Println("Please type your mode: 't' for test mode, 'm' for massconstruct, otherwise type your settings") 202 | if in == nil { 203 | in = os.Stdin 204 | } 205 | reader := bufio.NewReader(in) 206 | txt, _ := reader.ReadString('\n') 207 | txt = strings.Replace(txt, "\n", "", -1) 208 | _gopath := os.Getenv("GOPATH") 209 | _bftxpath := "/src/github.com/blockfreight/go-bftx" 210 | if txt == "t" { 211 | st.mode = "test" 212 | st.address = "localhost:22222" 213 | st.txpath = _gopath + _bftxpath + "/examples/bftx.json" 214 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 215 | // For server run on localhost 216 | st.KeyName = _gopath + _bftxpath + "/examples/carol_pri_key.json" 217 | // For server run on docker 218 | st.KeyName = "./Data/carol_pri_key.json" 219 | } else if txt == "m" { 220 | st.mode = "massconstruct" 221 | st.address = "localhost:22222" 222 | st.txconfigpath = _gopath + _bftxpath + "/examples/config.yaml" 223 | st.KeyName = "./Data/carol_pri_key.json" 224 | } else { 225 | st.mode = txt 226 | fmt.Println("Please type your service host address:") 227 | txt, _ := reader.ReadString('\n') 228 | st.address = strings.Replace(txt, "\n", "", -1) 229 | fmt.Println("Please type your transaction file path:") 230 | txt, _ = reader.ReadString('\n') 231 | st.txpath = strings.Replace(txt, "\n", "", -1) 232 | fmt.Println("Please type your transaction configuration file path:") 233 | txt, _ = reader.ReadString('\n') 234 | st.txconfigpath = strings.Replace(txt, "\n", "", -1) 235 | fmt.Println("Please type your decryption key path:") 236 | txt, _ = reader.ReadString('\n') 237 | st.KeyName = strings.Replace(txt, "\n", "", -1) 238 | } 239 | return st 240 | } 241 | 242 | // SaberEncoding takes an Bftx transaction and returns the saber encoded messages 243 | func SaberEncoding(tx *BFTXTransaction, st Saberinput) (*BFTXTransaction, error) { 244 | txconfig := loadconfiguration(st.txconfigpath) 245 | 246 | bfencreq := BFTX_EncodeRequest{ 247 | Bftxtrans: tx, 248 | Bftxconfig: txconfig, 249 | } 250 | 251 | conn, err := grpc.Dial(st.address, grpc.WithInsecure()) 252 | if err != nil { 253 | return tx, err 254 | } 255 | defer conn.Close() 256 | c := NewBFSaberServiceClient(conn) 257 | 258 | encr, err := c.BFTX_Encode(context.Background(), &bfencreq) 259 | if err != nil { 260 | return tx, err 261 | } 262 | 263 | return encr, nil 264 | } 265 | 266 | // SaberEncodingTestCase is the function that enable it to connect to a container which realizing the 267 | // saber encoding service 268 | func SaberEncodingTestCase(st Saberinput) (*BFTXTransaction, error) { 269 | switch st.mode { 270 | // case "massconstruct": 271 | // err := massSaberEncoding(st) 272 | // return nil, err 273 | default: 274 | tx := loadtransaction(st.txpath) 275 | // txconfig := loadconfiguration(st.txconfigpath) 276 | 277 | // bfencreq := BFTX_EncodeRequest{ 278 | // Bftxtrans: tx, 279 | // Bftxconfig: txconfig, 280 | // } 281 | 282 | // conn, err := grpc.Dial(st.address, grpc.WithInsecure()) 283 | // if err != nil { 284 | // log.Fatalf("%s cannot connected by program: %v", st.address, err) 285 | // } 286 | // defer conn.Close() 287 | // c := NewBFSaberServiceClient(conn) 288 | 289 | // encr, err := c.BFTX_Encode(context.Background(), &bfencreq) 290 | // check(err) 291 | encr, err := SaberEncoding(tx, st) 292 | return encr, err 293 | } 294 | } 295 | 296 | // massSaberEncoding is used for massively load the transaction from the lading.csv file 297 | /* 298 | func massSaberEncoding(st Saberinput) error { 299 | // define the index i 300 | i := 0 301 | wd, err := os.Getwd() 302 | if err != nil { 303 | panic(err) 304 | } 305 | // fmt.Printf(wd + "/examples/Lading.csv") 306 | csvFile, err := os.Open(wd + "/examples/Lading.csv") 307 | if err != nil { 308 | log.Fatal("csv read error:\n", err) 309 | } 310 | 311 | // Define the abci client 312 | abciClient, err := abcicli.NewClient("tcp://127.0.0.1:46658", "socket", true) 313 | if err != nil { 314 | fmt.Println("Error when starting abci client") 315 | log.Fatalf("\n massSaberEncoding Error: %+v \n", err) 316 | } 317 | err = abciClient.Start() 318 | if err != nil { 319 | fmt.Println("Error when initializing abciClient") 320 | log.Fatal(err.Error()) 321 | } 322 | defer abciClient.Stop() 323 | 324 | // Define the rpc client 325 | rpcClient := rpc.NewHTTP("tcp://127.0.0.1:46657", "/websocket") 326 | 327 | err = rpcClient.Start() 328 | if err != nil { 329 | fmt.Println("Error when initializing rpcClient") 330 | log.Fatal(err.Error()) 331 | } 332 | defer rpcClient.Stop() 333 | 334 | // define the grpc client for saber service 335 | conn, err := grpc.Dial(st.address, grpc.WithInsecure()) 336 | if err != nil { 337 | log.Fatalf("%s cannot connected by program: %v", st.address, err) 338 | } 339 | defer conn.Close() 340 | bfsaberclient := NewBFSaberServiceClient(conn) 341 | 342 | txconfig := loadconfiguration(st.txconfigpath) 343 | 344 | reader := csv.NewReader(bufio.NewReader(csvFile)) 345 | 346 | for { 347 | i++ 348 | line, err := reader.Read() 349 | if err == io.EOF { 350 | log.Fatal("io read error", err) 351 | } 352 | if err != nil { 353 | log.Fatal(err) 354 | } 355 | 356 | if len(line) != 22 { 357 | fmt.Printf("breaking line number: %d \n", i) 358 | fmt.Printf("Line has wrong length:%d \n", len(line)) 359 | fmt.Printf("Line: %+v", line) 360 | continue 361 | } 362 | tx := NVCsvConverterNew(line) 363 | 364 | bfencreq := BFTX_EncodeRequest{ 365 | Bftxtrans: tx, 366 | Bftxconfig: txconfig, 367 | } 368 | bfencr, err := bfsaberclient.BFTX_Encode(context.Background(), &bfencreq) 369 | if err != nil { 370 | log.Printf("Line %d, BFTX_Encode error: %v", i, err) 371 | continue 372 | } 373 | 374 | // do the bftx sign-------------------------------------- 375 | oldbf, err := BftxStructConverstionNO(bfencr) 376 | bfmsg := *oldbf 377 | if err != nil { 378 | log.Fatalf("Cannot do the conversion: %v", err) 379 | } 380 | 381 | salt, err := th.GetBlockAppHash(abciClient) 382 | if err != nil { 383 | log.Fatalf("GetBlockAppHash error: %v", err) 384 | } 385 | 386 | // Hash BF_TX Object 387 | hash, err := btx.HashBFTX(bfmsg) 388 | if err != nil { 389 | log.Fatalf("HashBFTX error: %v", err) 390 | } 391 | // Generate BF_TX id 392 | bftxID := btx.HashByteArray(hash, salt) 393 | bfmsg.Id = bftxID 394 | // do the bftx sign-------------------------------------- 395 | 396 | if err = crypto.SignBFTX() 397 | if err != nil { 398 | return err 399 | } 400 | 401 | bfmsg, err = crypto.SignBFTX(bfmsg) 402 | if err != nil { 403 | return err 404 | } 405 | // Change the boolean valud for Transmitted attribute 406 | bfmsg.Transmitted = true 407 | 408 | // Get the BF_TX content in string format 409 | content, err := btx.BFTXContent(bfmsg) 410 | if err != nil { 411 | log.Fatal("BFTXContent error", err) 412 | return err 413 | } 414 | // Update on database 415 | err = leveldb.RecordOnDB(string(bfmsg.Id), content) 416 | if err != nil { 417 | log.Fatal("BFTXContent error", err) 418 | return err 419 | } 420 | 421 | resp, err := rpcClient.BroadcastTxSync([]byte(content)) 422 | if err != nil { 423 | log.Fatal("rpcclient err:", err) 424 | } 425 | // added for flow control 426 | 427 | if i%100 == 0 { 428 | fmt.Print(i, "\n") 429 | fmt.Printf(bfmsg.Id, "\n") 430 | fmt.Printf(": %+v\n", resp) 431 | } else { 432 | fmt.Print(i, ",") 433 | } 434 | 435 | } 436 | return err 437 | 438 | } 439 | */ 440 | // SaberDecodingTestCase is the function that enable it to connect to a container which realizing the 441 | // saber decoding service 442 | func SaberDecoding(tx *BFTXTransaction, st Saberinput) (*BFTXTransaction, error) { 443 | 444 | bfdcpreq := BFTX_DecodeRequest{} 445 | 446 | conn, err := grpc.Dial(st.address, grpc.WithInsecure()) 447 | if err != nil { 448 | return tx, err 449 | } 450 | defer conn.Close() 451 | c := NewBFSaberServiceClient(conn) 452 | 453 | bfdcpreq.Bftxtrans = tx 454 | bfdcpreq.KeyName = st.KeyName 455 | 456 | _, err = fmt.Print("\n==============================\n") 457 | if err != nil { 458 | return tx, err 459 | } 460 | 461 | dcpr, err := c.BFTX_Decode(context.Background(), &bfdcpreq) 462 | if err != nil { 463 | return tx, err 464 | } 465 | fmt.Print(dcpr) 466 | 467 | return dcpr, nil 468 | } 469 | -------------------------------------------------------------------------------- /lib/app/bf_tx/bf_tx.go: -------------------------------------------------------------------------------- 1 | // File: ./blockfreight/lib/bf_tx/bf_tx.go 2 | // Summary: Application code for Blockfreight™ | The blockchain of global freight. 3 | // License: MIT License 4 | // Company: Blockfreight, Inc. 5 | // Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors 6 | // Site: https://blockfreight.com 7 | // Support: 8 | 9 | // Copyright © 2017 Blockfreight, Inc. All Rights Reserved. 10 | 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the "Software"), 13 | // to deal in the Software without restriction, including without limitation 14 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 15 | // and/or sell copies of the Software, and to permit persons to whom the 16 | // Software is furnished to do so, subject to the following conditions: 17 | 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 26 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | 28 | // ================================================================================================================================================= 29 | // ================================================================================================================================================= 30 | // 31 | // BBBBBBBBBBBb lll kkk ffff iii hhh ttt 32 | // BBBB``````BBBB lll kkk fff ``` hhh ttt 33 | // BBBB BBBB lll oooooo ccccccc kkk kkkk fffffff rrr rrr eeeee iii gggggg ggg hhh hhhhh tttttttt 34 | // BBBBBBBBBBBB lll ooo oooo ccc ccc kkk kkk fffffff rrrrrrrr eee eeee iii gggg ggggg hhhh hhhh tttttttt 35 | // BBBBBBBBBBBBBB lll ooo ooo ccc kkkkkkk fff rrrr eeeeeeeeeeeee iii gggg ggg hhh hhh ttt 36 | // BBBB BBB lll ooo ooo ccc kkkk kkkk fff rrr eeeeeeeeeeeee iii ggg ggg hhh hhh ttt 37 | // BBBB BBBB lll oooo oooo cccc ccc kkk kkkk fff rrr eee eee iii ggg gggg hhh hhh tttt .... 38 | // BBBBBBBBBBBBB lll oooooooo ccccccc kkk kkkk fff rrr eeeeeeeee iii gggggg ggg hhh hhh ttttt .... 39 | // ggg ggg 40 | // Blockfreight™ | The blockchain of global freight. ggggggggg 41 | // 42 | // ================================================================================================================================================= 43 | // ================================================================================================================================================= 44 | 45 | // Package bf_tx is a package that defines the Blockfreight™ Transaction (BF_TX) transaction standard 46 | // and provides some useful functions to work with the BF_TX. 47 | package bf_tx 48 | 49 | import ( 50 | // ======================= 51 | // Golang Standard library 52 | // ======================= 53 | "crypto/ecdsa" // Implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3. 54 | "crypto/elliptic" 55 | "crypto/md5" 56 | "crypto/rand" 57 | "crypto/sha256" 58 | "encoding/json" 59 | "errors" // Implements the SHA256 Algorithm for Hash. 60 | "hash" 61 | "io" 62 | "log" 63 | "math/big" 64 | "os" 65 | // Implements encoding and decoding of JSON as defined in RFC 4627. 66 | "net/http" 67 | "strconv" 68 | 69 | "fmt" // Implements formatted I/O with functions analogous to C's printf and scanf. 70 | 71 | // =============== 72 | // Tendermint Core 73 | // =============== 74 | 75 | rpc "github.com/tendermint/tendermint/rpc/client" 76 | //ctypes "github.com/tendermint/tendermint/rpc/core/types" 77 | tmTypes "github.com/tendermint/tendermint/types" 78 | 79 | // ====================== 80 | // Blockfreight™ packages 81 | // ====================== 82 | 83 | "github.com/blockfreight/go-bftx/lib/app/bftx_logger" 84 | "github.com/blockfreight/go-bftx/lib/pkg/common" 85 | "github.com/blockfreight/go-bftx/lib/pkg/leveldb" // Implements common functions for Blockfreight™ 86 | ) 87 | 88 | // SetBFTX receives the path of a JSON, reads it and returns the BF_TX structure with all attributes. 89 | func SetBFTX(jsonpath string) (BF_TX, error) { 90 | var bftx BF_TX 91 | file, err := common.ReadJSON(jsonpath) 92 | if err != nil { 93 | bftx_logger.SimpleLogger("SetBFTX", err) 94 | return bftx, err 95 | } 96 | json.Unmarshal(file, &bftx) 97 | return bftx, nil 98 | } 99 | 100 | //HashBFTX hashes the BF_TX object 101 | func HashBFTX(bftx BF_TX) ([]byte, error) { 102 | bftxBytes := []byte(fmt.Sprintf("%v", bftx)) 103 | 104 | hash := sha256.New() 105 | hash.Write(bftxBytes) 106 | 107 | return hash.Sum(nil), nil 108 | } 109 | 110 | //HashByteArray hashes two byte arrays and returns it. 111 | func HashByteArray(hash []byte, salt []byte) string { 112 | return "BFTX" + fmt.Sprintf("%x", common.HashByteArrays(hash, salt)) 113 | } 114 | 115 | // BFTXContent receives the BF_TX structure, applies it the json.Marshal procedure and return the content of the BF_TX JSON. 116 | func BFTXContent(bftx BF_TX) (string, error) { 117 | jsonContent, err := json.Marshal(bftx) 118 | return string(jsonContent), err 119 | } 120 | 121 | // State reports the current state of a BF_TX 122 | func State(bftx BF_TX) string { 123 | if bftx.Transmitted { 124 | return "Transmitted!" 125 | } else if bftx.Verified { 126 | return "Signed!" 127 | } else { 128 | return "Constructed!" 129 | } 130 | } 131 | 132 | func ByteArrayToBFTX(obj []byte) BF_TX { 133 | var bftx BF_TX 134 | json.Unmarshal(obj, &bftx) 135 | return bftx 136 | } 137 | 138 | func (bftx *BF_TX) GenerateBFTX(origin string) error { 139 | if os.Getenv("LOCAL_RPC_CLIENT_ADDRESS") == "" { 140 | os.Setenv("LOCAL_RPC_CLIENT_ADDRESS", "tcp://localhost:46657") 141 | } 142 | rpcClient := rpc.NewHTTP(os.Getenv("LOCAL_RPC_CLIENT_ADDRESS"), "/websocket") 143 | err := rpcClient.Start() 144 | if err != nil { 145 | log.Println(err.Error()) 146 | bftx_logger.TransLogger("BroadcastBFTX", err, "") 147 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 148 | } 149 | 150 | resInfo, err := rpcClient.ABCIInfo() 151 | if err != nil { 152 | bftx_logger.SimpleLogger("GenerateBFTX", err) 153 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 154 | } 155 | 156 | hash, err := HashBFTX(*bftx) 157 | if err != nil { 158 | bftx_logger.SimpleLogger("GenerateBFTX", err) 159 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 160 | } 161 | 162 | // Generate BF_TX id 163 | bftx.Id = HashByteArray(hash, resInfo.Response.GetLastBlockAppHash()) 164 | 165 | // Get the BF_TX content in string format 166 | content, err := BFTXContent(*bftx) 167 | if err != nil { 168 | bftx_logger.TransLogger("GenerateBFTX", err, bftx.Id) 169 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 170 | } 171 | 172 | // Save on DB 173 | if err = leveldb.RecordOnDB(bftx.Id, content); err != nil { 174 | bftx_logger.TransLogger("GenerateBFTX", err, bftx.Id) 175 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 176 | } 177 | 178 | return nil 179 | } 180 | 181 | func (bftx *BF_TX) SignBFTX(idBftx, origin string) error { 182 | data, err := leveldb.GetBfTx(idBftx) 183 | if err != nil { 184 | if err.Error() == "LevelDB Get function: BF_TX not found." { 185 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 186 | return handleResponse(origin, err, strconv.Itoa(http.StatusNotFound)) 187 | } 188 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 189 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 190 | } 191 | 192 | if err = json.Unmarshal(data, &bftx); err != nil { 193 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 194 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 195 | } 196 | 197 | if bftx.Verified { 198 | return handleResponse(origin, errors.New("Transaction already signed"), strconv.Itoa(http.StatusNotAcceptable)) 199 | } 200 | 201 | // Sign BF_TX 202 | if err = bftx.setSignature(); err != nil { 203 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 204 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 205 | } 206 | 207 | // Get the BF_TX content in string format 208 | content, err := BFTXContent(*bftx) 209 | if err != nil { 210 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 211 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 212 | } 213 | 214 | // Update on DB 215 | if err = leveldb.RecordOnDB(bftx.Id, content); err != nil { 216 | bftx_logger.TransLogger("SignBFTX", err, idBftx) 217 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 218 | } 219 | 220 | return nil 221 | 222 | } 223 | 224 | // SignBFTX has the whole process of signing each BF_TX. 225 | func (bftx *BF_TX) setSignature() error { 226 | content, err := BFTXContent(*bftx) 227 | if err != nil { 228 | bftx_logger.TransLogger("setSignature", err, bftx.Id) 229 | return err 230 | } 231 | 232 | pubkeyCurve := elliptic.P256() //see http://golang.org/pkg/crypto/elliptic/#P256 233 | 234 | privatekey := new(ecdsa.PrivateKey) 235 | privatekey, err = ecdsa.GenerateKey(pubkeyCurve, rand.Reader) // this generates a public & private key pair 236 | if err != nil { 237 | bftx_logger.TransLogger("setSignature", err, bftx.Id) 238 | return err 239 | } 240 | pubkey := privatekey.PublicKey 241 | 242 | // Sign ecdsa style 243 | var h hash.Hash 244 | h = md5.New() 245 | r := big.NewInt(0) 246 | s := big.NewInt(0) 247 | 248 | io.WriteString(h, content) 249 | signhash := h.Sum(nil) 250 | 251 | r, s, err = ecdsa.Sign(rand.Reader, privatekey, signhash) 252 | if err != nil { 253 | bftx_logger.TransLogger("setSignature", err, bftx.Id) 254 | return err 255 | } 256 | 257 | signature := r.Bytes() 258 | signature = append(signature, s.Bytes()...) 259 | 260 | sign := "" 261 | for i, _ := range signature { 262 | sign += strconv.Itoa(int(signature[i])) 263 | } 264 | 265 | // Verification 266 | verifystatus := ecdsa.Verify(&pubkey, signhash, r, s) 267 | 268 | //Set Private Key and Sign to BF_TX 269 | bftx.PrivateKey = *privatekey 270 | bftx.Signhash = signhash 271 | bftx.Signature = sign 272 | bftx.Verified = verifystatus 273 | 274 | return nil 275 | } 276 | 277 | func (bftx *BF_TX) BroadcastBFTX(idBftx, origin string) error { 278 | if os.Getenv("LOCAL_RPC_CLIENT_ADDRESS") == "" { 279 | os.Setenv("LOCAL_RPC_CLIENT_ADDRESS", "tcp://localhost:46657") 280 | } 281 | rpcClient := rpc.NewHTTP(os.Getenv("LOCAL_RPC_CLIENT_ADDRESS"), "/websocket") 282 | err := rpcClient.Start() 283 | if err != nil { 284 | log.Println(err.Error()) 285 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 286 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 287 | } 288 | 289 | // Get a BF_TX by id 290 | data, err := leveldb.GetBfTx(idBftx) 291 | if err != nil { 292 | if err.Error() == "LevelDB Get function: BF_TX not found." { 293 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 294 | return handleResponse(origin, err, strconv.Itoa(http.StatusNotFound)) 295 | } 296 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 297 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 298 | } 299 | 300 | if err = json.Unmarshal(data, &bftx); err != nil { 301 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 302 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 303 | } 304 | 305 | if !bftx.Verified { 306 | return handleResponse(origin, err, strconv.Itoa(http.StatusNotAcceptable)) 307 | } 308 | if bftx.Transmitted { 309 | return handleResponse(origin, err, strconv.Itoa(http.StatusNotAcceptable)) 310 | } 311 | 312 | // Change the boolean valud for Transmitted attribute 313 | bftx.Transmitted = true 314 | 315 | // Get the BF_TX content in string format 316 | content, err := BFTXContent(*bftx) 317 | if err != nil { 318 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 319 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 320 | } 321 | 322 | // Update on DB 323 | if err = leveldb.RecordOnDB(string(bftx.Id), content); err != nil { 324 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 325 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 326 | } 327 | 328 | var tx tmTypes.Tx 329 | tx = []byte(content) 330 | 331 | _, err = rpcClient.BroadcastTxSync(tx) 332 | if err != nil { 333 | fmt.Printf("%+v\n", err) 334 | bftx_logger.TransLogger("BroadcastBFTX", err, idBftx) 335 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 336 | } 337 | 338 | defer rpcClient.Stop() 339 | 340 | return nil 341 | } 342 | 343 | func (bftx *BF_TX) GetBFTX(idBftx, origin string) error { 344 | data, err := leveldb.GetBfTx(idBftx) 345 | if err != nil { 346 | if err.Error() == "LevelDB Get function: BF_TX not found." { 347 | bftx_logger.TransLogger("GetBFTX", err, idBftx) 348 | return handleResponse(origin, err, strconv.Itoa(http.StatusNotFound)) 349 | } 350 | bftx_logger.TransLogger("GetBFTX", err, idBftx) 351 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 352 | } 353 | 354 | json.Unmarshal(data, &bftx) 355 | if err != nil { 356 | bftx_logger.TransLogger("GetBFTX", err, idBftx) 357 | return handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 358 | } 359 | 360 | return nil 361 | 362 | } 363 | 364 | func (bftx *BF_TX) QueryBFTX(idBftx, origin string) ([]BF_TX, error) { 365 | if os.Getenv("LOCAL_RPC_CLIENT_ADDRESS") == "" { 366 | os.Setenv("LOCAL_RPC_CLIENT_ADDRESS", "tcp://localhost:46657") 367 | } 368 | rpcClient := rpc.NewHTTP(os.Getenv("LOCAL_RPC_CLIENT_ADDRESS"), "/websocket") 369 | err := rpcClient.Start() 370 | var bftxs []BF_TX 371 | if err != nil { 372 | log.Println(err.Error()) 373 | // queryLogger("QueryBFTX", err.Error(), idBftx) 374 | bftx_logger.TransLogger("QueryBFTX", err, idBftx) 375 | return nil, handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 376 | } 377 | defer rpcClient.Stop() 378 | query := "bftx.id CONTAINS '" + idBftx + "'" 379 | resQuery, err := rpcClient.TxSearch(query, true, 1, 10) 380 | if err != nil { 381 | bftx_logger.TransLogger("QueryBFTX", err, idBftx) 382 | return nil, handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 383 | } 384 | 385 | if resQuery.TotalCount > 0 { 386 | for _, element := range resQuery.Txs { 387 | 388 | var tx BF_TX 389 | err := json.Unmarshal(element.Tx, &tx) 390 | if err != nil { 391 | bftx_logger.TransLogger("QueryBFTX", err, idBftx) 392 | return nil, handleResponse(origin, err, strconv.Itoa(http.StatusInternalServerError)) 393 | } 394 | bftxs = append(bftxs, tx) 395 | } 396 | 397 | return bftxs, nil 398 | } 399 | 400 | bftx_logger.StringLogger("QueryBFTX", "Transaction not found", idBftx) 401 | return nil, handleResponse(origin, errors.New("Transaction not found"), strconv.Itoa(http.StatusNotFound)) 402 | } 403 | 404 | func (bftx BF_TX) GetTotal() (int, error) { 405 | total, err := leveldb.Total() 406 | if err != nil { 407 | bftx_logger.SimpleLogger("GetTotal", err) 408 | return 0, err 409 | } 410 | 411 | return total, nil 412 | } 413 | 414 | func handleResponse(origin string, err error, httpStatusCode string) error { 415 | if origin == common.ORIGIN_API { 416 | return errors.New(httpStatusCode) 417 | } 418 | return err 419 | } 420 | 421 | // Reinitialize set the default values to the Blockfreight attributes of BF_TX 422 | func Reinitialize(bftx BF_TX) BF_TX { 423 | bftx.PrivateKey.Curve = nil 424 | bftx.PrivateKey.X = nil 425 | bftx.PrivateKey.Y = nil 426 | bftx.PrivateKey.D = nil 427 | bftx.Signhash = nil 428 | bftx.Signature = "" 429 | bftx.Verified = false 430 | bftx.Transmitted = false 431 | return bftx 432 | } 433 | 434 | // BF_TX structure respresents an logical abstraction of a Blockfreight™ Transaction. 435 | type BF_TX struct { 436 | // ========================= 437 | // Bill of Lading attributes 438 | // ========================= 439 | Properties Properties 440 | 441 | // =================================== 442 | // Blockfreight Transaction attributes 443 | // =================================== 444 | Id string `json:"Id"` 445 | PrivateKey ecdsa.PrivateKey `json:"-"` 446 | Signhash []uint8 `json:"Signhash"` 447 | Signature string `json:"Signature"` 448 | Verified bool `json:"Verified"` 449 | Transmitted bool `json:"Transmitted"` 450 | Amendment string `json:"Amendment"` 451 | Private string `json:"Private"` 452 | } 453 | 454 | // Properties struct 455 | /*type Properties struct { 456 | Shipper string `protobuf:"bytes,1,opt,name=Shipper" json:"Shipper"` 457 | BolNum string `protobuf:"varint,1,opt,name=BolNum" json:"BolNum"` 458 | RefNum string `protobuf:"varint,2,opt,name=RefNum" json:"RefNum"` 459 | Consignee string `protobuf:"bytes,2,opt,name=Consignee" json:"Consignee"` 460 | HouseBill string `protobuf:"bytes,3,opt,name=HouseBill" json:"HouseBill"` 461 | Vessel string `protobuf:"varint,3,opt,name=Vessel" json:"Vessel"` 462 | Packages string `protobuf:"varint,4,opt,name=Packages" json:"Packages"` 463 | PackType string `protobuf:"bytes,4,opt,name=PackType" json:"PackType"` 464 | INCOTerms string `protobuf:"bytes,5,opt,name=INCOTerms" json:"INCOTerms"` 465 | PortOfLoading string `protobuf:"bytes,6,opt,name=PortOfLoading" json:"PortOfLoading"` 466 | PortOfDischarge string `protobuf:"bytes,7,opt,name=PortOfDischarge" json:"PortOfDischarge"` 467 | Destination string `protobuf:"bytes,8,opt,name=Destination" json:"Destination"` 468 | MarksAndNumbers string `protobuf:"bytes,9,opt,name=MarksAndNumbers" json:"MarksAndNumbers"` 469 | UnitOfWeight string `protobuf:"bytes,10,opt,name=UnitOfWeight" json:"UnitOfWeight"` 470 | DeliverAgent string `protobuf:"bytes,11,opt,name=DeliverAgent" json:"DeliverAgent"` 471 | ReceiveAgent string `protobuf:"bytes,12,opt,name=ReceiveAgent" json:"ReceiveAgent"` 472 | Container string `protobuf:"bytes,13,opt,name=Container" json:"Container"` 473 | ContainerSeal string `protobuf:"bytes,14,opt,name=ContainerSeal" json:"ContainerSeal"` 474 | ContainerMode string `protobuf:"bytes,15,opt,name=ContainerMode" json:"ContainerMode"` 475 | ContainerType string `protobuf:"bytes,16,opt,name=ContainerType" json:"ContainerType"` 476 | Volume string `protobuf:"bytes,17,opt,name=Volume" json:"Volume"` 477 | UnitOfVolume string `protobuf:"bytes,18,opt,name=UnitOfVolume" json:"UnitOfVolume"` 478 | NotifyAddress string `protobuf:"bytes,19,opt,name=NotifyAddress" json:"NotifyAddress"` 479 | DescOfGoods string `protobuf:"bytes,20,opt,name=DescOfGoods" json:"DescOfGoods"` 480 | GrossWeight string `protobuf:"varint,5,opt,name=GrossWeight" json:"GrossWeight"` 481 | FreightPayableAmt string `protobuf:"varint,6,opt,name=FreightPayableAmt" json:"FreightPayableAmt"` 482 | FreightAdvAmt string `protobuf:"varint,7,opt,name=FreightAdvAmt" json:"FreightAdvAmt"` 483 | GeneralInstructions string `protobuf:"bytes,21,opt,name=GeneralInstructions" json:"GeneralInstructions"` 484 | DateShipped string `protobuf:"bytes,22,opt,name=DateShipped" json:"DateShipped"` 485 | IssueDetails IssueDetails `json:"IssueDetails"` 486 | NumBol string `protobuf:"varint,8,opt,name=NumBol" json:"NumBol"` 487 | MasterInfo MasterInfo `json:"MasterInfo"` 488 | AgentForMaster AgentMaster `json:"AgentForMaster"` 489 | AgentForOwner AgentOwner `json:"AgentForOwner"` 490 | EncryptionMetaData string `json:"EncryptionMetaData"` 491 | }*/ 492 | 493 | type Properties struct { 494 | // Consol Level 495 | Consol Consol 496 | // Shipment Level 497 | Shipment Shipment 498 | // Extension 499 | Extension Extension 500 | } 501 | 502 | type Extension struct { 503 | ServiceLevel string 504 | } 505 | 506 | type Consol struct { 507 | Masterbill string 508 | ContainerMode string 509 | PaymentMethod string 510 | PortOfDischarge string 511 | PortOfLoading string 512 | ShipmentType string 513 | TransportMode string 514 | VesselName string 515 | VoyageFlightNo string 516 | EstimatedTimeOfDeparture string 517 | EstimatedTimeOfArrival string 518 | Carrier string 519 | ContainerNumber string 520 | ContainerType string 521 | DeliveryMode string 522 | Seal string 523 | } 524 | 525 | type Shipment struct { 526 | Housebill string 527 | ContainerMode string 528 | GoodsDescription string 529 | MarksAndNumbers string 530 | HBLAWBChargesDisplay string 531 | PackQuantity string 532 | PackType string 533 | Weight string 534 | Volume string 535 | ShippedOnBoard string 536 | TransportMode string 537 | EstimatedTimeOfDeparture string 538 | EstimatedTimeOfArrival string 539 | Consignee string 540 | Consignor string 541 | PackingLineCommodity string 542 | ContainerNumber string 543 | INCOTERM string 544 | ShipmentType string 545 | ReleaseType string 546 | } 547 | 548 | // Date struct 549 | type Date struct { 550 | Type string 551 | Format string 552 | } 553 | 554 | // IssueDetails struct 555 | type IssueDetails struct { 556 | PlaceOfIssue string `json:"PlaceOfIssue"` 557 | DateOfIssue string `json:"DateOfIssue"` 558 | } 559 | 560 | // MasterInfo struct 561 | type MasterInfo struct { 562 | FirstName string `json:"FirstName"` 563 | LastName string `json:"LastName"` 564 | Sig string `json:"Sig"` 565 | } 566 | 567 | // AgentMaster struct 568 | type AgentMaster struct { 569 | FirstName string `json:"FirstName"` 570 | LastName string `json:"LastName"` 571 | Sig string `json:"Sig"` 572 | } 573 | 574 | // AgentOwner struct 575 | type AgentOwner struct { 576 | FirstName string `json:"FirstName"` 577 | LastName string `json:"LastName"` 578 | Sig string `json:"Sig"` 579 | ConditionsForCarriage string `json:"ConditionsForCarriage"` 580 | } 581 | 582 | // ================================================= 583 | // Blockfreight™ | The blockchain of global freight. 584 | // ================================================= 585 | 586 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 587 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 588 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 589 | // BBBBBBB BBBBBBBBBBBBBBBBBBB 590 | // BBBBBBB BBBBBBBBBBBBBBBB 591 | // BBBBBBB BBBBBBBBBBBBBBB 592 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 593 | // BBBBBBB BBBBBBBBB BBBBBBBBBBBBBBB 594 | // BBBBBBB BBBBBBB BBBBBBBBBBBBBBBB 595 | // BBBBBBB BBBBBBBBBBBBBBBBBB 596 | // BBBBBBB BBBBBBBBBBBBBBB 597 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 598 | // BBBBBBB BBBBBBBBBBB BBBBBBBBBBBBBB 599 | // BBBBBBB BBBBBBBBBB BBBBBBBBBBBBBB 600 | // BBBBBBB BBBBBBBBB BBB BBBBB 601 | // BBBBBBB BBBB BBBBB 602 | // BBBBBBB BBBBBBB BBBBB 603 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 604 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 605 | // BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 606 | 607 | // ================================================== 608 | // Blockfreight™ | The blockchain for global freight. 609 | // ================================================== 610 | --------------------------------------------------------------------------------