mirror of
https://github.com/arnaucube/go-dvote.git
synced 2026-02-27 21:16:43 +01:00
Merge remote-tracking branch 'census/master'
Signed-off-by: p4u <p4u@dabax.net>
This commit is contained in:
131
LICENSE
131
LICENSE
@@ -1,5 +1,10 @@
|
||||
<<<<<<< HEAD
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
=======
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
>>>>>>> census/master
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
@@ -7,6 +12,7 @@
|
||||
|
||||
Preamble
|
||||
|
||||
<<<<<<< HEAD
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
@@ -16,6 +22,19 @@ to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
=======
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
>>>>>>> census/master
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
@@ -24,6 +43,7 @@ them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
<<<<<<< HEAD
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
@@ -52,6 +72,46 @@ published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
=======
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
>>>>>>> census/master
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
@@ -60,7 +120,11 @@ modification follow.
|
||||
|
||||
0. Definitions.
|
||||
|
||||
<<<<<<< HEAD
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
=======
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
>>>>>>> census/master
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
@@ -537,6 +601,7 @@ to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
<<<<<<< HEAD
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
@@ -557,25 +622,54 @@ combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
=======
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
>>>>>>> census/master
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
<<<<<<< HEAD
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
=======
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
>>>>>>> census/master
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
<<<<<<< HEAD
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
=======
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
>>>>>>> census/master
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
@@ -633,20 +727,32 @@ the "copyright" line and a pointer to where the full notice is found.
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
<<<<<<< HEAD
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
=======
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
>>>>>>> census/master
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
<<<<<<< HEAD
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
=======
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
>>>>>>> census/master
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
<<<<<<< HEAD
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
@@ -659,3 +765,28 @@ specific requirements.
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
=======
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
>>>>>>> census/master
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
# votingRelay
|
||||
# go-dvote
|
||||
|
||||
|
||||
## votingRelay
|
||||
|
||||
dVote library for Relay
|
||||
|
||||
@@ -9,3 +12,6 @@ and in another shell:
|
||||
./generator/generator 1000
|
||||
|
||||
|
||||
## dVote-census
|
||||
|
||||
Library to work with the creation and management of vocdoni census
|
||||
|
||||
128
cmd/censushttp/README.md
Normal file
128
cmd/censushttp/README.md
Normal file
@@ -0,0 +1,128 @@
|
||||
## Census HTTP service
|
||||
|
||||
Reference implementation of a voting census service running on the Vocdoni platform
|
||||
|
||||
## Compile
|
||||
|
||||
In a GO ready environment:
|
||||
|
||||
```
|
||||
go get -u github.com/vocdoni/dvote-census/...
|
||||
go build -o censusHttpService github.com/vocdoni/dvote-census/cmd/censushttp
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`./censusHttpService <port> <censusId>[:pubKey] [<censusId>[:pubKey] ...]`
|
||||
|
||||
Example
|
||||
|
||||
```
|
||||
./censusHttpService 1500 Got_Favorite
|
||||
2019/02/12 10:20:16 Starting process HTTP service on port 1500 for namespace GoT_Favorite
|
||||
2019/02/12 10:20:16 Starting server in http mode
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
A HTTP jSON endpoint is available with the following possible fields: `censusId`, `claimData`, `rootHash` and `proofData`.
|
||||
|
||||
If `pubKey` has been configured for a specific `censusId`, then two more methods are available (`timeStamp` and `signature`) to provide authentication.
|
||||
|
||||
The next table shows the available methods and its relation with the fields.
|
||||
|
||||
| method | censusId | claimData | rootHash | proofData | protected? | description |
|
||||
|------------|-----------|-----------|----------|-----------|------------|------------|
|
||||
| `addCLaim` | mandatory | mandatory | none | none | yes | adds a new claim to the merkle tree |
|
||||
| `getRoot` | mandatory | none | none | none | no | get the current merkletree root hash
|
||||
| `genProof` | mandatory | mandatory | optional | none | no | generate the merkle proof for a given claim
|
||||
| `checkProof` | mandatory | mandatory | optional | mandatory | no | check a claim and its merkle proof
|
||||
| `getIdx` | mandatory | mandatory | optional | none | no | get the merkletree data index of a given claim
|
||||
| `dump` | mandatory | none | optional | none | yes | list the contents of the census for a given hash
|
||||
|
||||
|
||||
## Signature
|
||||
|
||||
The signature provides authentication by signing a concatenation of the following strings (even if empty) without spaces: `censusId rootHash claimData timeStamp`.
|
||||
|
||||
The `timeStamp` when received on the server side must not differ more than 10 seconds from the current UNIX time.
|
||||
|
||||
## Examples
|
||||
|
||||
#### add claims
|
||||
|
||||
Add two new claims, one for `Jon Snow` and another for `Tyrion`.
|
||||
```
|
||||
curl -d '{"censusID":"GoT_Favorite","claimData":"Jon Snow"}' http://localhost:1500/addClaim
|
||||
|
||||
{"error":false,"response":""}
|
||||
```
|
||||
|
||||
```
|
||||
curl -d '{"censusID":"GoT_Favorite","claimData":"Tyrion"}' http://localhost:1500/addClaim
|
||||
|
||||
{"error":false,"response":""}
|
||||
```
|
||||
|
||||
In case signature is enabled:
|
||||
|
||||
```
|
||||
curl -d '{
|
||||
"censusID":"GoT_Favorite",
|
||||
"claimData":"Jon Snow",
|
||||
"timeStamp":"1547814675",
|
||||
"signature":"a117c4ce12b29090884112ffe57e664f007e7ef142a1679996e2d34fd2b852fe76966e47932f1e9d3a54610d0f361383afe2d9aab096e15d136c236abb0a0d0e" }' http://localhost:1500/addClaim
|
||||
|
||||
{"error":false,"response":""}
|
||||
```
|
||||
|
||||
|
||||
#### generate proof
|
||||
|
||||
Generate a merkle proof for the claim `Jon Snow`
|
||||
|
||||
```
|
||||
curl -d '{"censusID":"GoT_Favorite","claimData":"Jon Snow"}' http://localhost:1500/genProof
|
||||
|
||||
{"error":false,"response":"0x000200000000000000000000000000000000000000000000000000000000000212f8134039730791388a9bd0460f9fbd0757327212a64b3a2b0f0841ce561ee3"}
|
||||
```
|
||||
|
||||
If `rootHash` is specified, the proof will be calculated for the given root hash.
|
||||
|
||||
#### get root
|
||||
|
||||
The previous merkle proof is valid only for the current root hash. Let's get it
|
||||
|
||||
```
|
||||
curl -d '{"censusID":"GoT_Favorite"}' http://localhost:1500/getRoot
|
||||
|
||||
{"error":false,"response":"0x2f0ddde5cb995eae23dc3b75a5c0333f1cc89b73f3a00b0fe71996fb90fef04b"}
|
||||
```
|
||||
|
||||
|
||||
#### check proof
|
||||
|
||||
Now let's check if the proof is valid
|
||||
|
||||
```
|
||||
curl -d '{
|
||||
"censusID":"GoT_Favorite","claimData":"Jon Snow",
|
||||
"rootHash":"0x2f0ddde5cb995eae23dc3b75a5c0333f1cc89b73f3a00b0fe71996fb90fef04b",
|
||||
"proofData":"0x000200000000000000000000000000000000000000000000000000000000000212f8134039730791388a9bd0460f9fbd0757327212a64b3a2b0f0841ce561ee3"}' http://localhost:1500/checkProof
|
||||
|
||||
{"error":false,"response":"valid"}
|
||||
```
|
||||
|
||||
If `rootHash` is not specified, the current root hash is used.
|
||||
|
||||
#### dump
|
||||
|
||||
Dump contents of a specific censusId (values)
|
||||
|
||||
```
|
||||
curl -d '{"censusID":"GoT_Favorite"}' http://localhost:1500/dump
|
||||
|
||||
{"error":false,"response":"[\"Tyrion\",\"Jon Snow\"]"}
|
||||
```
|
||||
|
||||
If `rootHash` is specified, dump will return the values for the merkle tree with the given root hash.
|
||||
37
cmd/censushttp/censushttp.go
Normal file
37
cmd/censushttp/censushttp.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
censusmanager "github.com/vocdoni/dvote-census/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
log.Fatal("Usage: " + os.Args[0] +
|
||||
" <port> <namespace>[:pubKey] [<namespace>[:pubKey]]...")
|
||||
os.Exit(2)
|
||||
}
|
||||
port, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
os.Exit(2)
|
||||
}
|
||||
for i := 2; i < len(os.Args); i++ {
|
||||
s := strings.Split(os.Args[i], ":")
|
||||
ns := s[0]
|
||||
pubK := ""
|
||||
if len(s) > 1 {
|
||||
pubK = s[1]
|
||||
log.Printf("Public Key authentication enabled on namespace %s\n", ns)
|
||||
}
|
||||
censusmanager.AddNamespace(ns, pubK)
|
||||
log.Printf("Starting process HTTP service on port %d for namespace %s\n",
|
||||
port, ns)
|
||||
}
|
||||
censusmanager.Listen(port, "http")
|
||||
|
||||
}
|
||||
309
service/censusmanager.go
Normal file
309
service/censusmanager.go
Normal file
@@ -0,0 +1,309 @@
|
||||
package censusmanager
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tree "github.com/vocdoni/dvote-census/tree"
|
||||
signature "github.com/vocdoni/dvote-relay/crypto/signature"
|
||||
)
|
||||
|
||||
const hashSize = 32
|
||||
const authTimeWindow = 10 // Time window (seconds) in which TimeStamp will be accepted if auth enabled
|
||||
var MkTrees map[string]*tree.Tree // MerkleTree dvote-census library
|
||||
var Signatures map[string]string
|
||||
var Signature signature.SignKeys // Signature dvote-relay library
|
||||
|
||||
type Claim struct {
|
||||
CensusID string `json:"censusId"` // References to MerkleTree namespace
|
||||
RootHash string `json:"rootHash"` // References to MerkleTree rootHash
|
||||
ClaimData string `json:"claimData"` // Data to add to the MerkleTree
|
||||
ProofData string `json:"proofData"` // MerkleProof to check
|
||||
TimeStamp string `json:"timeStamp"` // Unix TimeStamp in seconds
|
||||
Signature string `json:"signature"` // Signature as Hexadecimal String
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Error bool `json:"error"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
func AddNamespace(name, pubKey string) {
|
||||
if len(MkTrees) == 0 {
|
||||
MkTrees = make(map[string]*tree.Tree)
|
||||
}
|
||||
if len(Signatures) == 0 {
|
||||
Signatures = make(map[string]string)
|
||||
}
|
||||
|
||||
mkTree := tree.Tree{}
|
||||
mkTree.Init(name)
|
||||
MkTrees[name] = &mkTree
|
||||
Signatures[name] = pubKey
|
||||
}
|
||||
|
||||
func reply(resp *Result, w http.ResponseWriter) {
|
||||
err := json.NewEncoder(w).Encode(resp)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
} else {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
}
|
||||
}
|
||||
|
||||
func checkRequest(w http.ResponseWriter, req *http.Request) bool {
|
||||
if req.Body == nil {
|
||||
http.Error(w, "Please send a request body", 400)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func checkAuth(timestamp, signature, pubKey, message string) bool {
|
||||
if len(pubKey) < 1 {
|
||||
return true
|
||||
}
|
||||
currentTime := int64(time.Now().Unix())
|
||||
timeStampRemote, err := strconv.ParseInt(timestamp, 10, 32)
|
||||
if err != nil {
|
||||
log.Printf("Cannot parse timestamp data %s\n", err)
|
||||
return false
|
||||
}
|
||||
if timeStampRemote < currentTime+authTimeWindow &&
|
||||
timeStampRemote > currentTime-authTimeWindow {
|
||||
v, err := Signature.Verify(message, signature, pubKey)
|
||||
if err != nil {
|
||||
log.Printf("Verification error: %s\n", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func claimHandler(w http.ResponseWriter, req *http.Request, op string) {
|
||||
var c Claim
|
||||
var resp Result
|
||||
|
||||
if ok := checkRequest(w, req); !ok {
|
||||
return
|
||||
}
|
||||
// Decode JSON
|
||||
err := json.NewDecoder(req.Body).Decode(&c)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
|
||||
// Process data
|
||||
log.Printf("censusId:{%s} rootHash:{%s} claimData:{%s} proofData:{%s} timeStamp:{%s} signature:{%s}\n",
|
||||
c.CensusID, c.RootHash, c.ClaimData, c.ProofData, c.TimeStamp, c.Signature)
|
||||
authString := fmt.Sprintf("%s%s%s%s", c.CensusID, c.RootHash, c.ClaimData, c.TimeStamp)
|
||||
resp.Error = false
|
||||
resp.Response = ""
|
||||
censusFound := false
|
||||
if len(c.CensusID) > 0 {
|
||||
_, censusFound = MkTrees[c.CensusID]
|
||||
}
|
||||
if !censusFound {
|
||||
resp.Error = true
|
||||
resp.Response = "censusId not valid or not found"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
|
||||
if op == "add" {
|
||||
if auth := checkAuth(c.TimeStamp, c.Signature, Signatures[c.CensusID], authString); auth {
|
||||
err = MkTrees[c.CensusID].AddClaim([]byte(c.ClaimData))
|
||||
} else {
|
||||
resp.Error = true
|
||||
resp.Response = "invalid authentication"
|
||||
}
|
||||
}
|
||||
|
||||
if op == "gen" {
|
||||
var t *tree.Tree
|
||||
var err error
|
||||
if len(c.RootHash) > 1 { //if rootHash specified
|
||||
t, err = MkTrees[c.CensusID].Snapshot(c.RootHash)
|
||||
if err != nil {
|
||||
log.Printf("Snapshot error: %s", err.Error())
|
||||
resp.Error = true
|
||||
resp.Response = "invalid root hash"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
} else { //if rootHash not specified use current tree
|
||||
t = MkTrees[c.CensusID]
|
||||
}
|
||||
resp.Response, err = t.GenProof([]byte(c.ClaimData))
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Response = err.Error()
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if op == "root" {
|
||||
resp.Response = MkTrees[c.CensusID].GetRoot()
|
||||
}
|
||||
|
||||
if op == "idx" {
|
||||
|
||||
}
|
||||
|
||||
if op == "dump" {
|
||||
var t *tree.Tree
|
||||
if auth := checkAuth(c.TimeStamp, c.Signature, Signatures[c.CensusID], authString); !auth {
|
||||
resp.Error = true
|
||||
resp.Response = "invalid authentication"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
|
||||
if len(c.RootHash) > 1 { //if rootHash specified
|
||||
t, err = MkTrees[c.CensusID].Snapshot(c.RootHash)
|
||||
if err != nil {
|
||||
log.Printf("Snapshot error: %s", err.Error())
|
||||
resp.Error = true
|
||||
resp.Response = "invalid root hash"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
} else { //if rootHash not specified use current merkletree
|
||||
t = MkTrees[c.CensusID]
|
||||
}
|
||||
|
||||
//dump the claim data and return it
|
||||
values, err := t.Dump()
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Response = err.Error()
|
||||
} else {
|
||||
jValues, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Response = err.Error()
|
||||
} else {
|
||||
resp.Response = fmt.Sprintf("%s", jValues)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if op == "check" {
|
||||
if len(c.ProofData) < 1 {
|
||||
resp.Error = true
|
||||
resp.Response = "proofData not provided"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
var t *tree.Tree
|
||||
if len(c.RootHash) > 1 { //if rootHash specified
|
||||
t, err = MkTrees[c.CensusID].Snapshot(c.RootHash)
|
||||
if err != nil {
|
||||
log.Printf("Snapshot error: %s", err.Error())
|
||||
resp.Error = true
|
||||
resp.Response = "invalid root hash"
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
} else { //if rootHash not specified use current merkletree
|
||||
t = MkTrees[c.CensusID]
|
||||
}
|
||||
|
||||
validProof, err := t.CheckProof([]byte(c.ClaimData), c.ProofData)
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Response = err.Error()
|
||||
reply(&resp, w)
|
||||
return
|
||||
}
|
||||
if validProof {
|
||||
resp.Response = "valid"
|
||||
} else {
|
||||
resp.Response = "invalid"
|
||||
}
|
||||
}
|
||||
|
||||
reply(&resp, w)
|
||||
}
|
||||
|
||||
func addCorsHeaders(w *http.ResponseWriter, req *http.Request) {
|
||||
(*w).Header().Set("Access-Control-Allow-Origin", "*")
|
||||
(*w).Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||
}
|
||||
|
||||
func Listen(port int, proto string) {
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", port),
|
||||
ReadHeaderTimeout: 4 * time.Second,
|
||||
ReadTimeout: 4 * time.Second,
|
||||
WriteTimeout: 4 * time.Second,
|
||||
IdleTimeout: 3 * time.Second,
|
||||
}
|
||||
|
||||
http.HandleFunc("/addClaim", func(w http.ResponseWriter, r *http.Request) {
|
||||
addCorsHeaders(&w, r)
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
claimHandler(w, r, "add")
|
||||
} else if r.Method != http.MethodOptions {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
http.HandleFunc("/genProof", func(w http.ResponseWriter, r *http.Request) {
|
||||
addCorsHeaders(&w, r)
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
claimHandler(w, r, "gen")
|
||||
} else if r.Method != http.MethodOptions {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
http.HandleFunc("/checkProof", func(w http.ResponseWriter, r *http.Request) {
|
||||
addCorsHeaders(&w, r)
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
claimHandler(w, r, "check")
|
||||
} else if r.Method != http.MethodOptions {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
http.HandleFunc("/getRoot", func(w http.ResponseWriter, r *http.Request) {
|
||||
addCorsHeaders(&w, r)
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
claimHandler(w, r, "root")
|
||||
} else if r.Method != http.MethodOptions {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
http.HandleFunc("/dump", func(w http.ResponseWriter, r *http.Request) {
|
||||
addCorsHeaders(&w, r)
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
claimHandler(w, r, "dump")
|
||||
} else if r.Method != http.MethodOptions {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
|
||||
if proto == "https" {
|
||||
log.Print("Starting server in https mode")
|
||||
if err := srv.ListenAndServeTLS("server.crt", "server.key"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
if proto == "http" {
|
||||
log.Print("Starting server in http mode")
|
||||
srv.SetKeepAlivesEnabled(false)
|
||||
if err := srv.ListenAndServe(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
22
tree/README.md
Normal file
22
tree/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
## dvote Tree
|
||||
|
||||
Implementation of dvote tree structure. Currently based on iden3 merkle tree.
|
||||
|
||||
Example of usage:
|
||||
|
||||
```
|
||||
T := tree.Tree
|
||||
if T.Init() != nil { fmt.Println("Cannot create tree database") }
|
||||
err := T.AddClaim([]byte("Hello you!"))
|
||||
if err != nil {
|
||||
fmt.Println("Claim already exist")
|
||||
}
|
||||
mpHex, err := T.GenProof([]byte("Hello you!"))
|
||||
fmt.Println(mpHex)
|
||||
fmt.Println(T.CheckProof([]byte("Hello you!"), mpHex))
|
||||
T.Close()
|
||||
```
|
||||
|
||||
#### To-Do
|
||||
|
||||
Avoid duplicates on dump/snapshot
|
||||
138
tree/tree.go
Normal file
138
tree/tree.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package tree
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/user"
|
||||
|
||||
common3 "github.com/iden3/go-iden3/common"
|
||||
mkcore "github.com/iden3/go-iden3/core"
|
||||
db "github.com/iden3/go-iden3/db"
|
||||
merkletree "github.com/iden3/go-iden3/merkletree"
|
||||
)
|
||||
|
||||
type Tree struct {
|
||||
Storage string
|
||||
Tree *merkletree.MerkleTree
|
||||
DbStorage *db.LevelDbStorage
|
||||
}
|
||||
|
||||
func (t *Tree) Init(namespace string) error {
|
||||
if len(t.Storage) < 1 {
|
||||
if len(namespace) < 1 {
|
||||
return errors.New("namespace not valid")
|
||||
}
|
||||
usr, err := user.Current()
|
||||
if err == nil {
|
||||
t.Storage = usr.HomeDir + "/.dvote/census/" + namespace
|
||||
} else {
|
||||
t.Storage = "./dvoteTree/" + namespace
|
||||
}
|
||||
}
|
||||
mtdb, err := db.NewLevelDbStorage(t.Storage, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mt, err := merkletree.NewMerkleTree(mtdb, 140)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.DbStorage = mtdb
|
||||
t.Tree = mt
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Tree) Close() {
|
||||
defer t.Tree.Storage().Close()
|
||||
}
|
||||
|
||||
func (t *Tree) GetClaim(data []byte) (*mkcore.ClaimBasic, error) {
|
||||
if len(data) > 496/8 {
|
||||
return nil, errors.New("claim data too large")
|
||||
}
|
||||
for i := len(data); i <= 496/8; i++ {
|
||||
data = append(data, '\x00')
|
||||
}
|
||||
var indexSlot [400 / 8]byte
|
||||
var dataSlot [496 / 8]byte
|
||||
copy(indexSlot[:], data[:400/8])
|
||||
copy(dataSlot[:], data[:496/8])
|
||||
e := mkcore.NewClaimBasic(indexSlot, dataSlot)
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func (t *Tree) AddClaim(data []byte) error {
|
||||
e, err := t.GetClaim(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.Tree.Add(e.Entry())
|
||||
}
|
||||
|
||||
func (t *Tree) GenProof(data []byte) (string, error) {
|
||||
e, err := t.GetClaim(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
mp, err := t.Tree.GenerateProof(e.Entry().HIndex())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
mpHex := common3.HexEncode(mp.Bytes())
|
||||
return mpHex, nil
|
||||
}
|
||||
|
||||
func (t *Tree) CheckProof(data []byte, mpHex string) (bool, error) {
|
||||
mpBytes, err := common3.HexDecode(mpHex)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
mp, err := merkletree.NewProofFromBytes(mpBytes)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
e, err := t.GetClaim(data)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return merkletree.VerifyProof(t.Tree.RootKey(), mp,
|
||||
e.Entry().HIndex(), e.Entry().HValue()), nil
|
||||
}
|
||||
|
||||
func (t *Tree) GetRoot() string {
|
||||
return common3.HexEncode(t.Tree.RootKey().Bytes())
|
||||
}
|
||||
|
||||
func (t *Tree) GetIndex(data []byte) (string, error) {
|
||||
e, err := t.GetClaim(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
index, err := t.Tree.GetDataByIndex(e.Entry().HIndex())
|
||||
return index.String(), err
|
||||
}
|
||||
|
||||
func (t *Tree) Dump() ([]string, error) {
|
||||
var response []string
|
||||
err := t.Tree.Walk(nil, func(n *merkletree.Node) {
|
||||
if n.Type == merkletree.NodeTypeLeaf {
|
||||
data := bytes.Trim(n.Value()[65:], "\x00")
|
||||
response = append(response, fmt.Sprintf("%s", data))
|
||||
}
|
||||
})
|
||||
return response, err
|
||||
}
|
||||
|
||||
func (t *Tree) Snapshot(root string) (*Tree, error) {
|
||||
var rootHash merkletree.Hash
|
||||
snapshotTree := new(Tree)
|
||||
rootBytes, err := common3.HexDecode(root)
|
||||
if err != nil {
|
||||
return snapshotTree, err
|
||||
}
|
||||
copy(rootHash[:32], rootBytes)
|
||||
mt, err := t.Tree.Snapshot(&rootHash)
|
||||
snapshotTree.Tree = mt
|
||||
return snapshotTree, err
|
||||
}
|
||||
Reference in New Issue
Block a user