Parcourir la source

Allow more flexibility to data stored in the blockchain

Ettore Di Giacinto il y a 3 ans
Parent
commit
eded6488fb
4 fichiers modifiés avec 41 ajouts et 49 suppressions
  1. 8 9
      pkg/blockchain/block.go
  2. 5 0
      pkg/blockchain/data.go
  3. 13 19
      pkg/blockchain/ledger.go
  4. 15 21
      pkg/edgevpn/edgevpn.go

+ 8 - 9
pkg/blockchain/block.go

@@ -9,11 +9,11 @@ import (
 
 
 // Block represents each 'item' in the blockchain
 // Block represents each 'item' in the blockchain
 type Block struct {
 type Block struct {
-	Index      int
-	Timestamp  string
-	AddressMap map[string]string
-	Hash       string
-	PrevHash   string
+	Index     int
+	Timestamp string
+	Storage   map[string]Data
+	Hash      string
+	PrevHash  string
 }
 }
 
 
 // Blockchain is a series of validated Blocks
 // Blockchain is a series of validated Blocks
@@ -42,7 +42,7 @@ func (newBlock Block) IsValid(oldBlock Block) bool {
 
 
 // Checksum does SHA256 hashing of the block
 // Checksum does SHA256 hashing of the block
 func (b Block) Checksum() string {
 func (b Block) Checksum() string {
-	record := fmt.Sprint(b.Index, b.Timestamp, b.AddressMap, b.PrevHash)
+	record := fmt.Sprint(b.Index, b.Timestamp, b.Storage, b.PrevHash)
 	h := sha256.New()
 	h := sha256.New()
 	h.Write([]byte(record))
 	h.Write([]byte(record))
 	hashed := h.Sum(nil)
 	hashed := h.Sum(nil)
@@ -50,15 +50,14 @@ func (b Block) Checksum() string {
 }
 }
 
 
 // create a new block using previous block's hash
 // create a new block using previous block's hash
-func (oldBlock Block) NewBlock(s map[string]string) Block {
-
+func (oldBlock Block) NewBlock(s map[string]Data) Block {
 	var newBlock Block
 	var newBlock Block
 
 
 	t := time.Now()
 	t := time.Now()
 
 
 	newBlock.Index = oldBlock.Index + 1
 	newBlock.Index = oldBlock.Index + 1
 	newBlock.Timestamp = t.String()
 	newBlock.Timestamp = t.String()
-	newBlock.AddressMap = s
+	newBlock.Storage = s
 	newBlock.PrevHash = oldBlock.Hash
 	newBlock.PrevHash = oldBlock.Hash
 	newBlock.Hash = newBlock.Checksum()
 	newBlock.Hash = newBlock.Checksum()
 
 

+ 5 - 0
pkg/blockchain/data.go

@@ -0,0 +1,5 @@
+package blockchain
+
+type Data struct {
+	PeerID string
+}

+ 13 - 19
pkg/blockchain/ledger.go

@@ -29,7 +29,7 @@ func New(w io.Writer, maxChainSize int) *Ledger {
 func (l *Ledger) newGenesis() {
 func (l *Ledger) newGenesis() {
 	t := time.Now()
 	t := time.Now()
 	genesisBlock := Block{}
 	genesisBlock := Block{}
-	genesisBlock = Block{0, t.String(), map[string]string{}, genesisBlock.Checksum(), ""}
+	genesisBlock = Block{0, t.String(), map[string]Data{}, genesisBlock.Checksum(), ""}
 	l.Blockchain = append(l.Blockchain, genesisBlock)
 	l.Blockchain = append(l.Blockchain, genesisBlock)
 }
 }
 
 
@@ -89,22 +89,15 @@ func (l *Ledger) Update(h *hub.Message) (err error) {
 // Sends a broadcast at the specified interval
 // Sends a broadcast at the specified interval
 // by making sure the async retrieved value is written to the
 // by making sure the async retrieved value is written to the
 // blockchain
 // blockchain
-func (l *Ledger) Announce(ctx context.Context, t time.Duration, key string, async func() string) {
+func (l *Ledger) Announce(ctx context.Context, t time.Duration, async func()) {
 	go func() {
 	go func() {
 		t := time.NewTicker(t)
 		t := time.NewTicker(t)
 		defer t.Stop()
 		defer t.Stop()
 		for {
 		for {
 			select {
 			select {
 			case <-t.C:
 			case <-t.C:
-				value := async()
-				// Retrieve current ID for ip in the blockchain
-				existingValue, found := l.GetKey(key)
-				// If mismatch, update the blockchain
-				if !found || existingValue != value {
-					updatedMap := map[string]string{}
-					updatedMap[key] = value
-					l.Add(updatedMap)
-				}
+				async()
+
 			case <-ctx.Done():
 			case <-ctx.Done():
 				return
 				return
 			}
 			}
@@ -117,12 +110,13 @@ func (l *Ledger) lastBlock() Block {
 }
 }
 
 
 // GetKey retrieve the current key from the blockchain
 // GetKey retrieve the current key from the blockchain
-func (l *Ledger) GetKey(s string) (value string, exists bool) {
+func (l *Ledger) GetKey(s string) (value Data, exists bool) {
 	l.Lock()
 	l.Lock()
 	defer l.Unlock()
 	defer l.Unlock()
+
 	if len(l.Blockchain) > 0 {
 	if len(l.Blockchain) > 0 {
 		last := l.lastBlock()
 		last := l.lastBlock()
-		value, exists = last.AddressMap[s]
+		value, exists = last.Storage[s]
 		if exists {
 		if exists {
 			return
 			return
 		}
 		}
@@ -132,12 +126,12 @@ func (l *Ledger) GetKey(s string) (value string, exists bool) {
 }
 }
 
 
 // ExistsValue returns true if there is one element with a matching value
 // ExistsValue returns true if there is one element with a matching value
-func (l *Ledger) ExistsValue(v string) (exists bool) {
+func (l *Ledger) Exists(f func(Data) bool) (exists bool) {
 	l.Lock()
 	l.Lock()
 	defer l.Unlock()
 	defer l.Unlock()
 	if len(l.Blockchain) > 0 {
 	if len(l.Blockchain) > 0 {
-		for _, bv := range l.lastBlock().AddressMap {
-			if bv == v {
+		for _, bv := range l.lastBlock().Storage {
+			if f(bv) {
 				exists = true
 				exists = true
 				return
 				return
 			}
 			}
@@ -148,9 +142,9 @@ func (l *Ledger) ExistsValue(v string) (exists bool) {
 }
 }
 
 
 // Add data to the blockchain
 // Add data to the blockchain
-func (l *Ledger) Add(s map[string]string) {
+func (l *Ledger) Add(s map[string]Data) {
 	l.Lock()
 	l.Lock()
-	current := l.lastBlock().AddressMap
+	current := l.lastBlock().Storage
 	for s, k := range s {
 	for s, k := range s {
 		current[s] = k
 		current[s] = k
 	}
 	}
@@ -158,7 +152,7 @@ func (l *Ledger) Add(s map[string]string) {
 	l.writeData(current)
 	l.writeData(current)
 }
 }
 
 
-func (l *Ledger) writeData(s map[string]string) {
+func (l *Ledger) writeData(s map[string]Data) {
 	newBlock := l.lastBlock().NewBlock(s)
 	newBlock := l.lastBlock().NewBlock(s)
 
 
 	if newBlock.IsValid(l.lastBlock()) {
 	if newBlock.IsValid(l.lastBlock()) {

+ 15 - 21
pkg/edgevpn/edgevpn.go

@@ -43,23 +43,6 @@ func New(p ...Option) *EdgeVPN {
 	}
 	}
 }
 }
 
 
-// keeps syncronized the blockchain with the node IP
-func (e *EdgeVPN) adverizer(ip net.IP, ledger *blockchain.Ledger) {
-	for {
-		time.Sleep(5 * time.Second)
-
-		nodeID := e.host.ID().String()
-		// Retrieve current ID for ip in the blockchain
-		existingPeerID, found := ledger.GetKey(ip.String())
-		// If mismatch, update the blockchain
-		if !found || existingPeerID != nodeID {
-			updatedMap := map[string]string{}
-			updatedMap[ip.String()] = nodeID
-			ledger.Add(updatedMap)
-		}
-	}
-}
-
 func (e *EdgeVPN) Join(ledger *blockchain.Ledger) error {
 func (e *EdgeVPN) Join(ledger *blockchain.Ledger) error {
 	// Set the handler when we receive messages
 	// Set the handler when we receive messages
 	// The ledger needs to read them and update the internal blockchain
 	// The ledger needs to read them and update the internal blockchain
@@ -83,8 +66,16 @@ func (e *EdgeVPN) Join(ledger *blockchain.Ledger) error {
 	ledger.Announce(
 	ledger.Announce(
 		context.Background(),
 		context.Background(),
 		e.config.LedgerAnnounceTime,
 		e.config.LedgerAnnounceTime,
-		ip.String(),
-		func() string { return e.host.ID().String() },
+		func() {
+			// Retrieve current ID for ip in the blockchain
+			existingValue, found := ledger.GetKey(ip.String())
+			// If mismatch, update the blockchain
+			if !found || existingValue.PeerID != e.host.ID().String() {
+				updatedMap := map[string]blockchain.Data{}
+				updatedMap[ip.String()] = blockchain.Data{PeerID: e.host.ID().String()}
+				ledger.Add(updatedMap)
+			}
+		},
 	)
 	)
 
 
 	return nil
 	return nil
@@ -143,7 +134,10 @@ func (e *EdgeVPN) MessageWriter(opts ...hub.MessageOption) (*MessageWriter, erro
 
 
 func streamHandler(ledger *blockchain.Ledger, ifce *water.Interface) func(stream network.Stream) {
 func streamHandler(ledger *blockchain.Ledger, ifce *water.Interface) func(stream network.Stream) {
 	return func(stream network.Stream) {
 	return func(stream network.Stream) {
-		if !ledger.ExistsValue(stream.Conn().RemotePeer().String()) {
+		if !ledger.Exists(
+			func(d blockchain.Data) bool {
+				return d.PeerID == stream.Conn().RemotePeer().String()
+			}) {
 			stream.Reset()
 			stream.Reset()
 			return
 			return
 		}
 		}
@@ -181,7 +175,7 @@ func (e *EdgeVPN) readPackets(ledger *blockchain.Ledger, ifce *water.Interface)
 		}
 		}
 
 
 		// Decode the Peer
 		// Decode the Peer
-		d, err := peer.Decode(value)
+		d, err := peer.Decode(value.PeerID)
 		if err != nil {
 		if err != nil {
 			e.config.Logger.Sugar().Infof("could not decode peer '%s'", value)
 			e.config.Logger.Sugar().Infof("could not decode peer '%s'", value)
 			continue
 			continue