Guest User

Untitled

a guest
Mar 22nd, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import blocks from '__mocks__/blocks';
  2. import { ec } from 'elliptic';
  3. import { getAddress } from 'utils/makeWallet';
  4. import ripemd160 from 'ripemd160';
  5. import sha256 from 'js-sha256';
  6.  
  7. const ecdsa = new ec('secp256k1');
  8. const COIN = 100000000;
  9. const MY_ADDRESS = '1Nd85AnFYDtaQAG6vF9FVWXFWksG5HuA3M';
  10. const FRIEND_ADDRESS = '1PDLNfJq5GAEn5StESZuBpaBe6B3134vmD';
  11.  
  12. // hash the txid with SHA-256 and RIPEMD-160 algorithms
  13. export function Hash(msg) {
  14. return new ripemd160().update(sha256(msg)).digest('hex');
  15. }
  16.  
  17. // sign a transaction input with private key
  18. export function unlockTransaction(txid, privateKey) {
  19. try {
  20. // hash transaction ID
  21. const hash = Hash(txid);
  22. // initialize signing keys
  23. const keys = ecdsa.keyFromPrivate(privateKey);
  24. // sign txid hash with signing keys
  25. const signature = ecdsa.sign(hash, keys);
  26. // return in hexadecimal format
  27. return signature.toDER('hex');
  28. } catch (e) {
  29. return null;
  30. }
  31. }
  32.  
  33. // verify that signature is owner of address and matches transaction
  34. export function verifyUnlock(txid, address, publicKey, signature) {
  35. try {
  36. // first validate that address is derived from public key
  37. const isAddress = getAddress(publicKey) === address;
  38. if (!isAddress) {
  39. return false;
  40. }
  41. const hash = Hash(txid);
  42. const keys = ecdsa.keyFromPublic(publicKey, 'hex');
  43. const isValid = keys.verify(hash, signature);
  44. return isValid;
  45. } catch (e) {
  46. return false;
  47. }
  48. }
  49.  
  50. export function testVerification(vin) {
  51. const { txid, prevout, scriptSig } = vin;
  52. const [ publicKey, signature ] = scriptSig.split(' ');
  53. return verifyUnlock(txid, prevout.scriptPubKey, publicKey, signature);
  54. }
Add Comment
Please, Sign In to add comment