script.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, int addrsize) {
  26. uint8_t raw[35] = {0};
  27. // P2PKH
  28. if(scriptlen == 25 && script[0] == 0x76 && script[1] == 0xA9 && script[2] == 0x14 &&
  29. script[23] == 0x88 && script[24] == 0xAC) {
  30. raw[0] = 0x00;
  31. memcpy(raw + 1, script + 3, 20);
  32. return base58_encode_check(raw, 1 + 20, HASHER_SHA2D, addr, addrsize);
  33. }
  34. // P2SH
  35. if(scriptlen == 23 && script[0] == 0xA9 && script[1] == 0x14 && script[22] == 0x87) {
  36. raw[0] = 0x05;
  37. memcpy(raw + 1, script + 2, 20);
  38. return base58_encode_check(raw, 1 + 20, HASHER_SHA2D, addr, addrsize);
  39. }
  40. // P2WPKH
  41. if(scriptlen == 22 && script[0] == 0x00 && script[1] == 0x14) {
  42. raw[0] = 0x06;
  43. raw[1] = 0x00;
  44. raw[2] = 0x00;
  45. memcpy(raw + 3, script + 2, 20);
  46. return base58_encode_check(raw, 3 + 20, HASHER_SHA2D, addr, addrsize);
  47. }
  48. // P2WSH
  49. if(scriptlen == 34 && script[0] == 0x00 && script[1] == 0x20) {
  50. raw[0] = 0x0A;
  51. raw[1] = 0x00;
  52. raw[2] = 0x00;
  53. memcpy(raw + 3, script + 2, 32);
  54. return base58_encode_check(raw, 3 + 32, HASHER_SHA2D, addr, addrsize);
  55. }
  56. return 0;
  57. }