0

Im essentially looking for a way to use bytes.Compare() but on an array of ethereum addresses that are of type common.Address. I need to search an array to see if another address exists in it and then add it only if it doesn't exist.

  • Why not use a mapping instead of an array? You could use an indexation array for iteration – Henk Jun 25 '18 at 13:28
  • i still need to be able to convert a lot of types back and forth... i need to find if an address exists inside an array of valid signers – Gizzard Jun 25 '18 at 13:40
1

Here's a working example of how to use bytes.Compare to check if an address exists in an array of common.Address and if it doesn't then add it to the list.

package main

import (
    "bytes"
    "fmt"

    "github.com/davecgh/go-spew/spew"
    "github.com/ethereum/go-ethereum/common"
)

func main() {
    list := []common.Address{
        common.HexToAddress("0x82a978b3f5962a5b0957d9ee9eef472ee55b42f1"),
        common.HexToAddress("0x7d577a597b2742b498cb5cf0c26cdcd726d39e6e"),
        common.HexToAddress("0xdceceaf3fc5c0a63d195d69b1a90011b7b19650d"),
        common.HexToAddress("0x598443f1880ef585b21f1d7585bd0577402861e5"),
        common.HexToAddress("0x13cbb8d99c6c4e0f2728c7d72606e78a29c4e224"),
        common.HexToAddress("0x77db2bebba79db42a978f896968f4afce746ea1f"),
        common.HexToAddress("0x24143873e0e0815fdcbcffdbe09c979cbf9ad013"),
        common.HexToAddress("0x10a1c1cb95c92ec31d3f22c66eef1d9f3f258c6b"),
        common.HexToAddress("0xe0fc04fa2d34a66b779fd5cee748268032a146c0"),
        common.HexToAddress("0x90f0b1ebbba1c1936aff7aaf20a7878ff9e04b6c"),
    }

    addressBytes := []byte{89, 132, 67, 241, 136, 14, 245, 133, 178, 31, 29, 117, 133, 189, 5, 119, 64, 40, 97, 229}

    var exists bool

    for i, addr := range list {
        if bytes.Compare(addr.Bytes(), addressBytes) == 0 {
            fmt.Printf("found %s at index %v", addr.Hex(), i) // found 0x598443F1880Ef585B21f1d7585Bd0577402861E5 at index 3
            exists = true
            break
        }
    }

    if !exists {
        list = append(list, common.BytesToAddress(addressBytes))
    }

    spew.Dump(list)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.