decred.org/dcrwallet/v3@v3.1.0/pgpwordlist/pgpwordlist.go (about)

     1  /*
     2   * Copyright (c) 2015-2016 The Decred developers
     3   *
     4   * Permission to use, copy, modify, and distribute this software for any
     5   * purpose with or without fee is hereby granted, provided that the above
     6   * copyright notice and this permission notice appear in all copies.
     7   *
     8   * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     9   * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    10   * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    11   * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    12   * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    13   * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    14   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    15   */
    16  
    17  package pgpwordlist
    18  
    19  import (
    20  	"strings"
    21  
    22  	"decred.org/dcrwallet/v3/errors"
    23  )
    24  
    25  // ByteToMnemonic returns the PGP word list encoding of b when found at index.
    26  func ByteToMnemonic(b byte, index int) string {
    27  	bb := uint16(b) * 2
    28  	if index%2 != 0 {
    29  		bb++
    30  	}
    31  	return wordList[bb]
    32  }
    33  
    34  // DecodeMnemonics returns the decoded value that is encoded by words.  Any
    35  // words that are whitespace are empty are skipped.
    36  func DecodeMnemonics(words []string) ([]byte, error) {
    37  	const op errors.Op = "pgpwordlist.DecodeMnemonics"
    38  
    39  	decoded := make([]byte, len(words))
    40  	idx := 0
    41  	for _, w := range words {
    42  		w = strings.TrimSpace(w)
    43  		if w == "" {
    44  			continue
    45  		}
    46  		b, ok := wordIndexes[strings.ToLower(w)]
    47  		if !ok {
    48  			err := errors.Errorf("word %v is not in the PGP word list", w)
    49  			return nil, errors.E(op, errors.Encoding, err)
    50  		}
    51  		if int(b%2) != idx%2 {
    52  			err := errors.Errorf("word %v is not valid at position %v, "+
    53  				"check for missing words", w, idx)
    54  			return nil, errors.E(op, errors.Encoding, err)
    55  		}
    56  		decoded[idx] = byte(b / 2)
    57  		idx++
    58  	}
    59  	return decoded[:idx], nil
    60  }