From d085133c6d9d75e9cbd016a9a597097fa2bb4345 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 15:57:12 +0100 Subject: move ethutil helper crypto functions to ethcrypto/crypto --- ethcrypto/crypto.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 ethcrypto/crypto.go (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go new file mode 100644 index 000000000..9c4013d6c --- /dev/null +++ b/ethcrypto/crypto.go @@ -0,0 +1,27 @@ +package ethcrypto + +import ( + "code.google.com/p/go.crypto/ripemd160" + "crypto/sha256" + "github.com/obscuren/sha3" +) + +func Sha256Bin(data []byte) []byte { + hash := sha256.Sum256(data) + + return hash[:] +} + +func Ripemd160(data []byte) []byte { + ripemd := ripemd160.New() + ripemd.Write(data) + + return ripemd.Sum(nil) +} + +func Sha3Bin(data []byte) []byte { + d := sha3.NewKeccak256() + d.Write(data) + + return d.Sum(nil) +} -- cgit v1.2.3 From 1db3e2241efe2a358b9c28c21fb2cb7c2f1e55a6 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 15:59:35 +0100 Subject: move ethutil/mnemonic to ethcrypto - electrum word list now sourced from file --- ethcrypto/mnemonic.go | 76 ++ ethcrypto/mnemonic.words.lst | 1626 ++++++++++++++++++++++++++++++++++++++++++ ethcrypto/mnemonic_test.go | 74 ++ 3 files changed, 1776 insertions(+) create mode 100644 ethcrypto/mnemonic.go create mode 100644 ethcrypto/mnemonic.words.lst create mode 100644 ethcrypto/mnemonic_test.go (limited to 'ethcrypto') diff --git a/ethcrypto/mnemonic.go b/ethcrypto/mnemonic.go new file mode 100644 index 000000000..6134f85f7 --- /dev/null +++ b/ethcrypto/mnemonic.go @@ -0,0 +1,76 @@ +package ethcrypto + +import ( + "fmt" + "io/ioutil" + "path" + "runtime" + "strconv" + "strings" +) + +func InitWords() []string { + _, thisfile, _, _ := runtime.Caller(1) + filename := path.Join(path.Dir(thisfile), "mnemonic.words.lst") + content, err := ioutil.ReadFile(filename) + if err != nil { + panic(fmt.Errorf("reading mnemonic word list file 'mnemonic.words.lst' failed: ", err)) + } + return strings.Split(string(content), "\n") +} + +var words = InitWords() + +// TODO: See if we can refactor this into a shared util lib if we need it multiple times +func IndexOf(slice []string, value string) int64 { + for p, v := range slice { + if v == value { + return int64(p) + } + } + return -1 +} + +func MnemonicEncode(message string) []string { + var out []string + n := int64(len(words)) + + for i := 0; i < len(message); i += (len(message) / 8) { + x := message[i : i+8] + bit, _ := strconv.ParseInt(x, 16, 64) + w1 := (bit % n) + w2 := ((bit / n) + w1) % n + w3 := ((bit / n / n) + w2) % n + out = append(out, words[w1], words[w2], words[w3]) + } + return out +} + +func MnemonicDecode(wordsar []string) string { + var out string + n := int64(len(words)) + + for i := 0; i < len(wordsar); i += 3 { + word1 := wordsar[i] + word2 := wordsar[i+1] + word3 := wordsar[i+2] + w1 := IndexOf(words, word1) + w2 := IndexOf(words, word2) + w3 := IndexOf(words, word3) + + y := (w2 - w1) % n + z := (w3 - w2) % n + + // Golang handles modulo with negative numbers different then most languages + // The modulo can be negative, we don't want that. + if z < 0 { + z += n + } + if y < 0 { + y += n + } + x := w1 + n*(y) + n*n*(z) + out += fmt.Sprintf("%08x", x) + } + return out +} diff --git a/ethcrypto/mnemonic.words.lst b/ethcrypto/mnemonic.words.lst new file mode 100644 index 000000000..6bf412ce1 --- /dev/null +++ b/ethcrypto/mnemonic.words.lst @@ -0,0 +1,1626 @@ +like +just +love +know +never +want +time +out +there +make +look +eye +down +only +think +heart +back +then +into +about +more +away +still +them +take +thing +even +through +long +always +world +too +friend +tell +try +hand +thought +over +here +other +need +smile +again +much +cry +been +night +ever +little +said +end +some +those +around +mind +people +girl +leave +dream +left +turn +myself +give +nothing +really +off +before +something +find +walk +wish +good +once +place +ask +stop +keep +watch +seem +everything +wait +got +yet +made +remember +start +alone +run +hope +maybe +believe +body +hate +after +close +talk +stand +own +each +hurt +help +home +god +soul +new +many +two +inside +should +true +first +fear +mean +better +play +another +gone +change +use +wonder +someone +hair +cold +open +best +any +behind +happen +water +dark +laugh +stay +forever +name +work +show +sky +break +came +deep +door +put +black +together +upon +happy +such +great +white +matter +fill +past +please +burn +cause +enough +touch +moment +soon +voice +scream +anything +stare +sound +red +everyone +hide +kiss +truth +death +beautiful +mine +blood +broken +very +pass +next +forget +tree +wrong +air +mother +understand +lip +hit +wall +memory +sleep +free +high +realize +school +might +skin +sweet +perfect +blue +kill +breath +dance +against +fly +between +grow +strong +under +listen +bring +sometimes +speak +pull +person +become +family +begin +ground +real +small +father +sure +feet +rest +young +finally +land +across +today +different +guy +line +fire +reason +reach +second +slowly +write +eat +smell +mouth +step +learn +three +floor +promise +breathe +darkness +push +earth +guess +save +song +above +along +both +color +house +almost +sorry +anymore +brother +okay +dear +game +fade +already +apart +warm +beauty +heard +notice +question +shine +began +piece +whole +shadow +secret +street +within +finger +point +morning +whisper +child +moon +green +story +glass +kid +silence +since +soft +yourself +empty +shall +angel +answer +baby +bright +dad +path +worry +hour +drop +follow +power +war +half +flow +heaven +act +chance +fact +least +tired +children +near +quite +afraid +rise +sea +taste +window +cover +nice +trust +lot +sad +cool +force +peace +return +blind +easy +ready +roll +rose +drive +held +music +beneath +hang +mom +paint +emotion +quiet +clear +cloud +few +pretty +bird +outside +paper +picture +front +rock +simple +anyone +meant +reality +road +sense +waste +bit +leaf +thank +happiness +meet +men +smoke +truly +decide +self +age +book +form +alive +carry +escape +damn +instead +able +ice +minute +throw +catch +leg +ring +course +goodbye +lead +poem +sick +corner +desire +known +problem +remind +shoulder +suppose +toward +wave +drink +jump +woman +pretend +sister +week +human +joy +crack +grey +pray +surprise +dry +knee +less +search +bleed +caught +clean +embrace +future +king +son +sorrow +chest +hug +remain +sat +worth +blow +daddy +final +parent +tight +also +create +lonely +safe +cross +dress +evil +silent +bone +fate +perhaps +anger +class +scar +snow +tiny +tonight +continue +control +dog +edge +mirror +month +suddenly +comfort +given +loud +quickly +gaze +plan +rush +stone +town +battle +ignore +spirit +stood +stupid +yours +brown +build +dust +hey +kept +pay +phone +twist +although +ball +beyond +hidden +nose +taken +fail +float +pure +somehow +wash +wrap +angry +cheek +creature +forgotten +heat +rip +single +space +special +weak +whatever +yell +anyway +blame +job +choose +country +curse +drift +echo +figure +grew +laughter +neck +suffer +worse +yeah +disappear +foot +forward +knife +mess +somewhere +stomach +storm +beg +idea +lift +offer +breeze +field +five +often +simply +stuck +win +allow +confuse +enjoy +except +flower +seek +strength +calm +grin +gun +heavy +hill +large +ocean +shoe +sigh +straight +summer +tongue +accept +crazy +everyday +exist +grass +mistake +sent +shut +surround +table +ache +brain +destroy +heal +nature +shout +sign +stain +choice +doubt +glance +glow +mountain +queen +stranger +throat +tomorrow +city +either +fish +flame +rather +shape +spin +spread +ash +distance +finish +image +imagine +important +nobody +shatter +warmth +became +feed +flesh +funny +lust +shirt +trouble +yellow +attention +bare +bite +money +protect +amaze +appear +born +choke +completely +daughter +fresh +friendship +gentle +probably +six +deserve +expect +grab +middle +nightmare +river +thousand +weight +worst +wound +barely +bottle +cream +regret +relationship +stick +test +crush +endless +fault +itself +rule +spill +art +circle +join +kick +mask +master +passion +quick +raise +smooth +unless +wander +actually +broke +chair +deal +favorite +gift +note +number +sweat +box +chill +clothes +lady +mark +park +poor +sadness +tie +animal +belong +brush +consume +dawn +forest +innocent +pen +pride +stream +thick +clay +complete +count +draw +faith +press +silver +struggle +surface +taught +teach +wet +bless +chase +climb +enter +letter +melt +metal +movie +stretch +swing +vision +wife +beside +crash +forgot +guide +haunt +joke +knock +plant +pour +prove +reveal +steal +stuff +trip +wood +wrist +bother +bottom +crawl +crowd +fix +forgive +frown +grace +loose +lucky +party +release +surely +survive +teacher +gently +grip +speed +suicide +travel +treat +vein +written +cage +chain +conversation +date +enemy +however +interest +million +page +pink +proud +sway +themselves +winter +church +cruel +cup +demon +experience +freedom +pair +pop +purpose +respect +shoot +softly +state +strange +bar +birth +curl +dirt +excuse +lord +lovely +monster +order +pack +pants +pool +scene +seven +shame +slide +ugly +among +blade +blonde +closet +creek +deny +drug +eternity +gain +grade +handle +key +linger +pale +prepare +swallow +swim +tremble +wheel +won +cast +cigarette +claim +college +direction +dirty +gather +ghost +hundred +loss +lung +orange +present +swear +swirl +twice +wild +bitter +blanket +doctor +everywhere +flash +grown +knowledge +numb +pressure +radio +repeat +ruin +spend +unknown +buy +clock +devil +early +false +fantasy +pound +precious +refuse +sheet +teeth +welcome +add +ahead +block +bury +caress +content +depth +despite +distant +marry +purple +threw +whenever +bomb +dull +easily +grasp +hospital +innocence +normal +receive +reply +rhyme +shade +someday +sword +toe +visit +asleep +bought +center +consider +flat +hero +history +ink +insane +muscle +mystery +pocket +reflection +shove +silently +smart +soldier +spot +stress +train +type +view +whether +bus +energy +explain +holy +hunger +inch +magic +mix +noise +nowhere +prayer +presence +shock +snap +spider +study +thunder +trail +admit +agree +bag +bang +bound +butterfly +cute +exactly +explode +familiar +fold +further +pierce +reflect +scent +selfish +sharp +sink +spring +stumble +universe +weep +women +wonderful +action +ancient +attempt +avoid +birthday +branch +chocolate +core +depress +drunk +especially +focus +fruit +honest +match +palm +perfectly +pillow +pity +poison +roar +shift +slightly +thump +truck +tune +twenty +unable +wipe +wrote +coat +constant +dinner +drove +egg +eternal +flight +flood +frame +freak +gasp +glad +hollow +motion +peer +plastic +root +screen +season +sting +strike +team +unlike +victim +volume +warn +weird +attack +await +awake +built +charm +crave +despair +fought +grant +grief +horse +limit +message +ripple +sanity +scatter +serve +split +string +trick +annoy +blur +boat +brave +clearly +cling +connect +fist +forth +imagination +iron +jock +judge +lesson +milk +misery +nail +naked +ourselves +poet +possible +princess +sail +size +snake +society +stroke +torture +toss +trace +wise +bloom +bullet +cell +check +cost +darling +during +footstep +fragile +hallway +hardly +horizon +invisible +journey +midnight +mud +nod +pause +relax +shiver +sudden +value +youth +abuse +admire +blink +breast +bruise +constantly +couple +creep +curve +difference +dumb +emptiness +gotta +honor +plain +planet +recall +rub +ship +slam +soar +somebody +tightly +weather +adore +approach +bond +bread +burst +candle +coffee +cousin +crime +desert +flutter +frozen +grand +heel +hello +language +level +movement +pleasure +powerful +random +rhythm +settle +silly +slap +sort +spoken +steel +threaten +tumble +upset +aside +awkward +bee +blank +board +button +card +carefully +complain +crap +deeply +discover +drag +dread +effort +entire +fairy +giant +gotten +greet +illusion +jeans +leap +liquid +march +mend +nervous +nine +replace +rope +spine +stole +terror +accident +apple +balance +boom +childhood +collect +demand +depression +eventually +faint +glare +goal +group +honey +kitchen +laid +limb +machine +mere +mold +murder +nerve +painful +poetry +prince +rabbit +shelter +shore +shower +soothe +stair +steady +sunlight +tangle +tease +treasure +uncle +begun +bliss +canvas +cheer +claw +clutch +commit +crimson +crystal +delight +doll +existence +express +fog +football +gay +goose +guard +hatred +illuminate +mass +math +mourn +rich +rough +skip +stir +student +style +support +thorn +tough +yard +yearn +yesterday +advice +appreciate +autumn +bank +beam +bowl +capture +carve +collapse +confusion +creation +dove +feather +girlfriend +glory +government +harsh +hop +inner +loser +moonlight +neighbor +neither +peach +pig +praise +screw +shield +shimmer +sneak +stab +subject +throughout +thrown +tower +twirl +wow +army +arrive +bathroom +bump +cease +cookie +couch +courage +dim +guilt +howl +hum +husband +insult +led +lunch +mock +mostly +natural +nearly +needle +nerd +peaceful +perfection +pile +price +remove +roam +sanctuary +serious +shiny +shook +sob +stolen +tap +vain +void +warrior +wrinkle +affection +apologize +blossom +bounce +bridge +cheap +crumble +decision +descend +desperately +dig +dot +flip +frighten +heartbeat +huge +lazy +lick +odd +opinion +process +puzzle +quietly +retreat +score +sentence +separate +situation +skill +soak +square +stray +taint +task +tide +underneath +veil +whistle +anywhere +bedroom +bid +bloody +burden +careful +compare +concern +curtain +decay +defeat +describe +double +dreamer +driver +dwell +evening +flare +flicker +grandma +guitar +harm +horrible +hungry +indeed +lace +melody +monkey +nation +object +obviously +rainbow +salt +scratch +shown +shy +stage +stun +third +tickle +useless +weakness +worship +worthless +afternoon +beard +boyfriend +bubble +busy +certain +chin +concrete +desk +diamond +doom +drawn +due +felicity +freeze +frost +garden +glide +harmony +hopefully +hunt +jealous +lightning +mama +mercy +peel +physical +position +pulse +punch +quit +rant +respond +salty +sane +satisfy +savior +sheep +slept +social +sport +tuck +utter +valley +wolf +aim +alas +alter +arrow +awaken +beaten +belief +brand +ceiling +cheese +clue +confidence +connection +daily +disguise +eager +erase +essence +everytime +expression +fan +flag +flirt +foul +fur +giggle +glorious +ignorance +law +lifeless +measure +mighty +muse +north +opposite +paradise +patience +patient +pencil +petal +plate +ponder +possibly +practice +slice +spell +stock +strife +strip +suffocate +suit +tender +tool +trade +velvet +verse +waist +witch +aunt +bench +bold +cap +certainly +click +companion +creator +dart +delicate +determine +dish +dragon +drama +drum +dude +everybody +feast +forehead +former +fright +fully +gas +hook +hurl +invite +juice +manage +moral +possess +raw +rebel +royal +scale +scary +several +slight +stubborn +swell +talent +tea +terrible +thread +torment +trickle +usually +vast +violence +weave +acid +agony +ashamed +awe +belly +blend +blush +character +cheat +common +company +coward +creak +danger +deadly +defense +define +depend +desperate +destination +dew +duck +dusty +embarrass +engine +example +explore +foe +freely +frustrate +generation +glove +guilty +health +hurry +idiot +impossible +inhale +jaw +kingdom +mention +mist +moan +mumble +mutter +observe +ode +pathetic +pattern +pie +prefer +puff +rape +rare +revenge +rude +scrape +spiral +squeeze +strain +sunset +suspend +sympathy +thigh +throne +total +unseen +weapon +weary \ No newline at end of file diff --git a/ethcrypto/mnemonic_test.go b/ethcrypto/mnemonic_test.go new file mode 100644 index 000000000..8bd8859ae --- /dev/null +++ b/ethcrypto/mnemonic_test.go @@ -0,0 +1,74 @@ +package ethcrypto + +import ( + "testing" +) + +func TestMnDecode(t *testing.T) { + words := []string{ + "ink", + "balance", + "gain", + "fear", + "happen", + "melt", + "mom", + "surface", + "stir", + "bottle", + "unseen", + "expression", + "important", + "curl", + "grant", + "fairy", + "across", + "back", + "figure", + "breast", + "nobody", + "scratch", + "worry", + "yesterday", + } + encode := "c61d43dc5bb7a4e754d111dae8105b6f25356492df5e50ecb33b858d94f8c338" + result := MnemonicDecode(words) + if encode != result { + t.Error("We expected", encode, "got", result, "instead") + } +} +func TestMnEncode(t *testing.T) { + encode := "c61d43dc5bb7a4e754d111dae8105b6f25356492df5e50ecb33b858d94f8c338" + result := []string{ + "ink", + "balance", + "gain", + "fear", + "happen", + "melt", + "mom", + "surface", + "stir", + "bottle", + "unseen", + "expression", + "important", + "curl", + "grant", + "fairy", + "across", + "back", + "figure", + "breast", + "nobody", + "scratch", + "worry", + "yesterday", + } + words := MnemonicEncode(encode) + for i, word := range words { + if word != result[i] { + t.Error("Mnenonic does not match:", words, result) + } + } +} -- cgit v1.2.3 From 772e7e8c8df066a64726b23bde84b6025c5af318 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 16:02:23 +0100 Subject: Key Manager - keypair, keyring: -- consistent naming of methods -- error propagation -- no panic - keyManager: persist, import, export, initialize and (re)set keyring - no global public "singleton" keyring, instead interface via keyManager - keys test - KeyStore interface, DB and File store implementations --- ethcrypto/key_manager.go | 121 ++++++++++++++++++++++++++++++++++++++++++++++ ethcrypto/key_store.go | 112 +++++++++++++++++++++++++++++++++++++++++++ ethcrypto/keypair.go | 41 ++++++++++++++++ ethcrypto/keyring.go | 118 +++++++++++++++++++++++++++++++++++++++++++++ ethcrypto/keys_test.go | 122 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 514 insertions(+) create mode 100644 ethcrypto/key_manager.go create mode 100644 ethcrypto/key_store.go create mode 100644 ethcrypto/keypair.go create mode 100644 ethcrypto/keyring.go create mode 100644 ethcrypto/keys_test.go (limited to 'ethcrypto') diff --git a/ethcrypto/key_manager.go b/ethcrypto/key_manager.go new file mode 100644 index 000000000..dcbc7b77e --- /dev/null +++ b/ethcrypto/key_manager.go @@ -0,0 +1,121 @@ +package ethcrypto + +import ( + "fmt" + "github.com/ethereum/eth-go/ethutil" + "sync" +) + +type KeyManager struct { + keyRing *KeyRing + session string + keyStore KeyStore // interface + keyRings map[string]*KeyRing // cache + keyPair *KeyPair +} + +func NewDBKeyManager(db ethutil.Database) *KeyManager { + return &KeyManager{keyStore: &DBKeyStore{db: db}, keyRings: make(map[string]*KeyRing)} +} + +func NewFileKeyManager(basedir string) *KeyManager { + return &KeyManager{keyStore: &FileKeyStore{basedir: basedir}, keyRings: make(map[string]*KeyRing)} +} + +func (k *KeyManager) KeyPair() *KeyPair { + return k.keyPair +} + +func (k *KeyManager) KeyRing() *KeyPair { + return k.keyPair +} + +func (k *KeyManager) PrivateKey() []byte { + return k.keyPair.PrivateKey +} + +func (k *KeyManager) PublicKey() []byte { + return k.keyPair.PublicKey +} + +func (k *KeyManager) Address() []byte { + return k.keyPair.Address() +} + +func (k *KeyManager) save(session string, keyRing *KeyRing) error { + err := k.keyStore.Save(session, keyRing) + if err != nil { + return err + } + k.keyRings[session] = keyRing + return nil +} + +func (k *KeyManager) load(session string) (*KeyRing, error) { + keyRing, found := k.keyRings[session] + if !found { + var err error + keyRing, err = k.keyStore.Load(session) + if err != nil { + return nil, err + } + } + return keyRing, nil +} + +func cursorError(cursor int, len int) error { + return fmt.Errorf("cursor %d out of range (0..%d)", cursor, len) +} + +func (k *KeyManager) reset(session string, cursor int, keyRing *KeyRing) error { + if cursor >= keyRing.Len() { + return cursorError(cursor, keyRing.Len()) + } + lock := &sync.Mutex{} + lock.Lock() + defer lock.Unlock() + err := k.save(session, keyRing) + if err != nil { + return err + } + k.session = session + k.keyRing = keyRing + k.keyPair = keyRing.GetKeyPair(cursor) + return nil +} + +func (k *KeyManager) SetCursor(cursor int) error { + if cursor >= k.keyRing.Len() { + return cursorError(cursor, k.keyRing.Len()) + } + k.keyPair = k.keyRing.GetKeyPair(cursor) + return nil +} + +func (k *KeyManager) Init(session string, cursor int, force bool) error { + var keyRing *KeyRing + if !force { + var err error + keyRing, err = k.load(session) + if err != nil { + return err + } + } + if keyRing == nil { + keyRing = NewGeneratedKeyRing(1) + } + return k.reset(session, cursor, keyRing) +} + +func (k *KeyManager) InitFromSecretsFile(session string, cursor int, secretsfile string) error { + keyRing, err := NewKeyRingFromFile(secretsfile) + if err != nil { + return err + } + return k.reset(session, cursor, keyRing) +} + +func (k *KeyManager) Export(dir string) error { + fileKeyStore := FileKeyStore{dir} + return fileKeyStore.Save(k.session, k.keyRing) +} diff --git a/ethcrypto/key_store.go b/ethcrypto/key_store.go new file mode 100644 index 000000000..c8c506fda --- /dev/null +++ b/ethcrypto/key_store.go @@ -0,0 +1,112 @@ +package ethcrypto + +import ( + "fmt" + "github.com/ethereum/eth-go/ethutil" + "io/ioutil" + "os" + "path" + "strings" +) + +type KeyStore interface { + Load(string) (*KeyRing, error) + Save(string, *KeyRing) error +} + +type DBKeyStore struct { + db ethutil.Database +} + +const dbKeyPrefix = "KeyRing" + +func (k *DBKeyStore) dbKey(session string) []byte { + return []byte(fmt.Sprintf("%s%s", dbKeyPrefix, session)) +} + +func (k *DBKeyStore) Save(session string, keyRing *KeyRing) error { + k.db.Put(k.dbKey(session), keyRing.RlpEncode()) + return nil +} + +func (k *DBKeyStore) Load(session string) (*KeyRing, error) { + data, err := k.db.Get(k.dbKey(session)) + if err != nil { + return nil, err + } + var keyRing *KeyRing + keyRing, err = NewKeyRingFromBytes(data) + if err != nil { + return nil, err + } + // if empty keyRing is found we return nil, no error + if keyRing.Len() == 0 { + return nil, nil + } + return keyRing, nil +} + +type FileKeyStore struct { + basedir string +} + +func (k *FileKeyStore) Save(session string, keyRing *KeyRing) error { + var content []byte + var err error + var privateKeys []string + var publicKeys []string + var mnemonics []string + var addresses []string + keyRing.Each(func(keyPair *KeyPair) { + privateKeys = append(privateKeys, ethutil.Bytes2Hex(keyPair.PrivateKey)) + publicKeys = append(publicKeys, ethutil.Bytes2Hex(keyPair.PublicKey)) + addresses = append(addresses, ethutil.Bytes2Hex(keyPair.Address())) + mnemonics = append(mnemonics, strings.Join(MnemonicEncode(ethutil.Bytes2Hex(keyPair.PrivateKey)), " ")) + }) + + basename := session + if session == "" { + basename = "default" + } + + path := path.Join(k.basedir, basename) + content = []byte(strings.Join(privateKeys, "\n")) + err = ioutil.WriteFile(path+".prv", content, 0600) + if err != nil { + return err + } + + content = []byte(strings.Join(publicKeys, "\n")) + err = ioutil.WriteFile(path+".pub", content, 0644) + if err != nil { + return err + } + + content = []byte(strings.Join(addresses, "\n")) + err = ioutil.WriteFile(path+".addr", content, 0644) + if err != nil { + return err + } + + content = []byte(strings.Join(mnemonics, "\n")) + err = ioutil.WriteFile(path+".mne", content, 0600) + if err != nil { + return err + } + + return nil +} + +func (k *FileKeyStore) Load(session string) (*KeyRing, error) { + basename := session + if session == "" { + basename = "default" + } + secfile := path.Join(k.basedir, basename+".prv") + _, err := os.Stat(secfile) + // if file is not found then we return nil, no error + if err != nil { + return nil, nil + } + return NewKeyRingFromFile(secfile) +} diff --git a/ethcrypto/keypair.go b/ethcrypto/keypair.go new file mode 100644 index 000000000..ae9db3698 --- /dev/null +++ b/ethcrypto/keypair.go @@ -0,0 +1,41 @@ +package ethcrypto + +import ( + "github.com/ethereum/eth-go/ethutil" + "github.com/obscuren/secp256k1-go" +) + +type KeyPair struct { + PrivateKey []byte + PublicKey []byte + + // The associated account + // account *StateObject +} + +func GenerateNewKeyPair() *KeyPair { + _, prv := secp256k1.GenerateKeyPair() + keyPair, _ := NewKeyPairFromSec(prv) // swallow error, this one cannot err + return keyPair +} + +func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) { + pubkey, err := secp256k1.GeneratePubKey(seckey) + if err != nil { + return nil, err + } + + return &KeyPair{PrivateKey: seckey, PublicKey: pubkey}, nil +} + +func (k *KeyPair) Address() []byte { + return Sha3Bin(k.PublicKey[1:])[12:] +} + +func (k *KeyPair) RlpEncode() []byte { + return k.RlpValue().Encode() +} + +func (k *KeyPair) RlpValue() *ethutil.Value { + return ethutil.NewValue(k.PrivateKey) +} diff --git a/ethcrypto/keyring.go b/ethcrypto/keyring.go new file mode 100644 index 000000000..277fa2134 --- /dev/null +++ b/ethcrypto/keyring.go @@ -0,0 +1,118 @@ +package ethcrypto + +import ( + "fmt" + "github.com/ethereum/eth-go/ethutil" + "io/ioutil" + "strings" +) + +type KeyRing struct { + keys []*KeyPair +} + +func NewKeyRing() *KeyRing { + return &KeyRing{} +} + +func (k *KeyRing) AddKeyPair(keyPair *KeyPair) { + k.keys = append(k.keys, keyPair) +} + +func (k *KeyRing) GetKeyPair(i int) *KeyPair { + if len(k.keys) > i { + return k.keys[i] + } + + return nil +} + +func (k *KeyRing) Empty() bool { + return k.Len() == 0 +} + +func (k *KeyRing) Len() int { + return len(k.keys) +} + +func (k *KeyRing) Each(f func(*KeyPair)) { + for _, keyPair := range k.keys { + f(keyPair) + } +} + +func NewGeneratedKeyRing(len int) *KeyRing { + keyRing := NewKeyRing() + for i := 0; i < len; i++ { + keyRing.AddKeyPair(GenerateNewKeyPair()) + } + return keyRing +} + +func NewKeyRingFromFile(secfile string) (*KeyRing, error) { + var content []byte + var err error + content, err = ioutil.ReadFile(secfile) + if err != nil { + return nil, err + } + keyRing, err := NewKeyRingFromString(string(content)) + if err != nil { + return nil, err + } + return keyRing, nil +} + +func NewKeyRingFromString(content string) (*KeyRing, error) { + secretStrings := strings.Split(content, "\n") + var secrets [][]byte + for _, secretString := range secretStrings { + secret := secretString + words := strings.Split(secretString, " ") + if len(words) == 24 { + secret = MnemonicDecode(words) + } else if len(words) != 1 { + return nil, fmt.Errorf("Unrecognised key format") + } + secrets = append(secrets, ethutil.Hex2Bytes(secret)) + } + return NewKeyRingFromSecrets(secrets) +} + +func NewKeyRingFromSecrets(secs [][]byte) (*KeyRing, error) { + keyRing := NewKeyRing() + for _, sec := range secs { + keyPair, err := NewKeyPairFromSec(sec) + if err != nil { + return nil, err + } + keyRing.AddKeyPair(keyPair) + } + return keyRing, nil +} + +func NewKeyRingFromBytes(data []byte) (*KeyRing, error) { + var secrets [][]byte + it := ethutil.NewValueFromBytes(data).NewIterator() + for it.Next() { + secret := it.Value().Bytes() + secrets = append(secrets, secret) + } + keyRing, err := NewKeyRingFromSecrets(secrets) + if err != nil { + return nil, err + } + return keyRing, nil +} + +func (k *KeyRing) RlpEncode() []byte { + return k.RlpValue().Encode() +} + +func (k *KeyRing) RlpValue() *ethutil.Value { + v := ethutil.EmptyValue() + k.Each(func(keyPair *KeyPair) { + v.Append(keyPair.RlpValue()) + }) + return v +} diff --git a/ethcrypto/keys_test.go b/ethcrypto/keys_test.go new file mode 100644 index 000000000..3ebf4e818 --- /dev/null +++ b/ethcrypto/keys_test.go @@ -0,0 +1,122 @@ +package ethcrypto + +import ( + "github.com/ethereum/eth-go/ethdb" + // "io/ioutil" + "fmt" + "os" + "path" + "testing" +) + +// test if persistence layer works +func TestDBKeyManager(t *testing.T) { + memdb, _ := ethdb.NewMemDatabase() + keyManager0 := NewDBKeyManager(memdb) + err := keyManager0.Init("", 0, false) + if err != nil { + t.Error("Unexpected error: ", err) + } + keyManager1 := NewDBKeyManager(memdb) + err = keyManager1.Init("", 0, false) + if err != nil { + t.Error("Unexpected error: ", err) + } + if string(keyManager0.PrivateKey()) != string(keyManager1.PrivateKey()) { + t.Error("Expected private keys %x, %x, to be identical via db persistence", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + } + err = keyManager1.Init("", 0, true) + if err != nil { + t.Error("Unexpected error: ", err) + } + if string(keyManager0.PrivateKey()) == string(keyManager1.PrivateKey()) { + t.Error("Expected private keys %x, %x, to be be different despite db persistence if force generate", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + } +} + +func TestFileKeyManager(t *testing.T) { + basedir0 := "/tmp/ethtest0" + os.RemoveAll(basedir0) + os.Mkdir(basedir0, 0777) + + keyManager0 := NewFileKeyManager(basedir0) + err := keyManager0.Init("", 0, false) + if err != nil { + t.Error("Unexpected error: ", err) + } + + keyManager1 := NewFileKeyManager(basedir0) + + err = keyManager1.Init("", 0, false) + if err != nil { + t.Error("Unexpected error: ", err) + } + if string(keyManager0.PrivateKey()) != string(keyManager1.PrivateKey()) { + t.Error("Expected private keys %x, %x, to be identical via db persistence", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + } + + err = keyManager1.Init("", 0, true) + if err != nil { + t.Error("Unexpected error: ", err) + } + if string(keyManager0.PrivateKey()) == string(keyManager1.PrivateKey()) { + t.Error("Expected private keys %x, %x, to be be different despite db persistence if force generate", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + } +} + +// cursor errors +func TestCursorErrors(t *testing.T) { + memdb, _ := ethdb.NewMemDatabase() + keyManager0 := NewDBKeyManager(memdb) + err := keyManager0.Init("", 0, false) + err = keyManager0.Init("", 1, false) + if err == nil { + t.Error("Expected cursor error") + } + err = keyManager0.SetCursor(1) + if err == nil { + t.Error("Expected cursor error") + } +} + +func TestExportImport(t *testing.T) { + memdb, _ := ethdb.NewMemDatabase() + keyManager0 := NewDBKeyManager(memdb) + err := keyManager0.Init("", 0, false) + basedir0 := "/tmp/ethtest0" + os.RemoveAll(basedir0) + os.Mkdir(basedir0, 0777) + keyManager0.Export(basedir0) + + keyManager1 := NewFileKeyManager(basedir0) + err = keyManager1.Init("", 0, false) + if err != nil { + t.Error("Unexpected error: ", err) + } + fmt.Printf("keyRing: %v\n", keyManager0.KeyPair()) + fmt.Printf("keyRing: %v\n", keyManager1.KeyPair()) + if string(keyManager0.PrivateKey()) != string(keyManager1.PrivateKey()) { + t.Error("Expected private keys %x, %x, to be identical via export to filestore basedir", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + } + path.Join("") + + // memdb, _ = ethdb.NewMemDatabase() + // keyManager2 := NewDBKeyManager(memdb) + // err = keyManager2.InitFromSecretsFile("", 0, path.Join(basedir0, "default.prv")) + // if err != nil { + // t.Error("Unexpected error: ", err) + // } + // if string(keyManager0.PrivateKey()) != string(keyManager2.PrivateKey()) { + // t.Error("Expected private keys %s, %s, to be identical via export/import prv", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + // } + + // memdb, _ = ethdb.NewMemDatabase() + // keyManager3 := NewDBKeyManager(memdb) + // err = keyManager3.InitFromSecretsFile("", 0, path.Join(basedir0, "default.mne")) + // if err != nil { + // t.Error("Unexpected error: ", err) + // } + // if string(keyManager0.PrivateKey()) != string(keyManager3.PrivateKey()) { + // t.Error("Expected private keys %s, %s, to be identical via export/import mnemonic file", keyManager0.PrivateKey(), keyManager1.PrivateKey()) + // } +} -- cgit v1.2.3 From e3b911652dfba1475001137ba8b3687b9fec5331 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 16:08:33 +0100 Subject: move CreateAddress from ethutil/common to ethcrypto --- ethcrypto/crypto.go | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index 9c4013d6c..b341915eb 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -25,3 +25,10 @@ func Sha3Bin(data []byte) []byte { return d.Sum(nil) } + +// Creates an ethereum address given the bytes and the nonce +func CreateAddress(b []byte, nonce *big.Int) []byte { + addrBytes := append(b, nonce.Bytes()...) + + return Sha3Bin(addrBytes)[12:] +} -- cgit v1.2.3 From 4be3521727698141512eb6454121302bd3b9cc6d Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 16:17:33 +0100 Subject: import math/big --- ethcrypto/crypto.go | 1 + 1 file changed, 1 insertion(+) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index b341915eb..8cb0be88c 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -4,6 +4,7 @@ import ( "code.google.com/p/go.crypto/ripemd160" "crypto/sha256" "github.com/obscuren/sha3" + "math/big" ) func Sha256Bin(data []byte) []byte { -- cgit v1.2.3 From a8be0d9f4849d8127d2ba36b90327097f94a91cb Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 20:26:55 +0100 Subject: add InitFromString method to be used in gui --- ethcrypto/key_manager.go | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'ethcrypto') diff --git a/ethcrypto/key_manager.go b/ethcrypto/key_manager.go index dcbc7b77e..066a62aab 100644 --- a/ethcrypto/key_manager.go +++ b/ethcrypto/key_manager.go @@ -115,6 +115,14 @@ func (k *KeyManager) InitFromSecretsFile(session string, cursor int, secretsfile return k.reset(session, cursor, keyRing) } +func (k *KeyManager) InitFromString(session string, cursor int, secrets string) error { + keyRing, err := NewKeyRingFromString(secrets) + if err != nil { + return err + } + return k.reset(session, cursor, keyRing) +} + func (k *KeyManager) Export(dir string) error { fileKeyStore := FileKeyStore{dir} return fileKeyStore.Save(k.session, k.keyRing) -- cgit v1.2.3 From 25314313f8eefd5ae8d13b4c687e4811703eec2a Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 20:28:04 +0100 Subject: added Mnemonic() and AsStrings() methods, added memoization for address --- ethcrypto/keypair.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/keypair.go b/ethcrypto/keypair.go index ae9db3698..18fa5b788 100644 --- a/ethcrypto/keypair.go +++ b/ethcrypto/keypair.go @@ -3,12 +3,14 @@ package ethcrypto import ( "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/secp256k1-go" + "strings" ) type KeyPair struct { PrivateKey []byte PublicKey []byte - + address []byte + mnemonic string // The associated account // account *StateObject } @@ -29,7 +31,21 @@ func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) { } func (k *KeyPair) Address() []byte { - return Sha3Bin(k.PublicKey[1:])[12:] + if k.address == nil { + k.address = Sha3Bin(k.PublicKey[1:])[12:] + } + return k.address +} + +func (k *KeyPair) Mnemonic() string { + if k.mnemonic == "" { + k.mnemonic = strings.Join(MnemonicEncode(ethutil.Bytes2Hex(k.PrivateKey)), " ") + } + return k.mnemonic +} + +func (k *KeyPair) AsStrings() (string, string, string, string) { + return k.Mnemonic(), ethutil.Bytes2Hex(k.Address()), ethutil.Bytes2Hex(k.PrivateKey), ethutil.Bytes2Hex(k.PublicKey) } func (k *KeyPair) RlpEncode() []byte { -- cgit v1.2.3 From 2920795168dfe5c5f1f1d66f09026f971d5e53fd Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 20:28:54 +0100 Subject: using keyPair.Mnemonic() in file key store Save method --- ethcrypto/key_store.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethcrypto') diff --git a/ethcrypto/key_store.go b/ethcrypto/key_store.go index c8c506fda..f14f14205 100644 --- a/ethcrypto/key_store.go +++ b/ethcrypto/key_store.go @@ -61,7 +61,7 @@ func (k *FileKeyStore) Save(session string, keyRing *KeyRing) error { privateKeys = append(privateKeys, ethutil.Bytes2Hex(keyPair.PrivateKey)) publicKeys = append(publicKeys, ethutil.Bytes2Hex(keyPair.PublicKey)) addresses = append(addresses, ethutil.Bytes2Hex(keyPair.Address())) - mnemonics = append(mnemonics, strings.Join(MnemonicEncode(ethutil.Bytes2Hex(keyPair.PrivateKey)), " ")) + mnemonics = append(mnemonics, keyPair.Mnemonic()) }) basename := session -- cgit v1.2.3 From 12972b4b65a303dc3f9e135b0e2d97f8b7a661e2 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 20:53:26 +0100 Subject: DBKeyStore.Load returns no error if keyring not found in db --- ethcrypto/key_store.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethcrypto') diff --git a/ethcrypto/key_store.go b/ethcrypto/key_store.go index f14f14205..460f0c978 100644 --- a/ethcrypto/key_store.go +++ b/ethcrypto/key_store.go @@ -32,7 +32,7 @@ func (k *DBKeyStore) Save(session string, keyRing *KeyRing) error { func (k *DBKeyStore) Load(session string) (*KeyRing, error) { data, err := k.db.Get(k.dbKey(session)) if err != nil { - return nil, err + return nil, nil } var keyRing *KeyRing keyRing, err = NewKeyRingFromBytes(data) -- cgit v1.2.3 From 6151ae7db5251436e9ece190eb3569d4aa882671 Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 1 Jul 2014 20:08:32 +0200 Subject: Fixed key import for empty entries --- ethcrypto/keyring.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'ethcrypto') diff --git a/ethcrypto/keyring.go b/ethcrypto/keyring.go index 277fa2134..d3399d13d 100644 --- a/ethcrypto/keyring.go +++ b/ethcrypto/keyring.go @@ -74,8 +74,12 @@ func NewKeyRingFromString(content string) (*KeyRing, error) { } else if len(words) != 1 { return nil, fmt.Errorf("Unrecognised key format") } - secrets = append(secrets, ethutil.Hex2Bytes(secret)) + + if len(secret) != 0 { + secrets = append(secrets, ethutil.Hex2Bytes(secret)) + } } + return NewKeyRingFromSecrets(secrets) } -- cgit v1.2.3 From 81bc721c5cd0330547e18bfb710d68d60da4dd46 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 3 Jul 2014 10:03:58 +0200 Subject: Fixed address generation --- ethcrypto/crypto.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index 8cb0be88c..b4bb881a0 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -3,8 +3,8 @@ package ethcrypto import ( "code.google.com/p/go.crypto/ripemd160" "crypto/sha256" + "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/sha3" - "math/big" ) func Sha256Bin(data []byte) []byte { @@ -28,8 +28,6 @@ func Sha3Bin(data []byte) []byte { } // Creates an ethereum address given the bytes and the nonce -func CreateAddress(b []byte, nonce *big.Int) []byte { - addrBytes := append(b, nonce.Bytes()...) - - return Sha3Bin(addrBytes)[12:] +func CreateAddress(b []byte, nonce uint64) []byte { + return Sha3Bin(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:] } -- cgit v1.2.3 From dcbd97d29c35913c0d13d5da434cb3567fc98ee6 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 9 Jul 2014 10:59:49 +0200 Subject: Check current folder for mnemonic words if it fails in source folder. For binary support --- ethcrypto/mnemonic.go | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'ethcrypto') diff --git a/ethcrypto/mnemonic.go b/ethcrypto/mnemonic.go index 6134f85f7..725846792 100644 --- a/ethcrypto/mnemonic.go +++ b/ethcrypto/mnemonic.go @@ -3,7 +3,9 @@ package ethcrypto import ( "fmt" "io/ioutil" + "os" "path" + "path/filepath" "runtime" "strconv" "strings" @@ -12,6 +14,14 @@ import ( func InitWords() []string { _, thisfile, _, _ := runtime.Caller(1) filename := path.Join(path.Dir(thisfile), "mnemonic.words.lst") + if _, err := os.Stat(filename); os.IsNotExist(err) { + fmt.Printf("reading mnemonic word list file 'mnemonic.words.lst' from source folder failed, looking in current folder.") + dir, err := filepath.Abs(filepath.Dir(os.Args[0])) + if err != nil { + panic(fmt.Errorf("problem getting current folder: ", err)) + } + filename = path.Join(dir, "mnemonic.words.lst") + } content, err := ioutil.ReadFile(filename) if err != nil { panic(fmt.Errorf("reading mnemonic word list file 'mnemonic.words.lst' failed: ", err)) -- cgit v1.2.3 From 54715586ab147a62342a9462f3a73cc2f750d148 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 12 Jul 2014 11:10:47 +0200 Subject: Changed sha3 to official one --- ethcrypto/crypto.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index b4bb881a0..19f8c9e55 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -2,9 +2,9 @@ package ethcrypto import ( "code.google.com/p/go.crypto/ripemd160" + "code.google.com/p/go.crypto/sha3" "crypto/sha256" "github.com/ethereum/eth-go/ethutil" - "github.com/obscuren/sha3" ) func Sha256Bin(data []byte) []byte { -- cgit v1.2.3 From 9a931698989fb8db2059a3dee1a431ef94beb59e Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 15 Jul 2014 12:52:44 +0200 Subject: Rewrote mnemonic word loading to facilitate deployable builds. --- ethcrypto/mnemonic.go | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/mnemonic.go b/ethcrypto/mnemonic.go index 725846792..b8df2ad6f 100644 --- a/ethcrypto/mnemonic.go +++ b/ethcrypto/mnemonic.go @@ -6,30 +6,35 @@ import ( "os" "path" "path/filepath" - "runtime" "strconv" "strings" ) -func InitWords() []string { - _, thisfile, _, _ := runtime.Caller(1) - filename := path.Join(path.Dir(thisfile), "mnemonic.words.lst") +func InitWords(wordsPath string) { + filename := path.Join(wordsPath, "mnemonic.words.lst") if _, err := os.Stat(filename); os.IsNotExist(err) { - fmt.Printf("reading mnemonic word list file 'mnemonic.words.lst' from source folder failed, looking in current folder.") - dir, err := filepath.Abs(filepath.Dir(os.Args[0])) - if err != nil { - panic(fmt.Errorf("problem getting current folder: ", err)) - } + fmt.Printf("reading mnemonic word list file from supplied path not found. Looked in %s. Trying next option.\n", filename) + + dir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "eth-go", "ethcrypto") filename = path.Join(dir, "mnemonic.words.lst") + if _, err := os.Stat(filename); os.IsNotExist(err) { + fmt.Printf("reading mnemonic word list file 'mnemonic.words.lst' from source folder failed: %s.\n", filename) + dir, err := filepath.Abs(filepath.Dir(os.Args[0])) + if err != nil { + panic(fmt.Errorf("problem getting current folder: ", err)) + } + filename = path.Join(dir, "mnemonic.words.lst") + } } + content, err := ioutil.ReadFile(filename) if err != nil { - panic(fmt.Errorf("reading mnemonic word list file 'mnemonic.words.lst' failed: ", err)) + panic(fmt.Errorf("All options for finding the mnemonic word list file 'mnemonic.words.lst' failed: ", err)) } - return strings.Split(string(content), "\n") + words = strings.Split(string(content), "\n") } -var words = InitWords() +var words []string // TODO: See if we can refactor this into a shared util lib if we need it multiple times func IndexOf(slice []string, value string) int64 { -- cgit v1.2.3 From da50c751480da32036f41ccbeb1f292694ca0286 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 6 Aug 2014 09:53:00 +0200 Subject: Added state dump method --- ethcrypto/mnemonic.go | 3 --- 1 file changed, 3 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/mnemonic.go b/ethcrypto/mnemonic.go index b8df2ad6f..2d3ac85a3 100644 --- a/ethcrypto/mnemonic.go +++ b/ethcrypto/mnemonic.go @@ -13,12 +13,9 @@ import ( func InitWords(wordsPath string) { filename := path.Join(wordsPath, "mnemonic.words.lst") if _, err := os.Stat(filename); os.IsNotExist(err) { - fmt.Printf("reading mnemonic word list file from supplied path not found. Looked in %s. Trying next option.\n", filename) - dir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "eth-go", "ethcrypto") filename = path.Join(dir, "mnemonic.words.lst") if _, err := os.Stat(filename); os.IsNotExist(err) { - fmt.Printf("reading mnemonic word list file 'mnemonic.words.lst' from source folder failed: %s.\n", filename) dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { panic(fmt.Errorf("problem getting current folder: ", err)) -- cgit v1.2.3 From e85f3972b9b4648666c6b50fff04938e3206ff96 Mon Sep 17 00:00:00 2001 From: zelig Date: Tue, 12 Aug 2014 14:56:10 +0200 Subject: inline mnemonic wordlist to support binary builds without extra asset --- ethcrypto/mnemonic.go | 40 +- ethcrypto/mnemonic.words.lst | 1626 ----------------------------------------- ethcrypto/mnemonic_words.go | 1630 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1636 insertions(+), 1660 deletions(-) delete mode 100644 ethcrypto/mnemonic.words.lst create mode 100644 ethcrypto/mnemonic_words.go (limited to 'ethcrypto') diff --git a/ethcrypto/mnemonic.go b/ethcrypto/mnemonic.go index 2d3ac85a3..5fb620219 100644 --- a/ethcrypto/mnemonic.go +++ b/ethcrypto/mnemonic.go @@ -2,37 +2,9 @@ package ethcrypto import ( "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" "strconv" - "strings" ) -func InitWords(wordsPath string) { - filename := path.Join(wordsPath, "mnemonic.words.lst") - if _, err := os.Stat(filename); os.IsNotExist(err) { - dir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "eth-go", "ethcrypto") - filename = path.Join(dir, "mnemonic.words.lst") - if _, err := os.Stat(filename); os.IsNotExist(err) { - dir, err := filepath.Abs(filepath.Dir(os.Args[0])) - if err != nil { - panic(fmt.Errorf("problem getting current folder: ", err)) - } - filename = path.Join(dir, "mnemonic.words.lst") - } - } - - content, err := ioutil.ReadFile(filename) - if err != nil { - panic(fmt.Errorf("All options for finding the mnemonic word list file 'mnemonic.words.lst' failed: ", err)) - } - words = strings.Split(string(content), "\n") -} - -var words []string - // TODO: See if we can refactor this into a shared util lib if we need it multiple times func IndexOf(slice []string, value string) int64 { for p, v := range slice { @@ -45,7 +17,7 @@ func IndexOf(slice []string, value string) int64 { func MnemonicEncode(message string) []string { var out []string - n := int64(len(words)) + n := int64(len(MnemonicWords)) for i := 0; i < len(message); i += (len(message) / 8) { x := message[i : i+8] @@ -53,22 +25,22 @@ func MnemonicEncode(message string) []string { w1 := (bit % n) w2 := ((bit / n) + w1) % n w3 := ((bit / n / n) + w2) % n - out = append(out, words[w1], words[w2], words[w3]) + out = append(out, MnemonicWords[w1], MnemonicWords[w2], MnemonicWords[w3]) } return out } func MnemonicDecode(wordsar []string) string { var out string - n := int64(len(words)) + n := int64(len(MnemonicWords)) for i := 0; i < len(wordsar); i += 3 { word1 := wordsar[i] word2 := wordsar[i+1] word3 := wordsar[i+2] - w1 := IndexOf(words, word1) - w2 := IndexOf(words, word2) - w3 := IndexOf(words, word3) + w1 := IndexOf(MnemonicWords, word1) + w2 := IndexOf(MnemonicWords, word2) + w3 := IndexOf(MnemonicWords, word3) y := (w2 - w1) % n z := (w3 - w2) % n diff --git a/ethcrypto/mnemonic.words.lst b/ethcrypto/mnemonic.words.lst deleted file mode 100644 index 6bf412ce1..000000000 --- a/ethcrypto/mnemonic.words.lst +++ /dev/null @@ -1,1626 +0,0 @@ -like -just -love -know -never -want -time -out -there -make -look -eye -down -only -think -heart -back -then -into -about -more -away -still -them -take -thing -even -through -long -always -world -too -friend -tell -try -hand -thought -over -here -other -need -smile -again -much -cry -been -night -ever -little -said -end -some -those -around -mind -people -girl -leave -dream -left -turn -myself -give -nothing -really -off -before -something -find -walk -wish -good -once -place -ask -stop -keep -watch -seem -everything -wait -got -yet -made -remember -start -alone -run -hope -maybe -believe -body -hate -after -close -talk -stand -own -each -hurt -help -home -god -soul -new -many -two -inside -should -true -first -fear -mean -better -play -another -gone -change -use -wonder -someone -hair -cold -open -best -any -behind -happen -water -dark -laugh -stay -forever -name -work -show -sky -break -came -deep -door -put -black -together -upon -happy -such -great -white -matter -fill -past -please -burn -cause -enough -touch -moment -soon -voice -scream -anything -stare -sound -red -everyone -hide -kiss -truth -death -beautiful -mine -blood -broken -very -pass -next -forget -tree -wrong -air -mother -understand -lip -hit -wall -memory -sleep -free -high -realize -school -might -skin -sweet -perfect -blue -kill -breath -dance -against -fly -between -grow -strong -under -listen -bring -sometimes -speak -pull -person -become -family -begin -ground -real -small -father -sure -feet -rest -young -finally -land -across -today -different -guy -line -fire -reason -reach -second -slowly -write -eat -smell -mouth -step -learn -three -floor -promise -breathe -darkness -push -earth -guess -save -song -above -along -both -color -house -almost -sorry -anymore -brother -okay -dear -game -fade -already -apart -warm -beauty -heard -notice -question -shine -began -piece -whole -shadow -secret -street -within -finger -point -morning -whisper -child -moon -green -story -glass -kid -silence -since -soft -yourself -empty -shall -angel -answer -baby -bright -dad -path -worry -hour -drop -follow -power -war -half -flow -heaven -act -chance -fact -least -tired -children -near -quite -afraid -rise -sea -taste -window -cover -nice -trust -lot -sad -cool -force -peace -return -blind -easy -ready -roll -rose -drive -held -music -beneath -hang -mom -paint -emotion -quiet -clear -cloud -few -pretty -bird -outside -paper -picture -front -rock -simple -anyone -meant -reality -road -sense -waste -bit -leaf -thank -happiness -meet -men -smoke -truly -decide -self -age -book -form -alive -carry -escape -damn -instead -able -ice -minute -throw -catch -leg -ring -course -goodbye -lead -poem -sick -corner -desire -known -problem -remind -shoulder -suppose -toward -wave -drink -jump -woman -pretend -sister -week -human -joy -crack -grey -pray -surprise -dry -knee -less -search -bleed -caught -clean -embrace -future -king -son -sorrow -chest -hug -remain -sat -worth -blow -daddy -final -parent -tight -also -create -lonely -safe -cross -dress -evil -silent -bone -fate -perhaps -anger -class -scar -snow -tiny -tonight -continue -control -dog -edge -mirror -month -suddenly -comfort -given -loud -quickly -gaze -plan -rush -stone -town -battle -ignore -spirit -stood -stupid -yours -brown -build -dust -hey -kept -pay -phone -twist -although -ball -beyond -hidden -nose -taken -fail -float -pure -somehow -wash -wrap -angry -cheek -creature -forgotten -heat -rip -single -space -special -weak -whatever -yell -anyway -blame -job -choose -country -curse -drift -echo -figure -grew -laughter -neck -suffer -worse -yeah -disappear -foot -forward -knife -mess -somewhere -stomach -storm -beg -idea -lift -offer -breeze -field -five -often -simply -stuck -win -allow -confuse -enjoy -except -flower -seek -strength -calm -grin -gun -heavy -hill -large -ocean -shoe -sigh -straight -summer -tongue -accept -crazy -everyday -exist -grass -mistake -sent -shut -surround -table -ache -brain -destroy -heal -nature -shout -sign -stain -choice -doubt -glance -glow -mountain -queen -stranger -throat -tomorrow -city -either -fish -flame -rather -shape -spin -spread -ash -distance -finish -image -imagine -important -nobody -shatter -warmth -became -feed -flesh -funny -lust -shirt -trouble -yellow -attention -bare -bite -money -protect -amaze -appear -born -choke -completely -daughter -fresh -friendship -gentle -probably -six -deserve -expect -grab -middle -nightmare -river -thousand -weight -worst -wound -barely -bottle -cream -regret -relationship -stick -test -crush -endless -fault -itself -rule -spill -art -circle -join -kick -mask -master -passion -quick -raise -smooth -unless -wander -actually -broke -chair -deal -favorite -gift -note -number -sweat -box -chill -clothes -lady -mark -park -poor -sadness -tie -animal -belong -brush -consume -dawn -forest -innocent -pen -pride -stream -thick -clay -complete -count -draw -faith -press -silver -struggle -surface -taught -teach -wet -bless -chase -climb -enter -letter -melt -metal -movie -stretch -swing -vision -wife -beside -crash -forgot -guide -haunt -joke -knock -plant -pour -prove -reveal -steal -stuff -trip -wood -wrist -bother -bottom -crawl -crowd -fix -forgive -frown -grace -loose -lucky -party -release -surely -survive -teacher -gently -grip -speed -suicide -travel -treat -vein -written -cage -chain -conversation -date -enemy -however -interest -million -page -pink -proud -sway -themselves -winter -church -cruel -cup -demon -experience -freedom -pair -pop -purpose -respect -shoot -softly -state -strange -bar -birth -curl -dirt -excuse -lord -lovely -monster -order -pack -pants -pool -scene -seven -shame -slide -ugly -among -blade -blonde -closet -creek -deny -drug -eternity -gain -grade -handle -key -linger -pale -prepare -swallow -swim -tremble -wheel -won -cast -cigarette -claim -college -direction -dirty -gather -ghost -hundred -loss -lung -orange -present -swear -swirl -twice -wild -bitter -blanket -doctor -everywhere -flash -grown -knowledge -numb -pressure -radio -repeat -ruin -spend -unknown -buy -clock -devil -early -false -fantasy -pound -precious -refuse -sheet -teeth -welcome -add -ahead -block -bury -caress -content -depth -despite -distant -marry -purple -threw -whenever -bomb -dull -easily -grasp -hospital -innocence -normal -receive -reply -rhyme -shade -someday -sword -toe -visit -asleep -bought -center -consider -flat -hero -history -ink -insane -muscle -mystery -pocket -reflection -shove -silently -smart -soldier -spot -stress -train -type -view -whether -bus -energy -explain -holy -hunger -inch -magic -mix -noise -nowhere -prayer -presence -shock -snap -spider -study -thunder -trail -admit -agree -bag -bang -bound -butterfly -cute -exactly -explode -familiar -fold -further -pierce -reflect -scent -selfish -sharp -sink -spring -stumble -universe -weep -women -wonderful -action -ancient -attempt -avoid -birthday -branch -chocolate -core -depress -drunk -especially -focus -fruit -honest -match -palm -perfectly -pillow -pity -poison -roar -shift -slightly -thump -truck -tune -twenty -unable -wipe -wrote -coat -constant -dinner -drove -egg -eternal -flight -flood -frame -freak -gasp -glad -hollow -motion -peer -plastic -root -screen -season -sting -strike -team -unlike -victim -volume -warn -weird -attack -await -awake -built -charm -crave -despair -fought -grant -grief -horse -limit -message -ripple -sanity -scatter -serve -split -string -trick -annoy -blur -boat -brave -clearly -cling -connect -fist -forth -imagination -iron -jock -judge -lesson -milk -misery -nail -naked -ourselves -poet -possible -princess -sail -size -snake -society -stroke -torture -toss -trace -wise -bloom -bullet -cell -check -cost -darling -during -footstep -fragile -hallway -hardly -horizon -invisible -journey -midnight -mud -nod -pause -relax -shiver -sudden -value -youth -abuse -admire -blink -breast -bruise -constantly -couple -creep -curve -difference -dumb -emptiness -gotta -honor -plain -planet -recall -rub -ship -slam -soar -somebody -tightly -weather -adore -approach -bond -bread -burst -candle -coffee -cousin -crime -desert -flutter -frozen -grand -heel -hello -language -level -movement -pleasure -powerful -random -rhythm -settle -silly -slap -sort -spoken -steel -threaten -tumble -upset -aside -awkward -bee -blank -board -button -card -carefully -complain -crap -deeply -discover -drag -dread -effort -entire -fairy -giant -gotten -greet -illusion -jeans -leap -liquid -march -mend -nervous -nine -replace -rope -spine -stole -terror -accident -apple -balance -boom -childhood -collect -demand -depression -eventually -faint -glare -goal -group -honey -kitchen -laid -limb -machine -mere -mold -murder -nerve -painful -poetry -prince -rabbit -shelter -shore -shower -soothe -stair -steady -sunlight -tangle -tease -treasure -uncle -begun -bliss -canvas -cheer -claw -clutch -commit -crimson -crystal -delight -doll -existence -express -fog -football -gay -goose -guard -hatred -illuminate -mass -math -mourn -rich -rough -skip -stir -student -style -support -thorn -tough -yard -yearn -yesterday -advice -appreciate -autumn -bank -beam -bowl -capture -carve -collapse -confusion -creation -dove -feather -girlfriend -glory -government -harsh -hop -inner -loser -moonlight -neighbor -neither -peach -pig -praise -screw -shield -shimmer -sneak -stab -subject -throughout -thrown -tower -twirl -wow -army -arrive -bathroom -bump -cease -cookie -couch -courage -dim -guilt -howl -hum -husband -insult -led -lunch -mock -mostly -natural -nearly -needle -nerd -peaceful -perfection -pile -price -remove -roam -sanctuary -serious -shiny -shook -sob -stolen -tap -vain -void -warrior -wrinkle -affection -apologize -blossom -bounce -bridge -cheap -crumble -decision -descend -desperately -dig -dot -flip -frighten -heartbeat -huge -lazy -lick -odd -opinion -process -puzzle -quietly -retreat -score -sentence -separate -situation -skill -soak -square -stray -taint -task -tide -underneath -veil -whistle -anywhere -bedroom -bid -bloody -burden -careful -compare -concern -curtain -decay -defeat -describe -double -dreamer -driver -dwell -evening -flare -flicker -grandma -guitar -harm -horrible -hungry -indeed -lace -melody -monkey -nation -object -obviously -rainbow -salt -scratch -shown -shy -stage -stun -third -tickle -useless -weakness -worship -worthless -afternoon -beard -boyfriend -bubble -busy -certain -chin -concrete -desk -diamond -doom -drawn -due -felicity -freeze -frost -garden -glide -harmony -hopefully -hunt -jealous -lightning -mama -mercy -peel -physical -position -pulse -punch -quit -rant -respond -salty -sane -satisfy -savior -sheep -slept -social -sport -tuck -utter -valley -wolf -aim -alas -alter -arrow -awaken -beaten -belief -brand -ceiling -cheese -clue -confidence -connection -daily -disguise -eager -erase -essence -everytime -expression -fan -flag -flirt -foul -fur -giggle -glorious -ignorance -law -lifeless -measure -mighty -muse -north -opposite -paradise -patience -patient -pencil -petal -plate -ponder -possibly -practice -slice -spell -stock -strife -strip -suffocate -suit -tender -tool -trade -velvet -verse -waist -witch -aunt -bench -bold -cap -certainly -click -companion -creator -dart -delicate -determine -dish -dragon -drama -drum -dude -everybody -feast -forehead -former -fright -fully -gas -hook -hurl -invite -juice -manage -moral -possess -raw -rebel -royal -scale -scary -several -slight -stubborn -swell -talent -tea -terrible -thread -torment -trickle -usually -vast -violence -weave -acid -agony -ashamed -awe -belly -blend -blush -character -cheat -common -company -coward -creak -danger -deadly -defense -define -depend -desperate -destination -dew -duck -dusty -embarrass -engine -example -explore -foe -freely -frustrate -generation -glove -guilty -health -hurry -idiot -impossible -inhale -jaw -kingdom -mention -mist -moan -mumble -mutter -observe -ode -pathetic -pattern -pie -prefer -puff -rape -rare -revenge -rude -scrape -spiral -squeeze -strain -sunset -suspend -sympathy -thigh -throne -total -unseen -weapon -weary \ No newline at end of file diff --git a/ethcrypto/mnemonic_words.go b/ethcrypto/mnemonic_words.go new file mode 100644 index 000000000..72f0ad48f --- /dev/null +++ b/ethcrypto/mnemonic_words.go @@ -0,0 +1,1630 @@ +package ethcrypto + +var MnemonicWords []string = []string{ + "like", + "just", + "love", + "know", + "never", + "want", + "time", + "out", + "there", + "make", + "look", + "eye", + "down", + "only", + "think", + "heart", + "back", + "then", + "into", + "about", + "more", + "away", + "still", + "them", + "take", + "thing", + "even", + "through", + "long", + "always", + "world", + "too", + "friend", + "tell", + "try", + "hand", + "thought", + "over", + "here", + "other", + "need", + "smile", + "again", + "much", + "cry", + "been", + "night", + "ever", + "little", + "said", + "end", + "some", + "those", + "around", + "mind", + "people", + "girl", + "leave", + "dream", + "left", + "turn", + "myself", + "give", + "nothing", + "really", + "off", + "before", + "something", + "find", + "walk", + "wish", + "good", + "once", + "place", + "ask", + "stop", + "keep", + "watch", + "seem", + "everything", + "wait", + "got", + "yet", + "made", + "remember", + "start", + "alone", + "run", + "hope", + "maybe", + "believe", + "body", + "hate", + "after", + "close", + "talk", + "stand", + "own", + "each", + "hurt", + "help", + "home", + "god", + "soul", + "new", + "many", + "two", + "inside", + "should", + "true", + "first", + "fear", + "mean", + "better", + "play", + "another", + "gone", + "change", + "use", + "wonder", + "someone", + "hair", + "cold", + "open", + "best", + "any", + "behind", + "happen", + "water", + "dark", + "laugh", + "stay", + "forever", + "name", + "work", + "show", + "sky", + "break", + "came", + "deep", + "door", + "put", + "black", + "together", + "upon", + "happy", + "such", + "great", + "white", + "matter", + "fill", + "past", + "please", + "burn", + "cause", + "enough", + "touch", + "moment", + "soon", + "voice", + "scream", + "anything", + "stare", + "sound", + "red", + "everyone", + "hide", + "kiss", + "truth", + "death", + "beautiful", + "mine", + "blood", + "broken", + "very", + "pass", + "next", + "forget", + "tree", + "wrong", + "air", + "mother", + "understand", + "lip", + "hit", + "wall", + "memory", + "sleep", + "free", + "high", + "realize", + "school", + "might", + "skin", + "sweet", + "perfect", + "blue", + "kill", + "breath", + "dance", + "against", + "fly", + "between", + "grow", + "strong", + "under", + "listen", + "bring", + "sometimes", + "speak", + "pull", + "person", + "become", + "family", + "begin", + "ground", + "real", + "small", + "father", + "sure", + "feet", + "rest", + "young", + "finally", + "land", + "across", + "today", + "different", + "guy", + "line", + "fire", + "reason", + "reach", + "second", + "slowly", + "write", + "eat", + "smell", + "mouth", + "step", + "learn", + "three", + "floor", + "promise", + "breathe", + "darkness", + "push", + "earth", + "guess", + "save", + "song", + "above", + "along", + "both", + "color", + "house", + "almost", + "sorry", + "anymore", + "brother", + "okay", + "dear", + "game", + "fade", + "already", + "apart", + "warm", + "beauty", + "heard", + "notice", + "question", + "shine", + "began", + "piece", + "whole", + "shadow", + "secret", + "street", + "within", + "finger", + "point", + "morning", + "whisper", + "child", + "moon", + "green", + "story", + "glass", + "kid", + "silence", + "since", + "soft", + "yourself", + "empty", + "shall", + "angel", + "answer", + "baby", + "bright", + "dad", + "path", + "worry", + "hour", + "drop", + "follow", + "power", + "war", + "half", + "flow", + "heaven", + "act", + "chance", + "fact", + "least", + "tired", + "children", + "near", + "quite", + "afraid", + "rise", + "sea", + "taste", + "window", + "cover", + "nice", + "trust", + "lot", + "sad", + "cool", + "force", + "peace", + "return", + "blind", + "easy", + "ready", + "roll", + "rose", + "drive", + "held", + "music", + "beneath", + "hang", + "mom", + "paint", + "emotion", + "quiet", + "clear", + "cloud", + "few", + "pretty", + "bird", + "outside", + "paper", + "picture", + "front", + "rock", + "simple", + "anyone", + "meant", + "reality", + "road", + "sense", + "waste", + "bit", + "leaf", + "thank", + "happiness", + "meet", + "men", + "smoke", + "truly", + "decide", + "self", + "age", + "book", + "form", + "alive", + "carry", + "escape", + "damn", + "instead", + "able", + "ice", + "minute", + "throw", + "catch", + "leg", + "ring", + "course", + "goodbye", + "lead", + "poem", + "sick", + "corner", + "desire", + "known", + "problem", + "remind", + "shoulder", + "suppose", + "toward", + "wave", + "drink", + "jump", + "woman", + "pretend", + "sister", + "week", + "human", + "joy", + "crack", + "grey", + "pray", + "surprise", + "dry", + "knee", + "less", + "search", + "bleed", + "caught", + "clean", + "embrace", + "future", + "king", + "son", + "sorrow", + "chest", + "hug", + "remain", + "sat", + "worth", + "blow", + "daddy", + "final", + "parent", + "tight", + "also", + "create", + "lonely", + "safe", + "cross", + "dress", + "evil", + "silent", + "bone", + "fate", + "perhaps", + "anger", + "class", + "scar", + "snow", + "tiny", + "tonight", + "continue", + "control", + "dog", + "edge", + "mirror", + "month", + "suddenly", + "comfort", + "given", + "loud", + "quickly", + "gaze", + "plan", + "rush", + "stone", + "town", + "battle", + "ignore", + "spirit", + "stood", + "stupid", + "yours", + "brown", + "build", + "dust", + "hey", + "kept", + "pay", + "phone", + "twist", + "although", + "ball", + "beyond", + "hidden", + "nose", + "taken", + "fail", + "float", + "pure", + "somehow", + "wash", + "wrap", + "angry", + "cheek", + "creature", + "forgotten", + "heat", + "rip", + "single", + "space", + "special", + "weak", + "whatever", + "yell", + "anyway", + "blame", + "job", + "choose", + "country", + "curse", + "drift", + "echo", + "figure", + "grew", + "laughter", + "neck", + "suffer", + "worse", + "yeah", + "disappear", + "foot", + "forward", + "knife", + "mess", + "somewhere", + "stomach", + "storm", + "beg", + "idea", + "lift", + "offer", + "breeze", + "field", + "five", + "often", + "simply", + "stuck", + "win", + "allow", + "confuse", + "enjoy", + "except", + "flower", + "seek", + "strength", + "calm", + "grin", + "gun", + "heavy", + "hill", + "large", + "ocean", + "shoe", + "sigh", + "straight", + "summer", + "tongue", + "accept", + "crazy", + "everyday", + "exist", + "grass", + "mistake", + "sent", + "shut", + "surround", + "table", + "ache", + "brain", + "destroy", + "heal", + "nature", + "shout", + "sign", + "stain", + "choice", + "doubt", + "glance", + "glow", + "mountain", + "queen", + "stranger", + "throat", + "tomorrow", + "city", + "either", + "fish", + "flame", + "rather", + "shape", + "spin", + "spread", + "ash", + "distance", + "finish", + "image", + "imagine", + "important", + "nobody", + "shatter", + "warmth", + "became", + "feed", + "flesh", + "funny", + "lust", + "shirt", + "trouble", + "yellow", + "attention", + "bare", + "bite", + "money", + "protect", + "amaze", + "appear", + "born", + "choke", + "completely", + "daughter", + "fresh", + "friendship", + "gentle", + "probably", + "six", + "deserve", + "expect", + "grab", + "middle", + "nightmare", + "river", + "thousand", + "weight", + "worst", + "wound", + "barely", + "bottle", + "cream", + "regret", + "relationship", + "stick", + "test", + "crush", + "endless", + "fault", + "itself", + "rule", + "spill", + "art", + "circle", + "join", + "kick", + "mask", + "master", + "passion", + "quick", + "raise", + "smooth", + "unless", + "wander", + "actually", + "broke", + "chair", + "deal", + "favorite", + "gift", + "note", + "number", + "sweat", + "box", + "chill", + "clothes", + "lady", + "mark", + "park", + "poor", + "sadness", + "tie", + "animal", + "belong", + "brush", + "consume", + "dawn", + "forest", + "innocent", + "pen", + "pride", + "stream", + "thick", + "clay", + "complete", + "count", + "draw", + "faith", + "press", + "silver", + "struggle", + "surface", + "taught", + "teach", + "wet", + "bless", + "chase", + "climb", + "enter", + "letter", + "melt", + "metal", + "movie", + "stretch", + "swing", + "vision", + "wife", + "beside", + "crash", + "forgot", + "guide", + "haunt", + "joke", + "knock", + "plant", + "pour", + "prove", + "reveal", + "steal", + "stuff", + "trip", + "wood", + "wrist", + "bother", + "bottom", + "crawl", + "crowd", + "fix", + "forgive", + "frown", + "grace", + "loose", + "lucky", + "party", + "release", + "surely", + "survive", + "teacher", + "gently", + "grip", + "speed", + "suicide", + "travel", + "treat", + "vein", + "written", + "cage", + "chain", + "conversation", + "date", + "enemy", + "however", + "interest", + "million", + "page", + "pink", + "proud", + "sway", + "themselves", + "winter", + "church", + "cruel", + "cup", + "demon", + "experience", + "freedom", + "pair", + "pop", + "purpose", + "respect", + "shoot", + "softly", + "state", + "strange", + "bar", + "birth", + "curl", + "dirt", + "excuse", + "lord", + "lovely", + "monster", + "order", + "pack", + "pants", + "pool", + "scene", + "seven", + "shame", + "slide", + "ugly", + "among", + "blade", + "blonde", + "closet", + "creek", + "deny", + "drug", + "eternity", + "gain", + "grade", + "handle", + "key", + "linger", + "pale", + "prepare", + "swallow", + "swim", + "tremble", + "wheel", + "won", + "cast", + "cigarette", + "claim", + "college", + "direction", + "dirty", + "gather", + "ghost", + "hundred", + "loss", + "lung", + "orange", + "present", + "swear", + "swirl", + "twice", + "wild", + "bitter", + "blanket", + "doctor", + "everywhere", + "flash", + "grown", + "knowledge", + "numb", + "pressure", + "radio", + "repeat", + "ruin", + "spend", + "unknown", + "buy", + "clock", + "devil", + "early", + "false", + "fantasy", + "pound", + "precious", + "refuse", + "sheet", + "teeth", + "welcome", + "add", + "ahead", + "block", + "bury", + "caress", + "content", + "depth", + "despite", + "distant", + "marry", + "purple", + "threw", + "whenever", + "bomb", + "dull", + "easily", + "grasp", + "hospital", + "innocence", + "normal", + "receive", + "reply", + "rhyme", + "shade", + "someday", + "sword", + "toe", + "visit", + "asleep", + "bought", + "center", + "consider", + "flat", + "hero", + "history", + "ink", + "insane", + "muscle", + "mystery", + "pocket", + "reflection", + "shove", + "silently", + "smart", + "soldier", + "spot", + "stress", + "train", + "type", + "view", + "whether", + "bus", + "energy", + "explain", + "holy", + "hunger", + "inch", + "magic", + "mix", + "noise", + "nowhere", + "prayer", + "presence", + "shock", + "snap", + "spider", + "study", + "thunder", + "trail", + "admit", + "agree", + "bag", + "bang", + "bound", + "butterfly", + "cute", + "exactly", + "explode", + "familiar", + "fold", + "further", + "pierce", + "reflect", + "scent", + "selfish", + "sharp", + "sink", + "spring", + "stumble", + "universe", + "weep", + "women", + "wonderful", + "action", + "ancient", + "attempt", + "avoid", + "birthday", + "branch", + "chocolate", + "core", + "depress", + "drunk", + "especially", + "focus", + "fruit", + "honest", + "match", + "palm", + "perfectly", + "pillow", + "pity", + "poison", + "roar", + "shift", + "slightly", + "thump", + "truck", + "tune", + "twenty", + "unable", + "wipe", + "wrote", + "coat", + "constant", + "dinner", + "drove", + "egg", + "eternal", + "flight", + "flood", + "frame", + "freak", + "gasp", + "glad", + "hollow", + "motion", + "peer", + "plastic", + "root", + "screen", + "season", + "sting", + "strike", + "team", + "unlike", + "victim", + "volume", + "warn", + "weird", + "attack", + "await", + "awake", + "built", + "charm", + "crave", + "despair", + "fought", + "grant", + "grief", + "horse", + "limit", + "message", + "ripple", + "sanity", + "scatter", + "serve", + "split", + "string", + "trick", + "annoy", + "blur", + "boat", + "brave", + "clearly", + "cling", + "connect", + "fist", + "forth", + "imagination", + "iron", + "jock", + "judge", + "lesson", + "milk", + "misery", + "nail", + "naked", + "ourselves", + "poet", + "possible", + "princess", + "sail", + "size", + "snake", + "society", + "stroke", + "torture", + "toss", + "trace", + "wise", + "bloom", + "bullet", + "cell", + "check", + "cost", + "darling", + "during", + "footstep", + "fragile", + "hallway", + "hardly", + "horizon", + "invisible", + "journey", + "midnight", + "mud", + "nod", + "pause", + "relax", + "shiver", + "sudden", + "value", + "youth", + "abuse", + "admire", + "blink", + "breast", + "bruise", + "constantly", + "couple", + "creep", + "curve", + "difference", + "dumb", + "emptiness", + "gotta", + "honor", + "plain", + "planet", + "recall", + "rub", + "ship", + "slam", + "soar", + "somebody", + "tightly", + "weather", + "adore", + "approach", + "bond", + "bread", + "burst", + "candle", + "coffee", + "cousin", + "crime", + "desert", + "flutter", + "frozen", + "grand", + "heel", + "hello", + "language", + "level", + "movement", + "pleasure", + "powerful", + "random", + "rhythm", + "settle", + "silly", + "slap", + "sort", + "spoken", + "steel", + "threaten", + "tumble", + "upset", + "aside", + "awkward", + "bee", + "blank", + "board", + "button", + "card", + "carefully", + "complain", + "crap", + "deeply", + "discover", + "drag", + "dread", + "effort", + "entire", + "fairy", + "giant", + "gotten", + "greet", + "illusion", + "jeans", + "leap", + "liquid", + "march", + "mend", + "nervous", + "nine", + "replace", + "rope", + "spine", + "stole", + "terror", + "accident", + "apple", + "balance", + "boom", + "childhood", + "collect", + "demand", + "depression", + "eventually", + "faint", + "glare", + "goal", + "group", + "honey", + "kitchen", + "laid", + "limb", + "machine", + "mere", + "mold", + "murder", + "nerve", + "painful", + "poetry", + "prince", + "rabbit", + "shelter", + "shore", + "shower", + "soothe", + "stair", + "steady", + "sunlight", + "tangle", + "tease", + "treasure", + "uncle", + "begun", + "bliss", + "canvas", + "cheer", + "claw", + "clutch", + "commit", + "crimson", + "crystal", + "delight", + "doll", + "existence", + "express", + "fog", + "football", + "gay", + "goose", + "guard", + "hatred", + "illuminate", + "mass", + "math", + "mourn", + "rich", + "rough", + "skip", + "stir", + "student", + "style", + "support", + "thorn", + "tough", + "yard", + "yearn", + "yesterday", + "advice", + "appreciate", + "autumn", + "bank", + "beam", + "bowl", + "capture", + "carve", + "collapse", + "confusion", + "creation", + "dove", + "feather", + "girlfriend", + "glory", + "government", + "harsh", + "hop", + "inner", + "loser", + "moonlight", + "neighbor", + "neither", + "peach", + "pig", + "praise", + "screw", + "shield", + "shimmer", + "sneak", + "stab", + "subject", + "throughout", + "thrown", + "tower", + "twirl", + "wow", + "army", + "arrive", + "bathroom", + "bump", + "cease", + "cookie", + "couch", + "courage", + "dim", + "guilt", + "howl", + "hum", + "husband", + "insult", + "led", + "lunch", + "mock", + "mostly", + "natural", + "nearly", + "needle", + "nerd", + "peaceful", + "perfection", + "pile", + "price", + "remove", + "roam", + "sanctuary", + "serious", + "shiny", + "shook", + "sob", + "stolen", + "tap", + "vain", + "void", + "warrior", + "wrinkle", + "affection", + "apologize", + "blossom", + "bounce", + "bridge", + "cheap", + "crumble", + "decision", + "descend", + "desperately", + "dig", + "dot", + "flip", + "frighten", + "heartbeat", + "huge", + "lazy", + "lick", + "odd", + "opinion", + "process", + "puzzle", + "quietly", + "retreat", + "score", + "sentence", + "separate", + "situation", + "skill", + "soak", + "square", + "stray", + "taint", + "task", + "tide", + "underneath", + "veil", + "whistle", + "anywhere", + "bedroom", + "bid", + "bloody", + "burden", + "careful", + "compare", + "concern", + "curtain", + "decay", + "defeat", + "describe", + "double", + "dreamer", + "driver", + "dwell", + "evening", + "flare", + "flicker", + "grandma", + "guitar", + "harm", + "horrible", + "hungry", + "indeed", + "lace", + "melody", + "monkey", + "nation", + "object", + "obviously", + "rainbow", + "salt", + "scratch", + "shown", + "shy", + "stage", + "stun", + "third", + "tickle", + "useless", + "weakness", + "worship", + "worthless", + "afternoon", + "beard", + "boyfriend", + "bubble", + "busy", + "certain", + "chin", + "concrete", + "desk", + "diamond", + "doom", + "drawn", + "due", + "felicity", + "freeze", + "frost", + "garden", + "glide", + "harmony", + "hopefully", + "hunt", + "jealous", + "lightning", + "mama", + "mercy", + "peel", + "physical", + "position", + "pulse", + "punch", + "quit", + "rant", + "respond", + "salty", + "sane", + "satisfy", + "savior", + "sheep", + "slept", + "social", + "sport", + "tuck", + "utter", + "valley", + "wolf", + "aim", + "alas", + "alter", + "arrow", + "awaken", + "beaten", + "belief", + "brand", + "ceiling", + "cheese", + "clue", + "confidence", + "connection", + "daily", + "disguise", + "eager", + "erase", + "essence", + "everytime", + "expression", + "fan", + "flag", + "flirt", + "foul", + "fur", + "giggle", + "glorious", + "ignorance", + "law", + "lifeless", + "measure", + "mighty", + "muse", + "north", + "opposite", + "paradise", + "patience", + "patient", + "pencil", + "petal", + "plate", + "ponder", + "possibly", + "practice", + "slice", + "spell", + "stock", + "strife", + "strip", + "suffocate", + "suit", + "tender", + "tool", + "trade", + "velvet", + "verse", + "waist", + "witch", + "aunt", + "bench", + "bold", + "cap", + "certainly", + "click", + "companion", + "creator", + "dart", + "delicate", + "determine", + "dish", + "dragon", + "drama", + "drum", + "dude", + "everybody", + "feast", + "forehead", + "former", + "fright", + "fully", + "gas", + "hook", + "hurl", + "invite", + "juice", + "manage", + "moral", + "possess", + "raw", + "rebel", + "royal", + "scale", + "scary", + "several", + "slight", + "stubborn", + "swell", + "talent", + "tea", + "terrible", + "thread", + "torment", + "trickle", + "usually", + "vast", + "violence", + "weave", + "acid", + "agony", + "ashamed", + "awe", + "belly", + "blend", + "blush", + "character", + "cheat", + "common", + "company", + "coward", + "creak", + "danger", + "deadly", + "defense", + "define", + "depend", + "desperate", + "destination", + "dew", + "duck", + "dusty", + "embarrass", + "engine", + "example", + "explore", + "foe", + "freely", + "frustrate", + "generation", + "glove", + "guilty", + "health", + "hurry", + "idiot", + "impossible", + "inhale", + "jaw", + "kingdom", + "mention", + "mist", + "moan", + "mumble", + "mutter", + "observe", + "ode", + "pathetic", + "pattern", + "pie", + "prefer", + "puff", + "rape", + "rare", + "revenge", + "rude", + "scrape", + "spiral", + "squeeze", + "strain", + "sunset", + "suspend", + "sympathy", + "thigh", + "throne", + "total", + "unseen", + "weapon", + "weary", +} -- cgit v1.2.3 From 627b7c9fd75c84e0ca3af110b8f64ab5bbda963e Mon Sep 17 00:00:00 2001 From: obscuren Date: Sun, 7 Sep 2014 10:07:51 +0200 Subject: Updated to latest sha3 implementation. Fixes #48 --- ethcrypto/crypto.go | 5 +++-- ethcrypto/crypto_test.go | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 ethcrypto/crypto_test.go (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index 19f8c9e55..f5f0f7e68 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -1,9 +1,10 @@ package ethcrypto import ( + "crypto/sha256" + "code.google.com/p/go.crypto/ripemd160" "code.google.com/p/go.crypto/sha3" - "crypto/sha256" "github.com/ethereum/eth-go/ethutil" ) @@ -21,7 +22,7 @@ func Ripemd160(data []byte) []byte { } func Sha3Bin(data []byte) []byte { - d := sha3.NewKeccak256() + d := sha3.New256() d.Write(data) return d.Sum(nil) diff --git a/ethcrypto/crypto_test.go b/ethcrypto/crypto_test.go new file mode 100644 index 000000000..8418c9a5a --- /dev/null +++ b/ethcrypto/crypto_test.go @@ -0,0 +1,16 @@ +package ethcrypto + +import ( + "bytes" + "testing" + + "github.com/ethereum/eth-go/ethutil" +) + +func TestSha3(t *testing.T) { + const exp = "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532" + sha3_256 := Sha3Bin([]byte("abc")) + if bytes.Compare(sha3_256, ethutil.Hex2Bytes(exp)) != 0 { + t.Errorf("Sha3_256 failed. Incorrect result %x", sha3_256) + } +} -- cgit v1.2.3 From adabd71a4ad808faf13f0253ad248bc746308db5 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sun, 7 Sep 2014 22:34:24 +0200 Subject: Changed back to FIPS 180 --- ethcrypto/crypto.go | 21 +++------------------ ethcrypto/crypto_test.go | 1 + 2 files changed, 4 insertions(+), 18 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index f5f0f7e68..1f500f2db 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -1,28 +1,13 @@ package ethcrypto import ( - "crypto/sha256" - - "code.google.com/p/go.crypto/ripemd160" - "code.google.com/p/go.crypto/sha3" + //"code.google.com/p/go.crypto/sha3" "github.com/ethereum/eth-go/ethutil" + "github.com/obscuren/sha3" ) -func Sha256Bin(data []byte) []byte { - hash := sha256.Sum256(data) - - return hash[:] -} - -func Ripemd160(data []byte) []byte { - ripemd := ripemd160.New() - ripemd.Write(data) - - return ripemd.Sum(nil) -} - func Sha3Bin(data []byte) []byte { - d := sha3.New256() + d := sha3.NewKeccak256() d.Write(data) return d.Sum(nil) diff --git a/ethcrypto/crypto_test.go b/ethcrypto/crypto_test.go index 8418c9a5a..7323e1646 100644 --- a/ethcrypto/crypto_test.go +++ b/ethcrypto/crypto_test.go @@ -7,6 +7,7 @@ import ( "github.com/ethereum/eth-go/ethutil" ) +// FIPS 202 test (reverted back to FIPS 180) func TestSha3(t *testing.T) { const exp = "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532" sha3_256 := Sha3Bin([]byte("abc")) -- cgit v1.2.3 From 11ace543072726e76743f157a31956ad1b941956 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 8 Oct 2014 12:00:50 +0200 Subject: ECRECOVER RIPEMD160 SHA256 --- ethcrypto/crypto.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index 1f500f2db..624c5169f 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -2,10 +2,16 @@ package ethcrypto import ( //"code.google.com/p/go.crypto/sha3" + "crypto/sha256" + + "code.google.com/p/go.crypto/ripemd160" "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/sha3" + + "github.com/obscuren/secp256k1-go" ) +// TODO refactor, remove (bin) func Sha3Bin(data []byte) []byte { d := sha3.NewKeccak256() d.Write(data) @@ -17,3 +23,27 @@ func Sha3Bin(data []byte) []byte { func CreateAddress(b []byte, nonce uint64) []byte { return Sha3Bin(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:] } + +func Sha256(data []byte) []byte { + hash := sha256.Sum256(data) + + return hash[:] +} + +func Ripemd160(data []byte) []byte { + ripemd := ripemd160.New() + ripemd.Write(data) + + return ripemd.Sum(nil) +} + +func Ecrecover(data []byte) []byte { + var in = struct { + hash []byte + sig []byte + }{data[:32], data[32:]} + + r, _ := secp256k1.RecoverPubkey(in.hash, in.sig) + + return r +} -- cgit v1.2.3 From 9d86a49a7327199c01977f3372c8adf748252c32 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 8 Oct 2014 12:06:39 +0200 Subject: Renamed Sha3Bin to Sha3 --- ethcrypto/crypto.go | 5 ++--- ethcrypto/keypair.go | 5 +++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'ethcrypto') diff --git a/ethcrypto/crypto.go b/ethcrypto/crypto.go index 624c5169f..ebc8b171b 100644 --- a/ethcrypto/crypto.go +++ b/ethcrypto/crypto.go @@ -1,7 +1,6 @@ package ethcrypto import ( - //"code.google.com/p/go.crypto/sha3" "crypto/sha256" "code.google.com/p/go.crypto/ripemd160" @@ -12,7 +11,7 @@ import ( ) // TODO refactor, remove (bin) -func Sha3Bin(data []byte) []byte { +func Sha3(data []byte) []byte { d := sha3.NewKeccak256() d.Write(data) @@ -21,7 +20,7 @@ func Sha3Bin(data []byte) []byte { // Creates an ethereum address given the bytes and the nonce func CreateAddress(b []byte, nonce uint64) []byte { - return Sha3Bin(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:] + return Sha3(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:] } func Sha256(data []byte) []byte { diff --git a/ethcrypto/keypair.go b/ethcrypto/keypair.go index 18fa5b788..ebb982306 100644 --- a/ethcrypto/keypair.go +++ b/ethcrypto/keypair.go @@ -1,9 +1,10 @@ package ethcrypto import ( + "strings" + "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/secp256k1-go" - "strings" ) type KeyPair struct { @@ -32,7 +33,7 @@ func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) { func (k *KeyPair) Address() []byte { if k.address == nil { - k.address = Sha3Bin(k.PublicKey[1:])[12:] + k.address = Sha3(k.PublicKey[1:])[12:] } return k.address } -- cgit v1.2.3