script.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Copyright (c) 2016 Pavol Rusnak
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included
  12. * in all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
  18. * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  19. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  20. * OTHER DEALINGS IN THE SOFTWARE.
  21. */
  22. #include "script.h"
  23. #include <string.h>
  24. #include "base58.h"
  25. int script_output_to_address(const uint8_t *script, int scriptlen, char *addr,
  26. int addrsize) {
  27. uint8_t raw[35] = {0};
  28. // P2PKH
  29. if (scriptlen == 25 && script[0] == 0x76 && script[1] == 0xA9 &&
  30. script[2] == 0x14 && script[23] == 0x88 && script[24] == 0xAC) {
  31. raw[0] = 0x00;
  32. memcpy(raw + 1, script + 3, 20);
  33. return base58_encode_check(raw, 1 + 20, HASHER_SHA2D, addr, addrsize);
  34. }
  35. // P2SH
  36. if (scriptlen == 23 && script[0] == 0xA9 && script[1] == 0x14 &&
  37. script[22] == 0x87) {
  38. raw[0] = 0x05;
  39. memcpy(raw + 1, script + 2, 20);
  40. return base58_encode_check(raw, 1 + 20, HASHER_SHA2D, addr, addrsize);
  41. }
  42. // P2WPKH
  43. if (scriptlen == 22 && script[0] == 0x00 && script[1] == 0x14) {
  44. raw[0] = 0x06;
  45. raw[1] = 0x00;
  46. raw[2] = 0x00;
  47. memcpy(raw + 3, script + 2, 20);
  48. return base58_encode_check(raw, 3 + 20, HASHER_SHA2D, addr, addrsize);
  49. }
  50. // P2WSH
  51. if (scriptlen == 34 && script[0] == 0x00 && script[1] == 0x20) {
  52. raw[0] = 0x0A;
  53. raw[1] = 0x00;
  54. raw[2] = 0x00;
  55. memcpy(raw + 3, script + 2, 32);
  56. return base58_encode_check(raw, 3 + 32, HASHER_SHA2D, addr, addrsize);
  57. }
  58. return 0;
  59. }