// propagateSkipBlock saves a new skipblock to the identity func (s *Service) propagateSkipBlockHandler(msg network.Body) { log.Lvlf4("Got msg %+v %v", msg, reflect.TypeOf(msg).String()) usb, ok := msg.(*UpdateSkipBlock) if !ok { log.Error("Wrong message-type") return } sid := s.getIdentityStorage(usb.ID) if sid == nil { log.Error("Didn't find entity in", s) return } sid.Lock() defer sid.Unlock() skipblock := msg.(*UpdateSkipBlock).Latest _, msgLatest, err := network.UnmarshalRegistered(skipblock.Data) if err != nil { log.Error(err) return } al, ok := msgLatest.(*Config) if !ok { log.Error(err) return } sid.Data = skipblock sid.Latest = al sid.Proposed = nil }
// Run starts the simulation on the simulation-side func (e *Simulation) Run(config *onet.SimulationConfig) error { msg := []byte(e.Message) size := config.Tree.Size() log.Lvl2("Size is:", size, "rounds:", e.Rounds) for round := 0; round < e.Rounds; round++ { log.Lvl1("Starting round", round, "with message", string(msg)) round := monitor.NewTimeMeasure("round") p, err := config.Overlay.CreateProtocolOnet("NaiveTree", config.Tree) if err != nil { log.Error("Quitting the simulation....", err) return err } pi := p.(*Protocol) pi.Message = msg pi.verifySignature = e.Checking done := make(chan bool) pi.TreeNodeInstance.OnDoneCallback(func() bool { done <- true return true }) err = pi.Start() if err != nil { log.Error("Quitting the simulation....", err) return err } <-done round.Record() } return nil }
// If 'r' is nil, it will starts the response process. func (bft *ProtocolBFTCoSi) handleResponsePrepare(r *Response) error { if r != nil { // check if we have enough responses bft.tmpMutex.Lock() bft.tempPrepareResponse = append(bft.tempPrepareResponse, r.Response) bft.tempExceptions = append(bft.tempExceptions, r.Exceptions...) if len(bft.tempPrepareResponse) < len(bft.Children()) { bft.tmpMutex.Unlock() return nil } bft.tmpMutex.Unlock() } // wait for verification bzrReturn, ok := bft.waitResponseVerification() // append response if !ok { log.Lvl2(bft.Roster(), "Refused to sign") } // Return if we're not root if !bft.IsRoot() { return bft.SendTo(bft.Parent(), bzrReturn) } // Since cosi does not support exceptions yet, we have to remove // the responses that are not supposed to be there,i.e. exceptions. cosiSig := bft.prepare.Signature() correctResponseBuff, err := bzrReturn.Response.MarshalBinary() if err != nil { return err } // replace the old one with the corrected one copy(cosiSig[32:64], correctResponseBuff) bft.prepareSignature = cosiSig // Verify the signature is correct data := sha512.Sum512(bft.Msg) sig := &BFTSignature{ Msg: data[:], Sig: cosiSig, Exceptions: bft.tempExceptions, } aggCommit := bft.Suite().Point().Null() for _, c := range bft.tempPrepareCommit { aggCommit.Add(aggCommit, c) } if err := sig.Verify(bft.Suite(), bft.Roster().Publics()); err != nil { log.Error(bft.Name(), "Verification of the signature failed:", err) bft.signRefusal = true } log.Lvl3(bft.Name(), "Verification of signature successful") // Start the challenge of the 'commit'-round if err := bft.startChallenge(RoundCommit); err != nil { log.Error(bft.Name(), err) return err } return nil }
func (jv *JVSS) finaliseSecret(sid SID) error { secret, err := jv.secrets.secret(sid) if err != nil { return err } log.Lvlf4("Node %d: %s deals %d/%d", jv.Index(), sid, len(secret.deals), len(jv.List())) if len(secret.deals) == jv.info.T { for _, deal := range secret.deals { if _, err := secret.receiver.AddDeal(jv.Index(), deal); err != nil { log.Error(jv.Index(), err) return err } } sec, err := secret.receiver.ProduceSharedSecret() if err != nil { return err } secret.secret = sec isShortTermSecret := strings.HasPrefix(string(sid), string(STSS)) if isShortTermSecret { secret.nShortConfirmsMtx.Lock() defer secret.nShortConfirmsMtx.Unlock() secret.numShortConfs++ } else { secret.nLongConfirmsMtx.Lock() defer secret.nLongConfirmsMtx.Unlock() secret.numLongtermConfs++ } log.Lvlf4("Node %d: %v created", jv.Index(), sid) // Initialise Schnorr struct for long-term shared secret if not done so before if sid.IsLTSS() && !jv.ltssInit { jv.ltssInit = true jv.schnorr.Init(jv.keyPair.Suite, jv.info, secret.secret) log.Lvlf4("Node %d: %v Schnorr struct initialised", jv.Index(), sid) } // Broadcast that we have finished setting up our shared secret msg := &SecConfMsg{ Src: jv.Index(), SID: sid, } if err := jv.Broadcast(msg); err != nil { log.Error(err) return err } } return nil }
// saves the actual identity func (s *Service) save() { log.Lvl3("Saving service") b, err := network.MarshalRegisteredType(s.StorageMap) if err != nil { log.Error("Couldn't marshal service:", err) } else { err = ioutil.WriteFile(s.path+"/identity.bin", b, 0660) if err != nil { log.Error("Couldn't save file:", err) } } }
// PropagateSkipBlock will save a new SkipBlock func (s *Service) PropagateSkipBlock(msg network.Body) { sb, ok := msg.(*SkipBlock) if !ok { log.Error("Couldn't convert to SkipBlock") return } if err := sb.VerifySignatures(); err != nil { log.Error(err) return } s.storeSkipBlock(sb) log.Lvlf3("Stored skip block %+v in %x", *sb, s.Context.ServerIdentity().ID[0:8]) }
func GetShaString(data []byte) (res string) { sha := sha256.New() if _, err := sha.Write(data[:]); err != nil { log.Error("Failed to hash data", err) } tmp := sha.Sum(nil) sha.Reset() if _, err := sha.Write(tmp); err != nil { log.Error("Failed to hash data", err) } hash := sha.Sum(nil) res = HashString(hash) return }
// listen will select on the differents channels func (nt *Ntree) listen() { for { select { // Dispatch the block through the whole tree case msg := <-nt.announceChan: log.Lvl3(nt.Name(), "Received Block announcement") nt.block = msg.BlockAnnounce.Block // verify the block go byzcoin.VerifyBlock(nt.block, "", "", nt.verifyBlockChan) if nt.IsLeaf() { nt.startBlockSignature() continue } for _, tn := range nt.Children() { err := nt.SendTo(tn, &msg.BlockAnnounce) if err != nil { log.Error(nt.Name(), "couldn't send to", tn.Name(), err) } } // generate your own signature / exception and pass that up to the // root case msg := <-nt.blockSignatureChan: nt.handleBlockSignature(&msg.NaiveBlockSignature) // Dispatch the signature + expcetion made before through the whole // tree case msg := <-nt.roundSignatureRequestChan: log.Lvl3(nt.Name(), " Signature Request Received") go nt.verifySignatureRequest(&msg.RoundSignatureRequest) if nt.IsLeaf() { nt.startSignatureResponse() continue } for _, tn := range nt.Children() { err := nt.SendTo(tn, &msg.RoundSignatureRequest) if err != nil { log.Error(nt.Name(), "couldn't sent to", tn.Name(), err) } } // Decide if we want to sign this or not case msg := <-nt.roundSignatureResponseChan: nt.handleRoundSignatureResponse(&msg.RoundSignatureResponse) } } }
func (tl *TransactionList) HashSum() []byte { h := sha256.New() for _, tx := range tl.Txs { if _, err := h.Write([]byte(tx.Hash)); err != nil { log.Error("Couldn't hash TX list", err) } } if err := binary.Write(h, binary.LittleEndian, tl.TxCnt); err != nil { log.Error("Couldn't hash TX list", err) } if err := binary.Write(h, binary.LittleEndian, tl.Fees); err != nil { log.Error("Couldn't hash TX list", err) } return h.Sum(nil) }
func (c *CoSimul) getResponse(in []abstract.Scalar) { if c.IsLeaf() { // This is the leaf-node and we can't verify it return } verify := false switch VerifyResponse { case NoCheck: log.Lvl3("Not checking at all") case RootCheck: verify = c.IsRoot() case AllCheck: verify = !c.IsLeaf() } if verify { err := c.VerifyResponses(c.TreeNode().AggregatePublic()) if err != nil { log.Error("Couldn't verify responses at our level", c.Name(), err.Error()) } else { log.Lvl2("Successfully verified responses at", c.Name()) } } }
func (jv *JVSS) handleSecInit(m WSecInitMsg) error { msg := m.SecInitMsg log.Lvl4(jv.Name(), jv.Index(), "Received SecInit from", m.TreeNode.Name()) // Initialise shared secret if err := jv.initSecret(msg.SID); err != nil { return err } // Unmarshal received deal deal := new(poly.Deal).UnmarshalInit(jv.info.T, jv.info.R, jv.info.N, jv.keyPair.Suite) if err := deal.UnmarshalBinary(msg.Deal); err != nil { return err } // Buffer received deal for later secret, err := jv.secrets.secret(msg.SID) if err != nil { return err } secret.deals[msg.Src] = deal // Finalise shared secret if err := jv.finaliseSecret(msg.SID); err != nil { log.Error(jv.Index(), err) return err } log.Lvl4("Finished handleSecInit", jv.Name(), msg.SID) return nil }
func newIdentityService(c *onet.Context, path string) onet.Service { s := &Service{ ServiceProcessor: onet.NewServiceProcessor(c), StorageMap: &StorageMap{make(map[string]*Storage)}, skipchain: skipchain.NewClient(), path: path, } var err error s.propagateIdentity, err = manage.NewPropagationFunc(c, "IdentityPropagateID", s.propagateIdentityHandler) if err != nil { return nil } s.propagateSkipBlock, err = manage.NewPropagationFunc(c, "IdentityPropagateSB", s.propagateSkipBlockHandler) if err != nil { return nil } s.propagateConfig, err = manage.NewPropagationFunc(c, "IdentityPropagateConf", s.propagateConfigHandler) if err != nil { return nil } if err := s.tryLoad(); err != nil { log.Error(err) } for _, f := range []interface{}{s.ProposeSend, s.ProposeVote, s.CreateIdentity, s.ProposeUpdate, s.ConfigUpdate} { if err := s.RegisterHandler(f); err != nil { log.Fatal("Registration error:", err) } } return s }
// propagateIdentity stores a new identity in all nodes. func (s *Service) propagateIdentityHandler(msg network.Body) { log.Lvlf4("Got msg %+v %v", msg, reflect.TypeOf(msg).String()) pi, ok := msg.(*PropagateIdentity) if !ok { log.Error("Got a wrong message for propagation") return } id := ID(pi.Data.Hash) if s.getIdentityStorage(id) != nil { log.Error("Couldn't store new identity") return } log.Lvl3("Storing identity in", s) s.setIdentityStorage(id, pi.Storage) return }
// propagateConfig handles propagation of all configuration-proposals in the identity-service. func (s *Service) propagateConfigHandler(msg network.Body) { log.Lvlf4("Got msg %+v %v", msg, reflect.TypeOf(msg).String()) id := ID(nil) switch msg.(type) { case *ProposeSend: id = msg.(*ProposeSend).ID case *ProposeVote: id = msg.(*ProposeVote).ID default: log.Errorf("Got an unidentified propagation-request: %v", msg) return } if id != nil { sid := s.getIdentityStorage(id) if sid == nil { log.Error("Didn't find entity in", s) return } sid.Lock() defer sid.Unlock() switch msg.(type) { case *ProposeSend: p := msg.(*ProposeSend) sid.Proposed = p.Config sid.Votes = make(map[string]*crypto.SchnorrSig) case *ProposeVote: v := msg.(*ProposeVote) sid.Votes[v.Signer] = v.Signature } } }
func newSkipchainService(c *onet.Context, path string) onet.Service { s := &Service{ ServiceProcessor: onet.NewServiceProcessor(c), path: path, SkipBlockMap: &SkipBlockMap{make(map[string]*SkipBlock)}, verifiers: map[VerifierID]SkipBlockVerifier{}, } var err error s.Propagate, err = manage.NewPropagationFunc(c, "SkipchainPropagate", s.PropagateSkipBlock) log.ErrFatal(err) c.ProtocolRegister(skipchainBFT, func(n *onet.TreeNodeInstance) (onet.ProtocolInstance, error) { return bftcosi.NewBFTCoSiProtocol(n, s.bftVerify) }) if err := s.tryLoad(); err != nil { log.Error(err) } log.ErrFatal(s.RegisterHandlers(s.ProposeSkipBlock, s.SetChildrenSkipBlock, s.GetUpdateChain)) if err := s.RegisterVerification(VerifyShard, s.VerifyShardFunc); err != nil { log.Panic(err) } if err := s.RegisterVerification(VerifyNone, s.VerifyNoneFunc); err != nil { log.Panic(err) } return s }
// Dispatch listens for all channels and waits for a timeout in case nothing // happens for a certain duration func (p *ProtocolCount) Dispatch() error { running := true for running { log.Lvl3(p.Info(), "waiting for message during", p.Timeout()) select { case pc := <-p.PrepareCountChan: log.Lvl3(p.Info(), "received from", pc.TreeNode.ServerIdentity.Address, pc.Timeout) p.SetTimeout(pc.Timeout) p.FuncPC() case c := <-p.CountChan: p.FuncC(c) running = false case _ = <-p.NodeIsUpChan: if p.Parent() != nil { err := p.SendTo(p.Parent(), &NodeIsUp{}) if err != nil { log.Error(p.Info(), "couldn't send to parent", p.Parent().Name(), err) } } else { p.Replies++ } case <-time.After(time.Duration(p.Timeout()) * time.Millisecond): log.Lvl3(p.Info(), "timed out while waiting for", p.Timeout()) if p.IsRoot() { log.Lvl2("Didn't get all children in time:", p.Replies) p.Count <- p.Replies running = false } } } p.Done() return nil }
func (c *Client) triggerTransactions(blocksPath string, nTxs int) error { log.Lvl2("ByzCoin Client will trigger up to", nTxs, "transactions") parser, err := blockchain.NewParser(blocksPath, magicNum) if err != nil { log.Error("Error: Couldn't parse blocks in", blocksPath, ".\nPlease download bitcoin blocks as .dat files first and place them in", blocksPath, "Either run a bitcoin node (recommended) or using a torrent.") return err } transactions, err := parser.Parse(0, ReadFirstNBlocks) if err != nil { return fmt.Errorf("Error while parsing transactions %v", err) } if len(transactions) == 0 { return errors.New("Couldn't read any transactions.") } if len(transactions) < nTxs { return fmt.Errorf("Read only %v but caller wanted %v", len(transactions), nTxs) } consumed := nTxs for consumed > 0 { for _, tr := range transactions { // "send" transaction to server (we skip tcp connection on purpose here) c.srv.AddTransaction(tr) } consumed-- } return nil }
// Copy returns a deep copy of the AccountList. func (c *Config) Copy() *Config { b, err := network.MarshalRegisteredType(c) if err != nil { log.Error("Couldn't marshal AccountList:", err) return nil } _, msg, err := network.UnmarshalRegisteredType(b, network.DefaultConstructors(network.Suite)) if err != nil { log.Error("Couldn't unmarshal AccountList:", err) } ilNew := msg.(Config) if len(ilNew.Data) == 0 { ilNew.Data = make(map[string]string) } return &ilNew }
// handleCommitChallenge will verify the signature + check if no more than 1/3 // of participants refused to sign. func (bz *ByzCoin) handleChallengeCommit(ch *ChallengeCommit) error { // marshal the block marshalled, err := json.Marshal(bz.tempBlock) if err != nil { return err } ch.Challenge = bz.commit.Challenge(ch.Challenge) // verify if the signature is correct if err := cosi.VerifyCosiSignatureWithException(bz.suite, bz.aggregatedPublic, marshalled, ch.Signature, ch.Exceptions); err != nil { log.Error(bz.Name(), "Verification of the signature failed:", err) bz.signRefusal = true } // Verify if we have no more than 1/3 failed nodes if len(ch.Exceptions) > int(bz.threshold) { log.Errorf("More than 1/3 (%d/%d) refused to sign ! ABORT", len(ch.Exceptions), len(bz.Roster().List)) bz.signRefusal = true } // store the exceptions for later usage bz.tempExceptions = ch.Exceptions log.Lvl3("ByzCoin handle Challenge COMMIT") if bz.IsLeaf() { return bz.startResponseCommit() } // send it down for _, tn := range bz.Children() { err = bz.SendTo(tn, ch) } return nil }
// HashSum returns a hash representation of the header func (h *Header) HashSum() []byte { ha := sha256.New() if _, err := ha.Write([]byte(h.MerkleRoot)); err != nil { log.Error("Couldn't hash header", err) } if _, err := ha.Write([]byte(h.Parent)); err != nil { log.Error("Couldn't hash header", err) } if _, err := ha.Write([]byte(h.ParentKey)); err != nil { log.Error("Couldn't hash header", err) } if _, err := ha.Write([]byte(h.PublicKey)); err != nil { log.Error("Couldn't hash header", err) } return ha.Sum(nil) }
// Start the last phase : send up the final signature func (nt *Ntree) startSignatureResponse() { log.Lvl3(nt.Name(), "Start Signature Response phase") nt.computeSignatureResponse() if err := nt.SendTo(nt.Parent(), nt.tempSignatureResponse); err != nil { log.Error(err) } }
// startBlockSignature will send the first signature up the tree. func (nt *Ntree) startBlockSignature() { log.Lvl3(nt.Name(), "Starting Block Signature Phase") nt.computeBlockSignature() if err := nt.SendTo(nt.Parent(), nt.tempBlockSig); err != nil { log.Error(err) } }
// NewCount returns a new protocolInstance func NewCount(n *onet.TreeNodeInstance) (onet.ProtocolInstance, error) { p := &ProtocolCount{ TreeNodeInstance: n, Quit: make(chan bool), timeout: 1024, } p.Count = make(chan int, 1) if err := p.RegisterChannel(&p.CountChan); err != nil { log.Error("Couldn't reister channel:", err) } if err := p.RegisterChannel(&p.PrepareCountChan); err != nil { log.Error("Couldn't reister channel:", err) } if err := p.RegisterChannel(&p.NodeIsUpChan); err != nil { log.Error("Couldn't reister channel:", err) } return p, nil }
func HashHeader(h *Header) string { data := fmt.Sprintf("%v", h) sha := sha256.New() if _, err := sha.Write([]byte(data)); err != nil { log.Error("Couldn't hash header:", err) } hash := sha.Sum(nil) return hex.EncodeToString(hash) }
// Dispatch is an infinite loop to handle messages from channels func (p *ProtocolExampleChannels) Dispatch() error { for { select { case announcement := <-p.ChannelAnnounce: if !p.IsLeaf() { // If we have children, send the same message to all of them for _, c := range p.Children() { err := p.SendTo(c, &announcement.Announce) if err != nil { log.Error(p.Info(), "failed to send to", c.Name(), err) } } } else { // If we're the leaf, start to reply err := p.SendTo(p.Parent(), &Reply{1}) if err != nil { log.Error(p.Info(), "failed to send reply to", p.Parent().Name(), err) } return nil } case reply := <-p.ChannelReply: children := 1 for _, c := range reply { children += c.ChildrenCount } log.Lvl3(p.ServerIdentity().Address, "is done with total of", children) if !p.IsRoot() { log.Lvl3("Sending to parent") err := p.SendTo(p.Parent(), &Reply{children}) if err != nil { log.Error(p.Info(), "failed to reply to", p.Parent().Name(), err) } } else { log.Lvl3("Root-node is done - nbr of children found:", children) p.ChildCount <- children } return nil } } }
// Start sends the Announce message to all children func (p *ProtocolExampleChannels) Start() error { log.Lvl3("Starting ExampleChannels") for _, c := range p.Children() { if err := p.SendTo(c, &Announce{"Example is here"}); err != nil { log.Error(p.Info(), "failed to send Announcment to", c.Name(), err) } } return nil }
// finish is called by the root to tell everyone the root is done func (p *Protocol) finish() { p.broadcast(func(tn *onet.TreeNode) { if err := p.SendTo(tn, &Finish{"Finish"}); err != nil { log.Error(p.Name(), "couldn't send 'finish' message to", tn.Name(), err) } }) // notify ourselves go func() { p.finishChan <- finishChan{nil, Finish{}} }() }
// startSignatureRequest is the root starting the new phase. It will broadcast // the signature of everyone amongst the tree. func (nt *Ntree) startSignatureRequest(msg *NaiveBlockSignature) { log.Lvl3(nt.Name(), "Start Signature Request") sigRequest := &RoundSignatureRequest{msg} go nt.verifySignatureRequest(sigRequest) for _, tn := range nt.Children() { if err := nt.SendTo(tn, sigRequest); err != nil { log.Error(nt.Name(), "couldn't send to", tn.Name(), err) } } }
// SimulDirToBlockDir creates a path to the 'protocols/byzcoin/block'-dir by // using 'dir' which comes from 'cothority/simul' // If that directory doesn't exist, it will be created. func SimulDirToBlockDir(dir string) string { reg, _ := regexp.Compile("simul/.*") blockDir := string(reg.ReplaceAll([]byte(dir), []byte("protocols/byzcoin/block"))) if _, err := os.Stat(blockDir); os.IsNotExist(err) { if err := os.Mkdir(blockDir, 0777); err != nil { log.Error("Couldn't create blocks directory", err) } } return blockDir }
// Hash returns a hash representation of the block func (tr *TrBlock) HashSum() []byte { h := sha256.New() if _, err := h.Write(tr.Magic[:]); err != nil { log.Error("Couldn't hash block:", err) } if err := binary.Write(h, binary.LittleEndian, tr.BlockSize); err != nil { log.Error("Couldn't hash block:", err) } if _, err := h.Write([]byte(tr.HeaderHash)); err != nil { log.Error("Couldn't hash block:", err) } if _, err := h.Write(tr.Header.HashSum()); err != nil { log.Error("Couldn't hash block:", err) } if _, err := h.Write(tr.TransactionList.HashSum()); err != nil { log.Error("Couldn't hash block:", err) } return h.Sum(nil) }