text
stringlengths
1
1.05M
// (C) Copyright Christopher Jefferson 2011. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. // config for libc++ // Might need more in here later. #if !defined(_LIBCPP_VERSION) # include <ciso646> # if !defined(_LIBCPP_VERSION) # error "This is not libc++!" # endif #endif #define BOOST_STDLIB "libc++ version " BOOST_STRINGIZE(_LIBCPP_VERSION) #define BOOST_HAS_THREADS #ifdef _LIBCPP_HAS_NO_VARIADICS # define BOOST_NO_CXX11_HDR_TUPLE #endif // BOOST_NO_CXX11_ALLOCATOR should imply no support for the C++11 // allocator model. The C++11 allocator model requires a conforming // std::allocator_traits which is only possible with C++11 template // aliases since members rebind_alloc and rebind_traits require it. #if defined(_LIBCPP_HAS_NO_TEMPLATE_ALIASES) # define BOOST_NO_CXX11_ALLOCATOR # define BOOST_NO_CXX11_POINTER_TRAITS #endif #if __cplusplus < 201103 // // These two appear to be somewhat useable in C++03 mode, there may be others... // //# define BOOST_NO_CXX11_HDR_ARRAY //# define BOOST_NO_CXX11_HDR_FORWARD_LIST # define BOOST_NO_CXX11_HDR_CODECVT # define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE # define BOOST_NO_CXX11_HDR_INITIALIZER_LIST # define BOOST_NO_CXX11_HDR_MUTEX # define BOOST_NO_CXX11_HDR_RANDOM # define BOOST_NO_CXX11_HDR_RATIO # define BOOST_NO_CXX11_HDR_REGEX # define BOOST_NO_CXX11_HDR_SYSTEM_ERROR # define BOOST_NO_CXX11_HDR_THREAD # define BOOST_NO_CXX11_HDR_TUPLE # define BOOST_NO_CXX11_HDR_TYPEINDEX # define BOOST_NO_CXX11_HDR_UNORDERED_MAP # define BOOST_NO_CXX11_HDR_UNORDERED_SET # define BOOST_NO_CXX11_NUMERIC_LIMITS # define BOOST_NO_CXX11_ALLOCATOR # define BOOST_NO_CXX11_POINTER_TRAITS # define BOOST_NO_CXX11_SMART_PTR # define BOOST_NO_CXX11_HDR_FUNCTIONAL # define BOOST_NO_CXX11_STD_ALIGN # define BOOST_NO_CXX11_ADDRESSOF # define BOOST_NO_CXX11_HDR_ATOMIC # define BOOST_NO_CXX11_ATOMIC_SMART_PTR # define BOOST_NO_CXX11_HDR_CHRONO # define BOOST_NO_CXX11_HDR_TYPE_TRAITS # define BOOST_NO_CXX11_HDR_FUTURE #elif _LIBCPP_VERSION < 3700 // // These appear to be unusable/incomplete so far: // # define BOOST_NO_CXX11_HDR_ATOMIC # define BOOST_NO_CXX11_ATOMIC_SMART_PTR # define BOOST_NO_CXX11_HDR_CHRONO # define BOOST_NO_CXX11_HDR_TYPE_TRAITS # define BOOST_NO_CXX11_HDR_FUTURE #endif #if _LIBCPP_VERSION < 3700 // libc++ uses a non-standard messages_base #define BOOST_NO_STD_MESSAGES #endif // C++14 features #if (_LIBCPP_VERSION < 3700) || (__cplusplus <= 201402L) # define BOOST_NO_CXX14_STD_EXCHANGE #endif // C++17 features #if (_LIBCPP_VERSION < 4000) || (__cplusplus <= 201402L) # define BOOST_NO_CXX17_STD_APPLY # define BOOST_NO_CXX17_HDR_OPTIONAL # define BOOST_NO_CXX17_HDR_STRING_VIEW #endif #if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR) # define BOOST_NO_AUTO_PTR #endif #if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE) # define BOOST_NO_CXX98_RANDOM_SHUFFLE #endif #if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS) # define BOOST_NO_CXX98_BINDERS #endif #define BOOST_NO_CXX17_ITERATOR_TRAITS #define BOOST_NO_CXX17_STD_INVOKE // Invoke support is incomplete (no invoke_result) #if (_LIBCPP_VERSION <= 1101) && !defined(BOOST_NO_CXX11_THREAD_LOCAL) // This is a bit of a sledgehammer, because really it's just libc++abi that has no // support for thread_local, leading to linker errors such as // "undefined reference to `__cxa_thread_atexit'". It is fixed in the // most recent releases of libc++abi though... # define BOOST_NO_CXX11_THREAD_LOCAL #endif #if defined(__linux__) && (_LIBCPP_VERSION < 6000) && !defined(BOOST_NO_CXX11_THREAD_LOCAL) // After libc++-dev is installed on Trusty, clang++-libc++ almost works, // except uses of `thread_local` fail with undefined reference to // `__cxa_thread_atexit`. // // clang's libc++abi provides an implementation by deferring to the glibc // implementation, which may or may not be available (it is not on Trusty). // clang 4's libc++abi will provide an implementation if one is not in glibc // though, so thread local support should work with clang 4 and above as long // as libc++abi is linked in. # define BOOST_NO_CXX11_THREAD_LOCAL #endif #if defined(__has_include) #if !__has_include(<shared_mutex>) # define BOOST_NO_CXX14_HDR_SHARED_MUTEX #elif __cplusplus <= 201103 # define BOOST_NO_CXX14_HDR_SHARED_MUTEX #endif #elif __cplusplus < 201402 # define BOOST_NO_CXX14_HDR_SHARED_MUTEX #endif #if !defined(BOOST_NO_CXX14_HDR_SHARED_MUTEX) && (_LIBCPP_VERSION < 5000) # define BOOST_NO_CXX14_HDR_SHARED_MUTEX #endif // --- end ---
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.16.27027.1 TITLE C:\Users\DAG\Documents\_Clients\CodeProject Authors Group\Windows on ARM\libxml2\libxml2-2.9.9\xlink.c .686P .XMM include listing.inc .model flat INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES _DATA SEGMENT COMM _forbiddenExp:DWORD COMM _emptyExp:DWORD COMM _xmlMalloc:DWORD COMM _xmlMallocAtomic:DWORD COMM _xmlRealloc:DWORD COMM _xmlFree:DWORD COMM _xmlMemStrdup:DWORD _DATA ENDS msvcjmc SEGMENT __188180DA_corecrt_math@h DB 01H __2CC6E67D_corecrt_stdio_config@h DB 01H __05476D76_corecrt_wstdio@h DB 01H __A452D4A0_stdio@h DB 01H __4384A2D9_corecrt_memcpy_s@h DB 01H __4E51A221_corecrt_wstring@h DB 01H __2140C079_string@h DB 01H __7B7A869E_ctype@h DB 01H __A40A425D_stat@h DB 01H __457DD326_basetsd@h DB 01H __1887E595_winnt@h DB 01H __9FC7C64B_processthreadsapi@h DB 01H __FA470AEC_memoryapi@h DB 01H __F37DAFF1_winerror@h DB 01H __7A450CCC_winbase@h DB 01H __B4B40122_winioctl@h DB 01H __86261D59_stralign@h DB 01H __E43CAA02_xlink@c DB 01H msvcjmc ENDS PUBLIC ___local_stdio_printf_options PUBLIC _snprintf PUBLIC _xlinkGetDefaultDetect PUBLIC _xlinkSetDefaultDetect PUBLIC _xlinkGetDefaultHandler PUBLIC _xlinkSetDefaultHandler PUBLIC _xlinkIsLink PUBLIC __JustMyCode_Default PUBLIC ??_C@_0BO@DIGPEIDG@http?3?1?1www?4w3?4org?11999?1xhtml?1@ ; `string' PUBLIC ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ ; `string' PUBLIC ??_C@_04GPMDFGEJ@type@ ; `string' PUBLIC ??_C@_06MDDCAKGD@simple@ ; `string' PUBLIC ??_C@_08ONGCMBFO@extended@ ; `string' PUBLIC ??_C@_04IAMNPBLO@role@ ; `string' PUBLIC ??_C@_0BH@MHEJCPPK@xlink?3external?9linkset@ ; `string' PUBLIC ??_C@_0BE@NPIDLLNF@?$CFs?3external?9linkset@ ; `string' EXTRN _xmlStrEqual:PROC EXTRN __imp____stdio_common_vsprintf:PROC EXTRN _xmlSearchNs:PROC EXTRN _xmlGetNsProp:PROC EXTRN @_RTC_CheckStackVars@8:PROC EXTRN @__CheckForDebuggerJustMyCode@4:PROC EXTRN __RTC_CheckEsp:PROC EXTRN __RTC_InitBase:PROC EXTRN __RTC_Shutdown:PROC _DATA SEGMENT COMM ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9:QWORD ; `__local_stdio_printf_options'::`2'::_OptionsStorage _DATA ENDS _BSS SEGMENT _xlinkDefaultHandler DD 01H DUP (?) _xlinkDefaultDetect DD 01H DUP (?) _BSS ENDS ; COMDAT rtc$TMZ rtc$TMZ SEGMENT __RTC_Shutdown.rtc$TMZ DD FLAT:__RTC_Shutdown rtc$TMZ ENDS ; COMDAT rtc$IMZ rtc$IMZ SEGMENT __RTC_InitBase.rtc$IMZ DD FLAT:__RTC_InitBase rtc$IMZ ENDS ; COMDAT ??_C@_0BE@NPIDLLNF@?$CFs?3external?9linkset@ CONST SEGMENT ??_C@_0BE@NPIDLLNF@?$CFs?3external?9linkset@ DB '%s:external-linkset', 00H ; `string' CONST ENDS ; COMDAT ??_C@_0BH@MHEJCPPK@xlink?3external?9linkset@ CONST SEGMENT ??_C@_0BH@MHEJCPPK@xlink?3external?9linkset@ DB 'xlink:external-linkset', 00H ; `string' CONST ENDS ; COMDAT ??_C@_04IAMNPBLO@role@ CONST SEGMENT ??_C@_04IAMNPBLO@role@ DB 'role', 00H ; `string' CONST ENDS ; COMDAT ??_C@_08ONGCMBFO@extended@ CONST SEGMENT ??_C@_08ONGCMBFO@extended@ DB 'extended', 00H ; `string' CONST ENDS ; COMDAT ??_C@_06MDDCAKGD@simple@ CONST SEGMENT ??_C@_06MDDCAKGD@simple@ DB 'simple', 00H ; `string' CONST ENDS ; COMDAT ??_C@_04GPMDFGEJ@type@ CONST SEGMENT ??_C@_04GPMDFGEJ@type@ DB 'type', 00H ; `string' CONST ENDS ; COMDAT ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ CONST SEGMENT ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ DB 'http://ww' DB 'w.w3.org/1999/xlink/namespace/', 00H ; `string' CONST ENDS ; COMDAT ??_C@_0BO@DIGPEIDG@http?3?1?1www?4w3?4org?11999?1xhtml?1@ CONST SEGMENT ??_C@_0BO@DIGPEIDG@http?3?1?1www?4w3?4org?11999?1xhtml?1@ DB 'http://www.' DB 'w3.org/1999/xhtml/', 00H ; `string' CONST ENDS ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT push ebp mov ebp, esp pop ebp ret 0 __JustMyCode_Default ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\users\dag\documents\_clients\codeproject authors group\windows on arm\libxml2\libxml2-2.9.9\xlink.c ; COMDAT _xlinkIsLink _TEXT SEGMENT _buf$1 = -220 ; size = 200 _xlink$2 = -16 ; size = 4 _ret$ = -12 ; size = 4 _role$ = -8 ; size = 4 _type$ = -4 ; size = 4 _doc$ = 8 ; size = 4 _node$ = 12 ; size = 4 _xlinkIsLink PROC ; COMDAT ; 123 : xlinkIsLink (xmlDocPtr doc, xmlNodePtr node) { push ebp mov ebp, esp sub esp, 224 ; 000000e0H push esi push edi lea edi, DWORD PTR [ebp-224] mov ecx, 56 ; 00000038H mov eax, -858993460 ; ccccccccH rep stosd mov ecx, OFFSET __E43CAA02_xlink@c call @__CheckForDebuggerJustMyCode@4 ; 124 : xmlChar *type = NULL, *role = NULL; mov DWORD PTR _type$[ebp], 0 mov DWORD PTR _role$[ebp], 0 ; 125 : xlinkType ret = XLINK_TYPE_NONE; mov DWORD PTR _ret$[ebp], 0 ; 126 : ; 127 : if (node == NULL) return(XLINK_TYPE_NONE); cmp DWORD PTR _node$[ebp], 0 jne SHORT $LN2@xlinkIsLin xor eax, eax jmp $LN1@xlinkIsLin $LN2@xlinkIsLin: ; 128 : if (doc == NULL) doc = node->doc; cmp DWORD PTR _doc$[ebp], 0 jne SHORT $LN3@xlinkIsLin mov eax, DWORD PTR _node$[ebp] mov ecx, DWORD PTR [eax+32] mov DWORD PTR _doc$[ebp], ecx $LN3@xlinkIsLin: ; 129 : if ((doc != NULL) && (doc->type == XML_HTML_DOCUMENT_NODE)) { cmp DWORD PTR _doc$[ebp], 0 je SHORT $LN4@xlinkIsLin mov edx, DWORD PTR _doc$[ebp] cmp DWORD PTR [edx+4], 13 ; 0000000dH jne SHORT $LN4@xlinkIsLin jmp SHORT $LN5@xlinkIsLin $LN4@xlinkIsLin: ; 130 : /* ; 131 : * This is an HTML document. ; 132 : */ ; 133 : } else if ((node->ns != NULL) && mov eax, DWORD PTR _node$[ebp] cmp DWORD PTR [eax+36], 0 je SHORT $LN5@xlinkIsLin push OFFSET ??_C@_0BO@DIGPEIDG@http?3?1?1www?4w3?4org?11999?1xhtml?1@ mov ecx, DWORD PTR _node$[ebp] mov edx, DWORD PTR [ecx+36] mov eax, DWORD PTR [edx+8] push eax call _xmlStrEqual add esp, 8 $LN5@xlinkIsLin: ; 134 : (xmlStrEqual(node->ns->href, XHTML_NAMESPACE))) { ; 135 : /* ; 136 : * !!!! We really need an IS_XHTML_ELEMENT function from HTMLtree.h @@@ ; 137 : */ ; 138 : /* ; 139 : * This is an XHTML element within an XML document ; 140 : * Check whether it's one of the element able to carry links ; 141 : * and in that case if it holds the attributes. ; 142 : */ ; 143 : } ; 144 : ; 145 : /* ; 146 : * We don't prevent a-priori having XML Linking constructs on ; 147 : * XHTML elements ; 148 : */ ; 149 : type = xmlGetNsProp(node, BAD_CAST"type", XLINK_NAMESPACE); push OFFSET ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ push OFFSET ??_C@_04GPMDFGEJ@type@ mov ecx, DWORD PTR _node$[ebp] push ecx call _xmlGetNsProp add esp, 12 ; 0000000cH mov DWORD PTR _type$[ebp], eax ; 150 : if (type != NULL) { cmp DWORD PTR _type$[ebp], 0 je $LN7@xlinkIsLin ; 151 : if (xmlStrEqual(type, BAD_CAST "simple")) { push OFFSET ??_C@_06MDDCAKGD@simple@ mov edx, DWORD PTR _type$[ebp] push edx call _xmlStrEqual add esp, 8 test eax, eax je SHORT $LN8@xlinkIsLin ; 152 : ret = XLINK_TYPE_SIMPLE; mov DWORD PTR _ret$[ebp], 1 jmp $LN7@xlinkIsLin $LN8@xlinkIsLin: ; 153 : } else if (xmlStrEqual(type, BAD_CAST "extended")) { push OFFSET ??_C@_08ONGCMBFO@extended@ mov eax, DWORD PTR _type$[ebp] push eax call _xmlStrEqual add esp, 8 test eax, eax je $LN7@xlinkIsLin ; 154 : role = xmlGetNsProp(node, BAD_CAST "role", XLINK_NAMESPACE); push OFFSET ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ push OFFSET ??_C@_04IAMNPBLO@role@ mov ecx, DWORD PTR _node$[ebp] push ecx call _xmlGetNsProp add esp, 12 ; 0000000cH mov DWORD PTR _role$[ebp], eax ; 155 : if (role != NULL) { cmp DWORD PTR _role$[ebp], 0 je $LN11@xlinkIsLin ; 156 : xmlNsPtr xlink; ; 157 : xlink = xmlSearchNs(doc, node, XLINK_NAMESPACE); push OFFSET ??_C@_0CI@PBGMGCJI@http?3?1?1www?4w3?4org?11999?1xlink?1na@ mov edx, DWORD PTR _node$[ebp] push edx mov eax, DWORD PTR _doc$[ebp] push eax call _xmlSearchNs add esp, 12 ; 0000000cH mov DWORD PTR _xlink$2[ebp], eax ; 158 : if (xlink == NULL) { cmp DWORD PTR _xlink$2[ebp], 0 jne SHORT $LN12@xlinkIsLin ; 159 : /* Humm, fallback method */ ; 160 : if (xmlStrEqual(role, BAD_CAST"xlink:external-linkset")) push OFFSET ??_C@_0BH@MHEJCPPK@xlink?3external?9linkset@ mov ecx, DWORD PTR _role$[ebp] push ecx call _xmlStrEqual add esp, 8 test eax, eax je SHORT $LN14@xlinkIsLin ; 161 : ret = XLINK_TYPE_EXTENDED_SET; mov DWORD PTR _ret$[ebp], 3 $LN14@xlinkIsLin: ; 162 : } else { jmp SHORT $LN11@xlinkIsLin $LN12@xlinkIsLin: ; 163 : xmlChar buf[200]; ; 164 : snprintf((char *) buf, sizeof(buf), "%s:external-linkset", mov edx, DWORD PTR _xlink$2[ebp] mov eax, DWORD PTR [edx+12] push eax push OFFSET ??_C@_0BE@NPIDLLNF@?$CFs?3external?9linkset@ push 200 ; 000000c8H lea ecx, DWORD PTR _buf$1[ebp] push ecx call _snprintf add esp, 16 ; 00000010H ; 165 : (char *) xlink->prefix); ; 166 : buf[sizeof(buf) - 1] = 0; mov edx, 1 imul eax, edx, 199 mov BYTE PTR _buf$1[ebp+eax], 0 ; 167 : if (xmlStrEqual(role, buf)) lea ecx, DWORD PTR _buf$1[ebp] push ecx mov edx, DWORD PTR _role$[ebp] push edx call _xmlStrEqual add esp, 8 test eax, eax je SHORT $LN11@xlinkIsLin ; 168 : ret = XLINK_TYPE_EXTENDED_SET; mov DWORD PTR _ret$[ebp], 3 $LN11@xlinkIsLin: ; 169 : ; 170 : } ; 171 : ; 172 : } ; 173 : ret = XLINK_TYPE_EXTENDED; mov DWORD PTR _ret$[ebp], 2 $LN7@xlinkIsLin: ; 174 : } ; 175 : } ; 176 : ; 177 : if (type != NULL) xmlFree(type); cmp DWORD PTR _type$[ebp], 0 je SHORT $LN16@xlinkIsLin mov esi, esp mov eax, DWORD PTR _type$[ebp] push eax call DWORD PTR _xmlFree add esp, 4 cmp esi, esp call __RTC_CheckEsp $LN16@xlinkIsLin: ; 178 : if (role != NULL) xmlFree(role); cmp DWORD PTR _role$[ebp], 0 je SHORT $LN17@xlinkIsLin mov esi, esp mov ecx, DWORD PTR _role$[ebp] push ecx call DWORD PTR _xmlFree add esp, 4 cmp esi, esp call __RTC_CheckEsp $LN17@xlinkIsLin: ; 179 : return(ret); mov eax, DWORD PTR _ret$[ebp] $LN1@xlinkIsLin: ; 180 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN21@xlinkIsLin call @_RTC_CheckStackVars@8 pop eax pop edx pop edi pop esi add esp, 224 ; 000000e0H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 $LN21@xlinkIsLin: DD 1 DD $LN20@xlinkIsLin $LN20@xlinkIsLin: DD -220 ; ffffff24H DD 200 ; 000000c8H DD $LN19@xlinkIsLin $LN19@xlinkIsLin: DB 98 ; 00000062H DB 117 ; 00000075H DB 102 ; 00000066H DB 0 _xlinkIsLink ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\users\dag\documents\_clients\codeproject authors group\windows on arm\libxml2\libxml2-2.9.9\xlink.c ; COMDAT _xlinkSetDefaultHandler _TEXT SEGMENT _handler$ = 8 ; size = 4 _xlinkSetDefaultHandler PROC ; COMDAT ; 74 : xlinkSetDefaultHandler(xlinkHandlerPtr handler) { push ebp mov ebp, esp mov ecx, OFFSET __E43CAA02_xlink@c call @__CheckForDebuggerJustMyCode@4 ; 75 : xlinkDefaultHandler = handler; mov eax, DWORD PTR _handler$[ebp] mov DWORD PTR _xlinkDefaultHandler, eax ; 76 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _xlinkSetDefaultHandler ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\users\dag\documents\_clients\codeproject authors group\windows on arm\libxml2\libxml2-2.9.9\xlink.c ; COMDAT _xlinkGetDefaultHandler _TEXT SEGMENT _xlinkGetDefaultHandler PROC ; COMDAT ; 62 : xlinkGetDefaultHandler(void) { push ebp mov ebp, esp mov ecx, OFFSET __E43CAA02_xlink@c call @__CheckForDebuggerJustMyCode@4 ; 63 : return(xlinkDefaultHandler); mov eax, DWORD PTR _xlinkDefaultHandler ; 64 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _xlinkGetDefaultHandler ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\users\dag\documents\_clients\codeproject authors group\windows on arm\libxml2\libxml2-2.9.9\xlink.c ; COMDAT _xlinkSetDefaultDetect _TEXT SEGMENT _func$ = 8 ; size = 4 _xlinkSetDefaultDetect PROC ; COMDAT ; 97 : xlinkSetDefaultDetect (xlinkNodeDetectFunc func) { push ebp mov ebp, esp mov ecx, OFFSET __E43CAA02_xlink@c call @__CheckForDebuggerJustMyCode@4 ; 98 : xlinkDefaultDetect = func; mov eax, DWORD PTR _func$[ebp] mov DWORD PTR _xlinkDefaultDetect, eax ; 99 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _xlinkSetDefaultDetect ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\users\dag\documents\_clients\codeproject authors group\windows on arm\libxml2\libxml2-2.9.9\xlink.c ; COMDAT _xlinkGetDefaultDetect _TEXT SEGMENT _xlinkGetDefaultDetect PROC ; COMDAT ; 86 : xlinkGetDefaultDetect (void) { push ebp mov ebp, esp mov ecx, OFFSET __E43CAA02_xlink@c call @__CheckForDebuggerJustMyCode@4 ; 87 : return(xlinkDefaultDetect); mov eax, DWORD PTR _xlinkDefaultDetect ; 88 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _xlinkGetDefaultDetect ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\program files (x86)\windows kits\10\include\10.0.17763.0\ucrt\stdio.h ; COMDAT _snprintf _TEXT SEGMENT tv81 = -20 ; size = 4 __Result$1 = -16 ; size = 4 __Format$ = -12 ; size = 4 __ArgList$ = -8 ; size = 4 __Result$ = -4 ; size = 4 __Buffer$ = 8 ; size = 4 __BufferCount$ = 12 ; size = 4 __Format$ = 16 ; size = 4 _snprintf PROC ; COMDAT ; 1948 : { push ebp mov ebp, esp sub esp, 20 ; 00000014H push esi mov eax, -858993460 ; ccccccccH mov DWORD PTR [ebp-20], eax mov DWORD PTR [ebp-16], eax mov DWORD PTR [ebp-12], eax mov DWORD PTR [ebp-8], eax mov DWORD PTR [ebp-4], eax mov ecx, OFFSET __A452D4A0_stdio@h call @__CheckForDebuggerJustMyCode@4 ; 1949 : int _Result; ; 1950 : va_list _ArgList; ; 1951 : __crt_va_start(_ArgList, _Format); lea eax, DWORD PTR __Format$[ebp+4] mov DWORD PTR __ArgList$[ebp], eax ; 1952 : #pragma warning(suppress:28719) // 28719 ; 1953 : _Result = vsnprintf(_Buffer, _BufferCount, _Format, _ArgList); mov ecx, DWORD PTR __Format$[ebp] mov DWORD PTR __Format$[ebp], ecx ; 1440 : int const _Result = __stdio_common_vsprintf( mov esi, esp mov edx, DWORD PTR __ArgList$[ebp] push edx push 0 mov eax, DWORD PTR __Format$[ebp] push eax mov ecx, DWORD PTR __BufferCount$[ebp] push ecx mov edx, DWORD PTR __Buffer$[ebp] push edx call ___local_stdio_printf_options mov ecx, DWORD PTR [eax] or ecx, 2 mov edx, DWORD PTR [eax+4] push edx push ecx call DWORD PTR __imp____stdio_common_vsprintf add esp, 28 ; 0000001cH cmp esi, esp call __RTC_CheckEsp mov DWORD PTR __Result$1[ebp], eax ; 1441 : _CRT_INTERNAL_LOCAL_PRINTF_OPTIONS | _CRT_INTERNAL_PRINTF_STANDARD_SNPRINTF_BEHAVIOR, ; 1442 : _Buffer, _BufferCount, _Format, NULL, _ArgList); ; 1443 : ; 1444 : return _Result < 0 ? -1 : _Result; cmp DWORD PTR __Result$1[ebp], 0 jge SHORT $LN5@snprintf mov DWORD PTR tv81[ebp], -1 jmp SHORT $LN3@snprintf $LN5@snprintf: mov eax, DWORD PTR __Result$1[ebp] mov DWORD PTR tv81[ebp], eax $LN3@snprintf: ; 1952 : #pragma warning(suppress:28719) // 28719 ; 1953 : _Result = vsnprintf(_Buffer, _BufferCount, _Format, _ArgList); mov ecx, DWORD PTR tv81[ebp] mov DWORD PTR __Result$[ebp], ecx ; 1954 : __crt_va_end(_ArgList); mov DWORD PTR __ArgList$[ebp], 0 ; 1955 : return _Result; mov eax, DWORD PTR __Result$[ebp] ; 1956 : } pop esi add esp, 20 ; 00000014H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 _snprintf ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File c:\program files (x86)\windows kits\10\include\10.0.17763.0\ucrt\corecrt_stdio_config.h ; COMDAT ___local_stdio_printf_options _TEXT SEGMENT ___local_stdio_printf_options PROC ; COMDAT ; 86 : { push ebp mov ebp, esp mov ecx, OFFSET __2CC6E67D_corecrt_stdio_config@h call @__CheckForDebuggerJustMyCode@4 ; 87 : static unsigned __int64 _OptionsStorage; ; 88 : return &_OptionsStorage; mov eax, OFFSET ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9 ; `__local_stdio_printf_options'::`2'::_OptionsStorage ; 89 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 ___local_stdio_printf_options ENDP _TEXT ENDS END
; ; MSX specific routines ; by Stefano Bodrato, December 2007 ; ; int msx_sound(int reg, int val); ; ; Play a sound by PSG ; ; ; $Id: set_psg.asm,v 1.2 2015/01/19 01:33:04 pauloscustodio Exp $ ; PUBLIC set_psg EXTERN set_psg_callee EXTERN ASMDISP_SET_PSG_CALLEE set_psg: pop bc pop de pop hl push hl push de push bc jp set_psg_callee + ASMDISP_SET_PSG_CALLEE
; Z88 Small C+ Run Time Library ; Long functions ; ; feilipu 10/2021 SECTION code_clib SECTION code_l_sccz80 PUBLIC l_long_mult PUBLIC l_long_mult_u EXTERN l_mult_0 EXTERN l_mult_ulong_0 ;result = primary * secondary ;enter with secondary in dehl, primary on stack ;exit with product in dehl .l_long_mult .l_long_mult_u push de ;put secondary on stack push hl ld bc,hl ;secondary LSW ld de,sp+6 ;primary LSW offset ld hl,(de) ex de,hl call l_mult_ulong_0 ;dehl = de * bc push hl ;result LSW push de ;partial result MSW ld de,sp+12 ;primary MSW offset ld hl,(de) ld a,h ;check for primary MSW zero or l jp Z,demoted_prim ;primary MSW is zero ld bc,hl ld de,sp+4 ;secondary LSW offset ld hl,(de) ex de,hl call l_mult_0 ;hl = de * bc pop bc ;partial result MSW add hl,bc push hl .demoted_prim ld de,sp+6 ;secondary MSW offset ld hl,(de) ld a,h ;check for secondary MSW zero or l jp Z,demoted_sec ;secondary MSW is zero ld bc,hl ld de,sp+10 ;primary LSW offset ld hl,(de) ex de,hl call l_mult_0 ;hl = de * bc pop bc ;partial result MSW add hl,bc ;result MSW push hl .demoted_sec ld de,sp+8 ;get return from stack ld hl,(de) ld de,sp+12 ;place return on stack ld (de),hl pop hl ;result MSW pop bc ;result LSW ld de,sp+8 ;point to return again ex de,hl ;result MSW <> return sp ld sp,hl ;remove stacked parameters ld hl,bc ;result LSW ret
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #if OS_ANDROID #include "base/log_defines.h" #include "core/network/android/default_request_handler.h" #include "android/base/string/scoped_jstring_utf8.h" #include "base/android/jniprebuild/jniheader/RequestHandler_jni.h" #include "base/android/jni/android_jni.h" #include "core/manager/weex_core_manager.h" using namespace weex::core::network; static void InvokeOnSuccess(JNIEnv* env, jobject jcaller, jlong callback, jstring script, jstring bundleType) { CallbackWrapper* callback_wrapper = reinterpret_cast<CallbackWrapper*>(callback); WeexCore::ScopedJStringUTF8 jni_result(env, script); WeexCore::ScopedJStringUTF8 bundleTypeStr(env, bundleType); callback_wrapper->Invoke( jni_result.getChars() ? jni_result.getChars() : "", bundleTypeStr.getChars()); delete callback_wrapper; } static void InvokeOnFailed(JNIEnv* env, jobject jcaller, jlong callback) { LOGE_TAG("Eagle", "Download js file using src failed."); CallbackWrapper* callback_wrapper = reinterpret_cast<CallbackWrapper*>(callback); delete callback_wrapper; WeexCore::WeexCoreManager::Instance()->getPlatformBridge()->platform_side()->ReportException( "", "JsfmNotInitInEagleMode", "JSFramework is not initialized when executing bundle JS in eagle mode"); } namespace weex { namespace core { namespace network { bool DefaultRequestHandler::RegisterJNIUtils(JNIEnv* env) { return RegisterNativesImpl(env); } DefaultRequestHandler::DefaultRequestHandler() { JNIEnv* env = ::base::android::AttachCurrentThread(); Reset(env, Java_RequestHandler_create(env).Release()); } DefaultRequestHandler::~DefaultRequestHandler() {} void DefaultRequestHandler::Send(const char* instance_id, const char* url, Callback callback) { JNIEnv* env = ::base::android::AttachCurrentThread(); if (!env) return; CallbackWrapper* callback_wrapper = new CallbackWrapper(callback); ::base::android::ScopedLocalJavaRef<jstring> jni_url(env, env->NewStringUTF(url)); ::base::android::ScopedLocalJavaRef<jstring> jni_id( env, env->NewStringUTF(instance_id)); Java_RequestHandler_send(env, jni_object(), jni_id.Get(), jni_url.Get(), reinterpret_cast<jlong>(callback_wrapper)); } void DefaultRequestHandler::GetBundleType(const char *instance_id, const char *content, Callback callback){ JNIEnv* env = ::base::android::AttachCurrentThread(); if (!env) return; CallbackWrapper* callback_wrapper = new CallbackWrapper(callback); ::base::android::ScopedLocalJavaRef<jstring> jni_id(env, env->NewStringUTF(instance_id)); ::base::android::ScopedLocalJavaRef<jstring> jni_content(env,env->NewStringUTF(content)); Java_RequestHandler_getBundleType(env, jni_object(), jni_id.Get(), jni_content.Get(), reinterpret_cast<jlong>(callback_wrapper)); } RequestHandler* RequestHandler::CreateDefaultHandler() { return new DefaultRequestHandler(); } } // namespace network } // namespace core } // namespace weex #endif
#include "Tank.h"
/* $Id$ * EOSERV is released under the zlib license. * See LICENSE.txt for more info. */ #include "handlers.hpp" #include "../character.hpp" #include "../config.hpp" #include "../eodata.hpp" #include "../map.hpp" #include "../npc.hpp" #include "../npc_data.hpp" #include "../packet.hpp" #include "../world.hpp" #include "../util.hpp" namespace Handlers { // Talking to a skill master NPC void StatSkill_Open(Character *character, PacketReader &reader) { short id = reader.GetShort(); UTIL_FOREACH(character->map->npcs, npc) { if (npc->index == id && npc->Data().skill_learn.size() > 0) { character->npc = npc; character->npc_type = ENF::Skills; PacketBuilder reply(PACKET_STATSKILL, PACKET_OPEN, 2 + npc->Data().skill_name.length() + npc->Data().skill_learn.size() * 28); reply.AddShort(npc->id); reply.AddBreakString(npc->Data().skill_name.c_str()); UTIL_FOREACH_CREF(npc->Data().skill_learn, skill) { reply.AddShort(skill->id); reply.AddChar(skill->levelreq); reply.AddChar(skill->classreq); reply.AddInt(skill->cost); reply.AddShort(skill->skillreq[0]); reply.AddShort(skill->skillreq[1]); reply.AddShort(skill->skillreq[2]); reply.AddShort(skill->skillreq[3]); reply.AddShort(skill->strreq); reply.AddShort(skill->wisreq); reply.AddShort(skill->intreq); reply.AddShort(skill->agireq); reply.AddShort(skill->conreq); reply.AddShort(skill->chareq); } character->Send(reply); break; } } } // Learning a skill void StatSkill_Take(Character *character, PacketReader &reader) { /*int shopid = */reader.GetInt(); short spell_id = reader.GetShort(); if (character->HasSpell(spell_id)) return; if (character->npc_type == ENF::Skills) { UTIL_FOREACH_CREF(character->npc->Data().skill_learn, spell) { if (spell->id == spell_id) { if (character->level < spell->levelreq || character->HasItem(1) < spell->cost || character->display_str < spell->strreq || character->display_intl < spell->intreq || character->display_wis < spell->wisreq || character->display_agi < spell->agireq || character->display_con < spell->conreq || character->display_cha < spell->chareq) { // No correct reply for these PacketBuilder reply(PACKET_STATSKILL, PACKET_REPLY, 4); reply.AddShort(SKILLMASTER_WRONG_CLASS); reply.AddShort(character->clas); character->Send(reply); return; } if (spell->classreq != 0 && character->clas != spell->classreq) { PacketBuilder reply(PACKET_STATSKILL, PACKET_REPLY, 4); reply.AddShort(SKILLMASTER_WRONG_CLASS); reply.AddShort(character->clas); character->Send(reply); return; } UTIL_FOREACH(spell->skillreq, req) { if (req != 0 && !character->HasSpell(req)) { // No correct reply for this PacketBuilder reply(PACKET_STATSKILL, PACKET_REPLY, 4); reply.AddShort(SKILLMASTER_WRONG_CLASS); reply.AddShort(character->clas); character->Send(reply); return; } } character->DelItem(1, spell->cost); character->AddSpell(spell_id); PacketBuilder reply(PACKET_STATSKILL, PACKET_TAKE, 6); reply.AddShort(spell_id); reply.AddInt(character->HasItem(1)); character->Send(reply); break; } } } } // Forgeting a skill void StatSkill_Remove(Character *character, PacketReader &reader) { /*int shopid = */reader.GetInt(); short spell_id = reader.GetShort(); if (character->npc_type == ENF::Skills) { if (character->DelSpell(spell_id)) { PacketBuilder reply(PACKET_STATSKILL, PACKET_REMOVE, 2); reply.AddShort(spell_id); character->Send(reply); } } } // Spending a stat point on a skill void StatSkill_Add(Character *character, PacketReader &reader) { short *stat; TrainType action = TrainType(reader.GetChar()); int stat_id = reader.GetShort(); PacketBuilder reply; switch (action) { case TRAIN_STAT: if (character->statpoints <= 0) return; switch (stat_id) { case 1: stat = &character->str; break; case 2: stat = &character->intl; break; case 3: stat = &character->wis; break; case 4: stat = &character->agi; break; case 5: stat = &character->con; break; case 6: stat = &character->cha; break; default: return; } ++(*stat); --character->statpoints; character->CalculateStats(); reply.SetID(PACKET_STATSKILL, PACKET_PLAYER); reply.ReserveMore(32); reply.AddShort(character->statpoints); reply.AddShort(character->display_str); reply.AddShort(character->display_intl); reply.AddShort(character->display_wis); reply.AddShort(character->display_agi); reply.AddShort(character->display_con); reply.AddShort(character->display_cha); reply.AddShort(character->maxhp); reply.AddShort(character->maxtp); reply.AddShort(character->maxsp); reply.AddShort(character->maxweight); reply.AddShort(character->mindam); reply.AddShort(character->maxdam); reply.AddShort(character->accuracy); reply.AddShort(character->evade); reply.AddShort(character->armor); character->Send(reply); break; case TRAIN_SKILL: if (character->skillpoints <= 0 || !character->HasSpell(stat_id) || character->SpellLevel(stat_id) >= int(character->world->config["MaxSkillLevel"])) { return; } UTIL_IFOREACH(character->spells, spell) { if (spell->id == stat_id) { ++spell->level; --character->skillpoints; reply.SetID(PACKET_STATSKILL, PACKET_ACCEPT); reply.ReserveMore(6); reply.AddShort(character->skillpoints); reply.AddShort(stat_id); reply.AddShort(spell->level); character->Send(reply); } } break; } } // Reseting character's skills void StatSkill_Junk(Character *character, PacketReader &reader) { (void)reader; /*int shopid = reader.GetInt();*/ if (character->npc_type == ENF::Skills) { character->Reset(); PacketBuilder builder(PACKET_STATSKILL, PACKET_JUNK, 36); builder.AddShort(character->statpoints); builder.AddShort(character->skillpoints); builder.AddShort(character->hp); builder.AddShort(character->maxhp); builder.AddShort(character->tp); builder.AddShort(character->maxtp); builder.AddShort(character->maxsp); builder.AddShort(character->display_str); builder.AddShort(character->display_intl); builder.AddShort(character->display_wis); builder.AddShort(character->display_agi); builder.AddShort(character->display_con); builder.AddShort(character->display_cha); builder.AddShort(character->mindam); builder.AddShort(character->maxdam); builder.AddShort(character->accuracy); builder.AddShort(character->evade); builder.AddShort(character->armor); character->Send(builder); } } PACKET_HANDLER_REGISTER(PACKET_STATSKILL) Register(PACKET_OPEN, StatSkill_Open, Playing); Register(PACKET_TAKE, StatSkill_Take, Playing); Register(PACKET_REMOVE, StatSkill_Remove, Playing); Register(PACKET_ADD, StatSkill_Add, Playing); Register(PACKET_JUNK, StatSkill_Junk, Playing); PACKET_HANDLER_REGISTER_END(PACKET_STATSKILL) }
<% from pwnlib.shellcraft.mips.linux import syscall %> <%page args="level"/> <%docstring> Invokes the syscall iopl. See 'man 2 iopl' for more information. Arguments: level(int): level </%docstring> ${syscall('SYS_iopl', level)}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2017-19, Lawrence Livermore National Security, LLC // and RAJA Performance Suite project contributors. // See the RAJAPerf/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// /// /// Basic data types used in the Suite. /// #ifndef RAJAPerf_RPTypes_HPP #define RAJAPerf_RPTypes_HPP #include "RAJA/util/types.hpp" // // Only one of the following (double or float) should be defined. // #define RP_USE_DOUBLE //#undef RP_USE_DOUBLE //#define RP_USE_FLOAT #undef RP_USE_FLOAT #define RP_USE_COMPLEX //#undef RP_USE_COMPLEX #if defined(RP_USE_COMPLEX) #include <complex> #endif namespace rajaperf { /*! ****************************************************************************** * * \brief Type used for indexing in all kernel repetition loops. * * It is volatile to ensure that kernels will not be optimized away by * compilers, which can happen in some circumstances. * ****************************************************************************** */ using RepIndex_type = volatile int; /*! ****************************************************************************** * * \brief Types used for all kernel loop indexing. * ****************************************************************************** */ using Index_type = RAJA::Index_type; /// using Index_ptr = Index_type*; /*! ****************************************************************************** * * \brief Integer types used in kernels. * ****************************************************************************** */ using Int_type = int; /// using Int_ptr = Int_type*; /*! ****************************************************************************** * * \brief Type used for all kernel checksums. * ****************************************************************************** */ using Checksum_type = long double; /*! ****************************************************************************** * * \brief Floating point types used in kernels. * ****************************************************************************** */ #if defined(RP_USE_DOUBLE) /// using Real_type = double; #elif defined(RP_USE_FLOAT) /// using Real_type = float; #else #error Real_type is undefined! #endif using Real_ptr = Real_type*; typedef Real_type* RAJA_RESTRICT ResReal_ptr; #if defined(RP_USE_COMPLEX) /// using Complex_type = std::complex<Real_type>; using Complex_ptr = Complex_type*; typedef Complex_type* RAJA_RESTRICT ResComplex_ptr; #endif } // closing brace for rajaperf namespace #endif // closing endif for header file include guard
; A322108: Distance of n-th iteration in an alternating rectangular spiral. ; 1,3,7,15,29,50,79,118,169,233,311,405,517,648,799,972,1169,1391,1639,1915,2221,2558,2927,3330,3769,4245,4759,5313,5909,6548,7231,7960,8737,9563,10439,11367,12349,13386,14479 mov $1,$0 mul $1,$0 mov $2,$0 sub $0,2 mul $1,$0 div $1,2 add $1,1 div $1,2 add $1,1 add $1,$2 mov $3,$2 mul $3,$2 add $1,$3
; A094985: a(n) = floor(8^n/5^n). ; 1,1,2,4,6,10,16,26,42,68,109,175,281,450,720,1152,1844,2951,4722,7555,12089,19342,30948,49517,79228,126765,202824,324518,519229,830767,1329227,2126764,3402823,5444517,8711228,13937965,22300745,35681192,57089907,91343852,146150163,233840261,374144419,598631070,957809713,1532495540,2451992865,3923188584,6277101735,10043362776,16069380442,25711008708,41137613933,65820182292,105312291668,168499666669,269599466671,431359146674,690174634679,1104279415486,1766847064778,2826955303645,4523128485832,7237005577332,11579208923731,18526734277970,29642774844752,47428439751604,75885503602567,121416805764108,194266889222572,310827022756116,497323236409786,795717178255658,1273147485209053,2037035976334486,3259257562135177,5214812099416284,8343699359066055,13349918974505688,21359870359209100,34175792574734561,54681268119575298,87490028991320476,139984046386112763,223974474217780421,358359158748448673,573374653997517877,917399446396028604,1467839114233645767,2348542582773833227,3757668132438133164,6012269011901013063,9619630419041620901,15391408670466593442,24626253872746549507,39402006196394479212,63043209914231166739,100869135862769866783,161390617380431786853 mov $1,16 pow $1,$0 mov $2,10 pow $2,$0 div $1,$2 mov $0,$1
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("keplercoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("KeplercoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start keplercoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fde/fde_gedevice.h" #include <algorithm> #include <memory> #include "core/fxge/cfx_gemodule.h" #include "core/fxge/cfx_graphstatedata.h" #include "core/fxge/cfx_renderdevice.h" #include "core/fxge/cfx_substfont.h" #include "xfa/fde/cfde_path.h" #include "xfa/fde/fde_object.h" #include "xfa/fgas/font/cfgas_fontmgr.h" #include "xfa/fgas/font/cfgas_gefont.h" CFDE_RenderDevice::CFDE_RenderDevice(CFX_RenderDevice* pDevice, bool bOwnerDevice) : m_pDevice(pDevice), m_bOwnerDevice(bOwnerDevice), m_iCharCount(0) { ASSERT(pDevice); FX_RECT rt = m_pDevice->GetClipBox(); m_rtClip.Set((FX_FLOAT)rt.left, (FX_FLOAT)rt.top, (FX_FLOAT)rt.Width(), (FX_FLOAT)rt.Height()); } CFDE_RenderDevice::~CFDE_RenderDevice() { if (m_bOwnerDevice) delete m_pDevice; } int32_t CFDE_RenderDevice::GetWidth() const { return m_pDevice->GetWidth(); } int32_t CFDE_RenderDevice::GetHeight() const { return m_pDevice->GetHeight(); } void CFDE_RenderDevice::SaveState() { m_pDevice->SaveState(); } void CFDE_RenderDevice::RestoreState() { m_pDevice->RestoreState(false); const FX_RECT& rt = m_pDevice->GetClipBox(); m_rtClip.Set((FX_FLOAT)rt.left, (FX_FLOAT)rt.top, (FX_FLOAT)rt.Width(), (FX_FLOAT)rt.Height()); } bool CFDE_RenderDevice::SetClipRect(const CFX_RectF& rtClip) { m_rtClip = rtClip; return m_pDevice->SetClip_Rect(FX_RECT((int32_t)FXSYS_floor(rtClip.left), (int32_t)FXSYS_floor(rtClip.top), (int32_t)FXSYS_ceil(rtClip.right()), (int32_t)FXSYS_ceil(rtClip.bottom()))); } const CFX_RectF& CFDE_RenderDevice::GetClipRect() { return m_rtClip; } bool CFDE_RenderDevice::SetClipPath(const CFDE_Path* pClip) { return false; } CFDE_Path* CFDE_RenderDevice::GetClipPath() const { return nullptr; } FX_FLOAT CFDE_RenderDevice::GetDpiX() const { return 96; } FX_FLOAT CFDE_RenderDevice::GetDpiY() const { return 96; } bool CFDE_RenderDevice::DrawImage(CFX_DIBSource* pDib, const CFX_RectF* pSrcRect, const CFX_RectF& dstRect, const CFX_Matrix* pImgMatrix, const CFX_Matrix* pDevMatrix) { CFX_RectF srcRect; if (pSrcRect) { srcRect = *pSrcRect; } else { srcRect.Set(0, 0, (FX_FLOAT)pDib->GetWidth(), (FX_FLOAT)pDib->GetHeight()); } if (srcRect.IsEmpty()) { return false; } CFX_Matrix dib2fxdev; if (pImgMatrix) { dib2fxdev = *pImgMatrix; } else { dib2fxdev.SetIdentity(); } dib2fxdev.a = dstRect.width; dib2fxdev.d = -dstRect.height; dib2fxdev.e = dstRect.left; dib2fxdev.f = dstRect.bottom(); if (pDevMatrix) { dib2fxdev.Concat(*pDevMatrix); } void* handle = nullptr; m_pDevice->StartDIBits(pDib, 255, 0, (const CFX_Matrix*)&dib2fxdev, 0, handle); while (m_pDevice->ContinueDIBits(handle, nullptr)) { } m_pDevice->CancelDIBits(handle); return !!handle; } bool CFDE_RenderDevice::DrawString(CFDE_Brush* pBrush, const CFX_RetainPtr<CFGAS_GEFont>& pFont, const FXTEXT_CHARPOS* pCharPos, int32_t iCount, FX_FLOAT fFontSize, const CFX_Matrix* pMatrix) { ASSERT(pBrush && pFont && pCharPos && iCount > 0); CFX_Font* pFxFont = pFont->GetDevFont(); FX_ARGB argb = pBrush->GetColor(); if ((pFont->GetFontStyles() & FX_FONTSTYLE_Italic) != 0 && !pFxFont->IsItalic()) { FXTEXT_CHARPOS* pCP = (FXTEXT_CHARPOS*)pCharPos; FX_FLOAT* pAM; for (int32_t i = 0; i < iCount; ++i) { static const FX_FLOAT mc = 0.267949f; pAM = pCP->m_AdjustMatrix; pAM[2] = mc * pAM[0] + pAM[2]; pAM[3] = mc * pAM[1] + pAM[3]; pCP++; } } FXTEXT_CHARPOS* pCP = (FXTEXT_CHARPOS*)pCharPos; CFX_RetainPtr<CFGAS_GEFont> pCurFont; CFX_RetainPtr<CFGAS_GEFont> pSTFont; FXTEXT_CHARPOS* pCurCP = nullptr; int32_t iCurCount = 0; #if _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ uint32_t dwFontStyle = pFont->GetFontStyles(); CFX_Font FxFont; CFX_SubstFont* SubstFxFont = new CFX_SubstFont(); FxFont.SetSubstFont(std::unique_ptr<CFX_SubstFont>(SubstFxFont)); SubstFxFont->m_Weight = dwFontStyle & FX_FONTSTYLE_Bold ? 700 : 400; SubstFxFont->m_ItalicAngle = dwFontStyle & FX_FONTSTYLE_Italic ? -12 : 0; SubstFxFont->m_WeightCJK = SubstFxFont->m_Weight; SubstFxFont->m_bItalicCJK = !!(dwFontStyle & FX_FONTSTYLE_Italic); #endif // _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ for (int32_t i = 0; i < iCount; ++i) { pSTFont = pFont->GetSubstFont((int32_t)pCP->m_GlyphIndex); pCP->m_GlyphIndex &= 0x00FFFFFF; pCP->m_bFontStyle = false; if (pCurFont != pSTFont) { if (pCurFont) { pFxFont = pCurFont->GetDevFont(); #if _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ FxFont.SetFace(pFxFont->GetFace()); m_pDevice->DrawNormalText(iCurCount, pCurCP, &FxFont, -fFontSize, (const CFX_Matrix*)pMatrix, argb, FXTEXT_CLEARTYPE); #else m_pDevice->DrawNormalText(iCurCount, pCurCP, pFxFont, -fFontSize, (const CFX_Matrix*)pMatrix, argb, FXTEXT_CLEARTYPE); #endif // _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ } pCurFont = pSTFont; pCurCP = pCP; iCurCount = 1; } else { iCurCount++; } pCP++; } if (pCurFont && iCurCount) { pFxFont = pCurFont->GetDevFont(); #if _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ FxFont.SetFace(pFxFont->GetFace()); bool bRet = m_pDevice->DrawNormalText( iCurCount, pCurCP, &FxFont, -fFontSize, (const CFX_Matrix*)pMatrix, argb, FXTEXT_CLEARTYPE); FxFont.SetFace(nullptr); return bRet; #else return m_pDevice->DrawNormalText(iCurCount, pCurCP, pFxFont, -fFontSize, (const CFX_Matrix*)pMatrix, argb, FXTEXT_CLEARTYPE); #endif // _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ } #if _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ FxFont.SetFace(nullptr); #endif // _FXM_PLATFORM_ != _FXM_PLATFORM_WINDOWS_ return true; } bool CFDE_RenderDevice::DrawBezier(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_PointF& pt1, const CFX_PointF& pt2, const CFX_PointF& pt3, const CFX_PointF& pt4, const CFX_Matrix* pMatrix) { CFX_PointsF points; points.Add(pt1); points.Add(pt2); points.Add(pt3); points.Add(pt4); CFDE_Path path; path.AddBezier(points); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawCurve(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_PointsF& points, bool bClosed, FX_FLOAT fTension, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddCurve(points, bClosed, fTension); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawEllipse(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_RectF& rect, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddEllipse(rect); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawLines(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_PointsF& points, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddLines(points); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawLine(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_PointF& pt1, const CFX_PointF& pt2, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddLine(pt1, pt2); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawPath(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFDE_Path* pPath, const CFX_Matrix* pMatrix) { CFDE_Path* pGePath = (CFDE_Path*)pPath; if (!pGePath) return false; CFX_GraphStateData graphState; if (!CreatePen(pPen, fPenWidth, graphState)) { return false; } return m_pDevice->DrawPath(&pGePath->m_Path, (const CFX_Matrix*)pMatrix, &graphState, 0, pPen->GetColor(), 0); } bool CFDE_RenderDevice::DrawPolygon(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_PointsF& points, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddPolygon(points); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::DrawRectangle(CFDE_Pen* pPen, FX_FLOAT fPenWidth, const CFX_RectF& rect, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddRectangle(rect); return DrawPath(pPen, fPenWidth, &path, pMatrix); } bool CFDE_RenderDevice::FillClosedCurve(CFDE_Brush* pBrush, const CFX_PointsF& points, FX_FLOAT fTension, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddCurve(points, true, fTension); return FillPath(pBrush, &path, pMatrix); } bool CFDE_RenderDevice::FillEllipse(CFDE_Brush* pBrush, const CFX_RectF& rect, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddEllipse(rect); return FillPath(pBrush, &path, pMatrix); } bool CFDE_RenderDevice::FillPolygon(CFDE_Brush* pBrush, const CFX_PointsF& points, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddPolygon(points); return FillPath(pBrush, &path, pMatrix); } bool CFDE_RenderDevice::FillRectangle(CFDE_Brush* pBrush, const CFX_RectF& rect, const CFX_Matrix* pMatrix) { CFDE_Path path; path.AddRectangle(rect); return FillPath(pBrush, &path, pMatrix); } bool CFDE_RenderDevice::CreatePen(CFDE_Pen* pPen, FX_FLOAT fPenWidth, CFX_GraphStateData& graphState) { if (!pPen) return false; graphState.m_LineCap = CFX_GraphStateData::LineCapButt; graphState.m_LineJoin = CFX_GraphStateData::LineJoinMiter; graphState.m_LineWidth = fPenWidth; graphState.m_MiterLimit = 10; graphState.m_DashPhase = 0; return true; } bool CFDE_RenderDevice::FillPath(CFDE_Brush* pBrush, const CFDE_Path* pPath, const CFX_Matrix* pMatrix) { CFDE_Path* pGePath = (CFDE_Path*)pPath; if (!pGePath) return false; if (!pBrush) return false; return m_pDevice->DrawPath(&pGePath->m_Path, pMatrix, nullptr, pBrush->GetColor(), 0, FXFILL_WINDING); }
; Echo program that waits for user to enter a character and than echoing it. ; NASM assembly for Mac OS X x64. ; Differes from 'echo' program by using procedures. section .data msg_enter: db "Please, enter a char: " .len: equ $ - msg_enter msg_entered: db "You have entered: " .len: equ $ - msg_entered section .bss char: resb 1 ; reserve one byte for one char section .text global _main _main: call show_msg_enter call read_char call show_msg_entered call show_char call exit show_msg_enter: mov rax, 0x2000004 ; put the write-system-call-code into register rax mov rdi, 1 ; tell kernel to use stdout mov rsi, msg_enter ; rsi is where the kernel expects to find the address of the message mov rdx, msg_enter.len ; and rdx is where the kernel expects to find the length of the message syscall ret read_char: mov rax, 0x2000003 ; put the read-system-call-code into register rax mov rdi, 0 ; tell kernel to use stdin mov rsi, char ; address of storage, declared in section .bss mov rdx, 2 ; get 2 bytes from the kernel's buffer (one for the carriage return) syscall ret show_msg_entered: mov rax, 0x2000004 ; put the write-system-call-code into register rax mov rdi, 1 ; tell kernel to use stdout mov rsi, msg_entered ; rsi is where the kernel expects to find the address of the message mov rdx, msg_entered.len ; and rdx is where the kernel expects to find the length of the message syscall ret show_char: mov rax, 0x2000004 ; put the write-system-call-code into register rax mov rdi, 1 ; tell kernel to use stdout mov rsi, char ; address of storage of char mov rdx, 2 ; the second byte is to apply the carriage return expected in the string syscall ret exit: mov rax, 0x2000001 ; exit system call xor rdi, rdi ; equivalent to "mov rdi, 0", however xor is preferred pattern on modern ; CPUs syscall
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/instrumentation/ProcessStats.h" #if defined(_WINDOWS) // Include windows.h first because other includes from windows API need it. // The blank line after the include is necessary to avoid lint error. #define WIN32_LEAN_AND_MEAN #define NOMINMAX // do not define min/max macros #include <windows.h> #include <psapi.h> #elif defined(__MACH__) #include <mach/mach.h> #elif defined(__linux__) #include <unistd.h> #include <fstream> #endif // __MACH__, __linux__ namespace hermes { namespace vm { namespace { ProcessStats::Info getProcessStatSnapshot() { int64_t rss, va; #if defined(_WINDOWS) PROCESS_MEMORY_COUNTERS pmc; BOOL ret = GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); assert(ret != 0 && "Failed to call GetProcessMemoryInfo"); (void)ret; MEMORYSTATUSEX ms; ms.dwLength = sizeof(ms); ret = GlobalMemoryStatusEx(&ms); assert(ret != 0 && "Failed to call GlobalMemoryStatusEx"); (void)ret; rss = pmc.WorkingSetSize / 1024; va = (ms.ullTotalVirtual - ms.ullAvailVirtual) / 1024; #elif defined(__MACH__) const task_t self = mach_task_self(); struct task_basic_info info; mach_msg_type_number_t fields = TASK_BASIC_INFO_COUNT; auto ret = task_info( self, TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &fields); (void)ret; assert(ret == KERN_SUCCESS && "Failed to get process stats."); assert(fields == TASK_BASIC_INFO_COUNT && "Not all process stats returned."); rss = info.resident_size / 1024; va = info.virtual_size / 1024; #elif defined(__linux__) std::ifstream statm("/proc/self/statm"); statm >> va >> rss; // Linux outputs these metrics as a number of pages, correct for that. const size_t PS = getpagesize(); rss *= PS / 1024; va *= PS / 1024; #elif defined(__EMSCRIPTEN__) rss = va = 0; #else #error "Unsupported platform" #endif ProcessStats::Info result; result.RSSkB = rss; result.VAkB = va; return result; } } // namespace void ProcessStats::Info::printJSON(llvh::raw_ostream &os) { os << "{\n " << "\t\"Integral of RSS kBms\": " << RSSkB << ",\n" << "\t\"Integral of VA kBms\": " << VAkB << "\n" << "}\n"; } ProcessStats::ProcessStats() : initTime_(Clock::now()), initInfo_(getProcessStatSnapshot()) {} void ProcessStats::sample(ProcessStats::Clock::time_point now) { using namespace std::chrono; Info info = getProcessStatSnapshot(); int64_t deltaTms = duration_cast<milliseconds>(now - initTime_).count(); iRSSkBms_.push(deltaTms, info.RSSkB - initInfo_.RSSkB); iVAkBms_.push(deltaTms, info.VAkB - initInfo_.VAkB); } ProcessStats::Info ProcessStats::getIntegratedInfo() const { ProcessStats::Info ret; ret.RSSkB = iRSSkBms_.area(); ret.VAkB = iVAkBms_.area(); return ret; } } // namespace vm } // namespace hermes
; A126284: a(n) = 5*2^n - 4*n - 5. ; 1,7,23,59,135,291,607,1243,2519,5075,10191,20427,40903,81859,163775,327611,655287,1310643,2621359,5242795,10485671,20971427,41942943,83885979,167772055,335544211,671088527,1342177163,2684354439,5368708995,10737418111,21474836347,42949672823,85899345779,171798691695,343597383531,687194767207,1374389534563,2748779069279,5497558138715,10995116277591,21990232555347,43980465110863,87960930221899,175921860443975,351843720888131,703687441776447,1407374883553083,2814749767106359,5629499534212915,11258999068426031,22517998136852267,45035996273704743,90071992547409699,180143985094819615,360287970189639451,720575940379279127,1441151880758558483,2882303761517117199,5764607523034234635,11529215046068469511,23058430092136939267,46116860184273878783,92233720368547757819,184467440737095515895,368934881474191032051,737869762948382064367,1475739525896764129003,2951479051793528258279,5902958103587056516835,11805916207174113033951,23611832414348226068187,47223664828696452136663,94447329657392904273619,188894659314785808547535,377789318629571617095371,755578637259143234191047,1511157274518286468382403,3022314549036572936765119,6044629098073145873530555,12089258196146291747061431,24178516392292583494123187,48357032784585166988246703,96714065569170333976493739,193428131138340667952987815,386856262276681335905975971,773712524553362671811952287,1547425049106725343623904923,3094850098213450687247810199,6189700196426901374495620755,12379400392853802748991241871,24758800785707605497982484107,49517601571415210995964968583,99035203142830421991929937539,198070406285660843983859875455,396140812571321687967719751291,792281625142643375935439502967,1584563250285286751870879006323,3169126500570573503741758013039,6338253001141147007483516026475 mov $1,$0 lpb $1 sub $1,1 add $2,5 add $0,$2 mul $2,2 lpe add $0,1
#include "Animation.h" #include "../game.h" AnimatedTexture::AnimatedTexture(std::string id, int cFrame, int mFrame, int w, int h, int posX, int posY) { currFrame_ = cFrame; maxFrame_ = mFrame; x_ = posX; y_ = posY; id_ = id; frame_.w = w; // sets the size of the rectangle frame_.h = h; frame_.x = cFrame * frame_.w; frame_.y = 0; } void AnimatedTexture::loadFile(std::string filename) { TextureManager::Instance()->Load(id_, filename, Game::renderer_); } void AnimatedTexture::Render(int posX, int posY, bool reset) { // draw a frame to the screen // put posX and posY just in case but it should (probably) be viewport_center.x and .y if (reset) { // if you want to "force" the display of the initial frame currFrame_ = 0; frame_.x = 0; } TextureManager::Instance()->DrawFrame(id_, frame_, {posX, posY, 64, 64}, Game::renderer_); } void AnimatedTexture::Update() { if (SDL_GetTicks() - frameTime < frameDelay) return; if (currFrame_ >= maxFrame_) { currFrame_ = 0; } else currFrame_++; // move onto next frame frame_.x = currFrame_ * frame_.w; frameTime = SDL_GetTicks(); }
;-------------------------------------------------------- ; File Created by SDCC : free open source ANSI-C Compiler ; Version 3.5.0 #9253 (Jun 20 2015) (MINGW64) ; This file was generated Thu Aug 18 09:46:32 2016 ;-------------------------------------------------------- ; PIC16 port for the Microchip 16-bit core micros ;-------------------------------------------------------- list p=18f4520 radix dec CONFIG MCLRE=ON CONFIG OSC=HS CONFIG WDT=OFF CONFIG LVP=OFF CONFIG DEBUG=OFF CONFIG WDTPS=1 ;-------------------------------------------------------- ; public variables in this module ;-------------------------------------------------------- global _main ;-------------------------------------------------------- ; extern variables in this module ;-------------------------------------------------------- extern _printf ;-------------------------------------------------------- ; Equates to used internal registers ;-------------------------------------------------------- FSR1L equ 0xfe1 POSTDEC1 equ 0xfe5 ; Internal registers .registers udata_ovr 0x0000 r0x00 res 1 r0x01 res 1 r0x02 res 1 ;-------------------------------------------------------- ; interrupt vector ;-------------------------------------------------------- ;-------------------------------------------------------- ; global & static initialisations ;-------------------------------------------------------- ; I code from now on! ; ; Starting pCode block S_Aula1__main code _main: ; .line 19; Aula1.c printf("Douglas Barbosa \nAmaral"); MOVLW UPPER(___str_0) MOVWF r0x02 MOVLW HIGH(___str_0) MOVWF r0x01 MOVLW LOW(___str_0) MOVWF r0x00 MOVF r0x02, W MOVWF POSTDEC1 MOVF r0x01, W MOVWF POSTDEC1 MOVF r0x00, W MOVWF POSTDEC1 CALL _printf MOVLW 0x03 ADDWF FSR1L, F _00107_DS_: BRA _00107_DS_ RETURN ; ; Starting pCode block ___str_0: DB 0x44, 0x6f, 0x75, 0x67, 0x6c, 0x61, 0x73, 0x20, 0x42, 0x61, 0x72, 0x62 DB 0x6f, 0x73, 0x61, 0x20, 0x0a, 0x41, 0x6d, 0x61, 0x72, 0x61, 0x6c, 0x00 ; Statistics: ; code size: 40 (0x0028) bytes ( 0.03%) ; 20 (0x0014) words ; udata size: 0 (0x0000) bytes ( 0.00%) ; access size: 3 (0x0003) bytes end
; A014062: a(n) = binomial(n^2, n). ; 1,1,6,84,1820,53130,1947792,85900584,4426165368,260887834350,17310309456440,1276749965026536,103619293824707388,9176358300744339432,880530516383349192480,91005567811177478095440,10078751602022313874633200,1190739044344491048895397910,149482492334195165714038760136,19870867053543756004133247695400,2788360983670896737872851072994080,411887396336567398822620727355402190,63887407766986865702182544710470036560,10381758958529585222885358558747563185920,1763783520005146433232953016554504214270600 mov $1,$0 pow $0,2 bin $0,$1
Map_5CD00: dc.w word_5CD12-Map_5CD00 dc.w word_5CD20-Map_5CD00 dc.w word_5CD2E-Map_5CD00 dc.w word_5CD36-Map_5CD00 dc.w word_5CD3E-Map_5CD00 dc.w word_5CD46-Map_5CD00 dc.w word_5CD4E-Map_5CD00 dc.w word_5CD56-Map_5CD00 dc.w word_5CD5E-Map_5CD00 word_5CD12: dc.w 2 dc.b $F4, 5, 0, 0, $FF, $F4 dc.b 4, 8, 0, 4, $FF, $F4 word_5CD20: dc.w 2 dc.b $F4, 5, 0, 0, $FF, $F4 dc.b 4, 8, 0, 7, $FF, $F4 word_5CD2E: dc.w 1 dc.b $F4, 6, 0, $A, $FF, $F8 word_5CD36: dc.w 1 dc.b $F4, 6, 0, $10, $FF, $F8 word_5CD3E: dc.w 1 dc.b $FC, 5, 0, $16, $FF, $F2 word_5CD46: dc.w 1 dc.b $FC, 5, 0, $1A, $FF, $F2 word_5CD4E: dc.w 1 dc.b $FC, 5, 0, $1E, $FF, $F2 word_5CD56: dc.w 1 dc.b $F4, 6, 0, $22, $FF, $F8 word_5CD5E: dc.w 1 dc.b $F4, 6, 0, $28, $FF, $F8
; Turn key repeat off ; 10 SYS (49200) *=$0801 BYTE $0E, $08, $0A, $00, $9E, $20, $28, $34, $39, $32, $30, $30, $29, $00, $00, $00 *=$c030 lda #$0 sta $28a ; 650 - repeat all keys if $80 rts
; w_vector_t *w_vector_init_callee(void *p, size_t capacity, size_t max_size) SECTION code_adt_w_vector PUBLIC _w_vector_init_callee _w_vector_init_callee: pop hl pop de pop bc ex (sp),hl INCLUDE "adt/w_vector/z80/asm_w_vector_init.asm"
; A090305: a(n) = 16*a(n-1) + a(n-2), starting with a(0) = 2 and a(1) = 16. ; Submitted by Jamie Morken(s4) ; 2,16,258,4144,66562,1069136,17172738,275832944,4430499842,71163830416,1143051786498,18359992414384,294902930416642,4736806879080656,76083812995707138,1222077814810394864,19629328849962024962,315291339414202794256,5064290759477206733058,81343943491049510523184,1306567386616269375104002,20986422129351359512187216,337089321456238021570099458,5414415565429159704633778544,86967738368322793295710556162,1396898229458593852436002677136,22437339409705824432271753390338,360394328784751784768784056922544 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 mul $2,8 add $3,$2 lpe mov $0,$3 mul $0,2
; Functions dealing with palettes. UpdatePalsIfCGB:: ; update bgp data from wBGPals2 ; update obp data from wOBPals2 ; return carry if successful ; check cgb ldh a, [hCGB] and a ret z UpdateCGBPals:: ; return carry if successful ; any pals to update? ldh a, [hCGBPalUpdate] and a ret z ForceUpdateCGBPals:: ldh a, [rSVBK] push af ld a, BANK(wBGPals2) ldh [rSVBK], a ld hl, wBGPals2 ; copy 8 pals to bgpd ld a, 1 << rBGPI_AUTO_INCREMENT ldh [rBGPI], a ld c, LOW(rBGPD) ld b, 8 / 2 .bgp rept (1 palettes) * 2 ld a, [hli] ldh [c], a endr dec b jr nz, .bgp ; hl is now wOBPals2 ; copy 8 pals to obpd ld a, 1 << rOBPI_AUTO_INCREMENT ldh [rOBPI], a ld c, LOW(rOBPD) ld b, 8 / 2 .obp rept (1 palettes) * 2 ld a, [hli] ldh [c], a endr dec b jr nz, .obp pop af ldh [rSVBK], a ; clear pal update queue xor a ldh [hCGBPalUpdate], a scf ret DmgToCgbBGPals:: ; exists to forego reinserting cgb-converted image data ; input: a -> bgp ldh [rBGP], a push af ; Don't need to be here if DMG ldh a, [hCGB] and a jr z, .end push hl push de push bc ldh a, [rSVBK] push af ld a, BANK(wBGPals2) ldh [rSVBK], a ; copy & reorder bg pal buffer ld hl, wBGPals2 ; to ld de, wBGPals1 ; from ; order ldh a, [rBGP] ld b, a ; all pals ld c, 8 call CopyPals ; request pal update ld a, 1 ldh [hCGBPalUpdate], a pop af ldh [rSVBK], a pop bc pop de pop hl .end pop af ret DmgToCgbObjPals:: ; exists to forego reinserting cgb-converted image data ; input: d -> obp1 ; e -> obp2 ld a, e ldh [rOBP0], a ld a, d ldh [rOBP1], a ldh a, [hCGB] and a ret z push hl push de push bc ldh a, [rSVBK] push af ld a, BANK(wOBPals2) ldh [rSVBK], a ; copy & reorder obj pal buffer ld hl, wOBPals2 ; to ld de, wOBPals1 ; from ; order ldh a, [rOBP0] ld b, a ; all pals ld c, 8 call CopyPals ; request pal update ld a, 1 ldh [hCGBPalUpdate], a pop af ldh [rSVBK], a pop bc pop de pop hl ret DmgToCgbObjPal0:: ldh [rOBP0], a push af ; Don't need to be here if not CGB ldh a, [hCGB] and a jr z, .dmg push hl push de push bc ldh a, [rSVBK] push af ld a, BANK(wOBPals2) ldh [rSVBK], a ld hl, wOBPals2 palette 0 ld de, wOBPals1 palette 0 ldh a, [rOBP0] ld b, a ld c, 1 call CopyPals ld a, 1 ldh [hCGBPalUpdate], a pop af ldh [rSVBK], a pop bc pop de pop hl .dmg pop af ret DmgToCgbObjPal1:: ldh [rOBP1], a push af ldh a, [hCGB] and a jr z, .dmg push hl push de push bc ldh a, [rSVBK] push af ld a, BANK(wOBPals2) ldh [rSVBK], a ld hl, wOBPals2 palette 1 ld de, wOBPals1 palette 1 ldh a, [rOBP1] ld b, a ld c, 1 call CopyPals ld a, 1 ldh [hCGBPalUpdate], a pop af ldh [rSVBK], a pop bc pop de pop hl .dmg pop af ret CopyPals:: ; copy c palettes in order b from de to hl push bc ld c, NUM_PAL_COLORS .loop push de push hl ; get pal color ld a, b maskbits 1 << PAL_COLOR_SIZE ; 2 bytes per color add a ld l, a ld h, 0 add hl, de ld e, [hl] inc hl ld d, [hl] ; dest pop hl ; write color ld [hl], e inc hl ld [hl], d inc hl ; next pal color rept PAL_COLOR_SIZE srl b endr ; source pop de ; done pal? dec c jr nz, .loop ; de += 8 (next pal) ld a, PALETTE_SIZE add e jr nc, .ok inc d .ok ld e, a ; how many more pals? pop bc dec c jr nz, CopyPals ret ClearVBank1:: ldh a, [hCGB] and a ret z ld a, 1 ldh [rVBK], a ld hl, VRAM_Begin ld bc, VRAM_End - VRAM_Begin xor a call ByteFill xor a ldh [rVBK], a ret ReloadSpritesNoPalettes:: ldh a, [hCGB] and a ret z ldh a, [rSVBK] push af ld a, BANK(wBGPals2) ldh [rSVBK], a ld hl, wBGPals2 ld bc, (8 palettes) + (2 palettes) xor a call ByteFill pop af ldh [rSVBK], a ld a, 1 ldh [hCGBPalUpdate], a jp DelayFrame FarCallSwapTextboxPalettes:: homecall SwapTextboxPalettes ret FarCallScrollBGMapPalettes:: homecall ScrollBGMapPalettes ret LoadPalette_Mon:: ldh a, [hROMBank] push af ld a, BANK(PokemonPalettes) ; also BANK(TrainerPalettes) rst Bankswitch ldh a, [rSVBK] push af ld a, BANK(wBGPals1) ldh [rSVBK], a ld a, LOW(PALRGB_WHITE) ld [de], a inc de ld a, HIGH(PALRGB_WHITE) ld [de], a inc de ld c, 2 * PAL_COLOR_SIZE .loop ld a, [hli] ld [de], a inc de dec c jr nz, .loop xor a ld [de], a inc de ld [de], a inc de pop af ldh [rSVBK], a pop af rst Bankswitch ret
; A050999: Sum of squares of odd divisors of n. ; 1,1,10,1,26,10,50,1,91,26,122,10,170,50,260,1,290,91,362,26,500,122,530,10,651,170,820,50,842,260,962,1,1220,290,1300,91,1370,362,1700,26,1682,500,1850,122,2366,530,2210,10,2451,651,2900,170,2810,820,3172,50,3620,842,3482,260,3722,962,4550,1,4420,1220,4490,290,5300,1300,5042,91,5330,1370,6510,362,6100,1700,6242,26,7381,1682,6890,500,7540,1850,8420,122,7922,2366,8500,530,9620,2210,9412,10,9410,2451,11102,651 lpb $0 sub $0,1 mul $0,2 dif $0,4 lpe seq $0,1157 ; sigma_2(n): sum of squares of divisors of n.
copyright zengfr site:http://github.com/zengfr/romhack 03DB00 bne $3db0a [boss+96] 03DB5E jsr $3bec.w [boss+96] copyright zengfr site:http://github.com/zengfr/romhack
; A033064: Numbers whose base-13 representation Sum_{i=0..m} d(i)*13^i has odd d(i) for all odd i. ; 1,2,3,4,5,6,7,8,9,10,11,12,14,16,18,20,22,24,27,29,31,33,35,37,40,42,44,46,48,50,53,55,57,59,61,63,66,68,70,72,74,76,79,81,83,85,87,89,92,94,96,98,100,102,105,107,109,111,113,115,118 add $0,1 mov $1,$0 mov $2,$0 sub $2,7 lpb $0,1 trn $0,6 add $2,1 lpe trn $2,8 add $1,$2
; A000779: a(n) = 2*(2n-1)!!-(n-1)!*2^(n-1), where (2n-1)!! is A001147(n). ; Submitted by Christian Krause ; 1,4,22,162,1506,16950,224190,3408930,58596930,1123663590,23782729950,550718680050,13849716607650,375904338960150,10952237584237950,340947694234397250,11294123783425733250,396665528378000631750,14723245212561422286750,575884907142609830015250,23675058259250148742241250,1020578587803882224381013750,46033181922731984892660498750,2168273951116923820957698161250,106462286039161211653049327021250,5439985984849955126759377299843750,288839727039684288340940077979718750 mov $1,3 mov $3,3 lpb $0 sub $0,1 add $2,3 mul $3,$2 sub $2,1 add $3,$1 mul $1,$2 lpe mov $0,$3 div $0,3
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r15 push %rax push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1b4c, %rsi lea addresses_WT_ht+0x896c, %rdi nop nop sub %rax, %rax mov $26, %rcx rep movsw inc %rsi lea addresses_UC_ht+0x394c, %rsi lea addresses_WT_ht+0x994c, %rdi inc %rdx mov $55, %rcx rep movsl dec %rdx lea addresses_D_ht+0xbdcc, %rbp nop nop nop nop and %r15, %r15 movb (%rbp), %dl nop nop nop nop and %rcx, %rcx lea addresses_WT_ht+0xeb4c, %rsi nop nop nop nop cmp %rdi, %rdi mov $0x6162636465666768, %rax movq %rax, (%rsi) nop nop dec %rbp lea addresses_D_ht+0xca4c, %rbp nop nop nop xor $64395, %rax movw $0x6162, (%rbp) nop nop nop nop add $42946, %rax lea addresses_D_ht+0x4ec, %rcx nop nop nop cmp %rsi, %rsi mov (%rcx), %r15 nop xor $38743, %rdx lea addresses_UC_ht+0x612c, %rdi dec %rbp movups (%rdi), %xmm4 vpextrq $0, %xmm4, %rdx nop nop nop nop add %rbp, %rbp lea addresses_WT_ht+0xf94c, %rdx nop cmp %r15, %r15 mov (%rdx), %esi nop add $37076, %rax lea addresses_WC_ht+0xef37, %rsi lea addresses_WC_ht+0x1c924, %rdi add $19936, %r14 mov $42, %rcx rep movsw nop nop sub %r14, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %rax pop %r15 pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %rbp push %rcx push %rdi push %rdx // Store lea addresses_RW+0x1f4e2, %rbp clflush (%rbp) nop nop nop sub %r10, %r10 mov $0x5152535455565758, %r15 movq %r15, %xmm0 movups %xmm0, (%rbp) nop nop cmp $1213, %rdi // Faulty Load lea addresses_US+0x1234c, %r10 and $7343, %rdx movb (%r10), %r15b lea oracles, %rdi and $0xff, %r15 shlq $12, %r15 mov (%rdi,%r15,1), %r15 pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'00': 107} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
/** * TitaniumKit MusicLibraryResponseType * * Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #include "Titanium/Media/MusicLibraryResponseType.hpp" #include "Titanium/Media/Item.hpp" #include "Titanium/detail/TiImpl.hpp" namespace Titanium { namespace Media { using namespace HAL; MusicLibraryResponseType js_to_MusicLibraryResponseType(const JSObject& object) { MusicLibraryResponseType config; const auto items_property = object.GetProperty("items"); ENSURE_OBJECT_ARRAY(items_property, items, Item); config.items = items; const auto representative_property = object.GetProperty("representative"); TITANIUM_ASSERT(representative_property.IsObject()); config.representative = static_cast<JSObject>(representative_property).GetPrivate<Item>(); config.types = Constants::to_MusicMediaType(static_cast<std::uint32_t>(object.GetProperty("types"))); return config; }; JSObject MusicLibraryResponseType_to_js(const JSContext& js_context, const MusicLibraryResponseType& config) { auto object = js_context.CreateObject(); std::vector<JSValue> items; for (const auto v : config.items) { items.push_back(v->get_object()); } object.SetProperty("items", js_context.CreateArray(items)); object.SetProperty("representative", config.representative->get_object()); object.SetProperty("types", js_context.CreateNumber(Constants::to_underlying_type(config.types))); return object; } } // namespace Media } // namespace Titanium
PLAY_PC: EQU -8 PLAY_BC: EQU -6 PLAY_DE: EQU -4 PLAY_SP: EQU -2 DURATION: EQU 0 COUNTER: EQU 1 OCTAVE: EQU 2 ENVELOPE: EQU 3 BRACKETS: EQU 4 PLAY_THREAD: EQU 5 VOLUME: EQU 6 PSG_CH: EQU 7 PLAY_START: POP BC POP DE PLAY_LOOP: PUSH DE PUSH BC CALL PLAY_SCAN POP BC POP DE CP ")" JR Z,PLAY_LOOP CP "H" JR Z,PLAY_END CALL AY_VOLUME0 INC (IX+PLAY_THREAD) PLAY_YIELD: LD HL,$0000 ADD HL,SP LD (IX+PLAY_SP),L LD (IX+PLAY_SP+1),H PLAY_SKIP_THREAD: BIT 7,(IX+PLAY_THREAD) JR NZ,PLAY_LAST DEFB $DD INC H ; IXH PLAY_THIS: LD L,(IX+PLAY_SP) LD H,(IX+PLAY_SP+1) LD SP,HL LD A,(IX+PLAY_THREAD) RRCA JR C,PLAY_SKIP_THREAD SET PLAYBIT,(IY+FLAGS2-ERR_NR) RET PLAY_LAST: LD HL,FLAGS2 BIT PLAYBIT,(HL) RES PLAYBIT,(HL) PUSH AF PUSH IX RST $30 DEFW L15E6 ; INPUT-AD POP IX JR C,PLAY_END2 POP AF PLAY_CLEAN: LD IX,(PLAY_ST) JR NZ,PLAY_THIS CALL PLAY_SILENCE LD HL,$000A ADD HL,SP LD SP,HL RST $10 PLAY_END: LD A,(IX+PSG_CH) OR A JR Z,PLAY_CLEAN DEFB $DD INC H PLAY_END2: LD SP,IX PUSH BC JR PLAY_END PLAY: XOR A EX AF,AF' DEFB $3E ; LD A,skip next byte PLAY_MORE: RST $20 ; read next byte RST $30 DEFW L1C8C ; CLASS-0A, string expression CALL SYNTAX_Z JR Z,PLAY_S LD BC,$0100 ; 256 bytes of stack space per channel RST $30 DEFW L1F05 ; TEST-ROOM RST $30 DEFW L2BF1 ; STK-FETCH EX AF,AF' LD H,A EX AF,AF' LD L,$0F ; PGS_CH=A', VOLUME=15 PUSH HL LD A,H DEC A AND $80 LD H,A LD L,$05 ; BRACKETS=4+1 PUSH HL LD L,$05 ; ENVELOPE=0, OCTAVE=5 PUSH HL LD L,$18 ; COUNTER=0, DURATION=24 PUSH HL LD HL,PLAY_PC ADD HL,SP LD (PLAY_ST),HL PUSH HL PUSH DE PUSH BC LD HL,PLAY_START PUSH HL LD HL,1+PSG_CH-PLAY_PC-$100 ADD HL,SP LD SP,HL RST $18 ; re-read separator PLAY_S: EX AF,AF' INC A JP Z,ERROR_C ; do not accept more than 255 channels EX AF,AF' CP "," JR Z,PLAY_MORE CALL CHECK_END SET PLAYBIT,(IY+FLAGS2-ERR_NR) XOR A RST $30 DEFW L1601 ; CHAN-OPEN CALL PLAY_SILENCE DEC E LD A,$38 CALL OUTAY LD SP,(PLAY_ST) LD IX,-PLAY_PC ADD IX,SP LD (PLAY_ST),IX RET PLAY_MIDIZ: CALL PLAY_NUM PUSH AF LD A,H OR H JP NZ,PLAY_ERROR LD A,L PUSH BC PUSH DE CALL MIDI_O POP DE POP BC PLAY_CONTJ: POP AF JP PLAY_CONT PLAY_MIDIY: CALL PLAY_NUM PUSH AF DEC L LD A,15 CALL PLAY_RANGE SET 7,L LD (IX+PSG_CH),L JR PLAY_CONTJ PLAY_TIE: CALL PLAY_NUM EX AF,AF' LD A,9 CALL PLAY_RANGE PUSH BC LD BC,DURATIONS ADD HL,BC POP BC LD H,(HL) LD A,(IX+DURATION) PUSH HL ; save last note's duration ADD A,H JP C,PLAY_ERROR LD (IX+DURATION),A LD A,1 PUSH AF ; save note counter EX AF,AF' CP "_" JP NZ,PLAY_TI POP HL ; discard note counter POP HL ; discard saved duration JR PLAY_TIE PLAY_TAB: DEFM "N" DEFB PLAY_SCAN - $ DEFM " " DEFB PLAY_SCAN - $ DEFM "O" DEFB PLAY_OCTAVE - $ DEFM "(" DEFB PLAY_REP - $ DEFM "H" DEFB PLAY_RET - $ DEFM ")" DEFB PLAY_RET - $ DEFM "V" DEFB PLAY_VOLUME - $ DEFM "U" DEFB PLAY_SETENV - $ DEFM "W" DEFB PLAY_ENVELOPE - $ DEFM "X" DEFB PLAY_ENVDUR - $ DEFM "T" DEFB PLAY_TEMPO - $ DEFM "_" DEFB PLAY_TIED - $ DEFM "Z" DEFB PLAY_Z - $ DEFM "Y" DEFB PLAY_Y - $ DEFM "M" DEFB PLAY_MIXER - $ DEFM "!" DEFB PLAY_COMMENT - $ PLAY_TTAB: DEFM "#" DEFB PLAY_SHARP - $ DEFM "&" DEFB PLAY_REST - $ DEFM "$" DEFB PLAY_FLAT - $ DEFB 0 PLAY_Z: JR PLAY_MIDIZ PLAY_Y: JR PLAY_MIDIY PLAY_TIED: JR PLAY_TIE PLAY_MIXER: CALL PLAY_NUM EX AF,AF' PUSH DE LD E,7 LD A,L CPL PUSH BC JR PLAY_AY PLAY_ENVDUR: CALL NO_MIDI CALL PLAY_NUM EX AF,AF' PUSH DE LD E,11 LD A,L PUSH BC CALL OUTAY INC E LD A,H PLAY_AY:CALL OUTAY POP BC POP DE JR PLAY_CONT_EX2 PLAY_ENVELOPE: CALL NO_MIDI CALL PLAY_NUM EX AF,AF' LD A,7 CALL PLAY_RANGE PUSH DE LD DE,ENVELOPES ADD HL,DE POP DE LD A,(HL) LD (IX+ENVELOPE),A PLAY_CONT_EX2: JR PLAY_CONT_EX PLAY_SETENV: CALL NO_MIDI CALL PLAY_NEXT RET Z EX AF,AF' LD L,$1F JR PLAY_SETVOL PLAY_COMMENT: CALL PLAY_NEXT PLAY_RET: RET Z CP "!" JR Z,PLAY_SCAN JR PLAY_COMMENT PLAY_REP: DEC (IX+BRACKETS) JP Z,PLAY_ERROR PUSH DE PUSH BC CALL PLAY_SCAN POP BC POP DE CALL PLAY_SCAN INC (IX+BRACKETS) JR PLAY_SCAN PLAY_OCTAVE: CALL PLAY_NUM EX AF,AF' LD A,8 CALL PLAY_RANGE LD (IX+OCTAVE),L JR PLAY_CONT_EX PLAY_TEMPO: CALL PLAY_NUM EX AF,AF' LD A,240 CALL PLAY_RANGE LD A,59 CP L JR NC,PLAY_ERROR_NC LD A,L LD (TEMPO),A JR PLAY_CONT_EX PLAY_TRIPLET: PUSH HL LD A,3 PLAY_TL:PUSH AF CALL PLAY_STEP PLAY_TI:SET 6,(IX+PLAY_THREAD) CALL NOTE JR C,PLAY_NOTE LD HL,PLAY_TTAB JR PLAY_INDEX PLAY_VOLUME: CALL PLAY_NUM EX AF,AF' LD A,15 CALL PLAY_RANGE PLAY_SETVOL: LD (IX+VOLUME),L PLAY_CONT_EX: EX AF,AF' JR PLAY_CONT NOTE_LENGTH: CALL PLAY_NUMERIC RET Z DEC DE INC BC PUSH BC CALL PLAY_RANGE12 LD BC,DURATIONS LD A,L ADD HL,BC CP 10 LD A,(HL) LD H,(IX+DURATION) LD (IX+DURATION),A POP BC JR NC,PLAY_TRIPLET PLAY_SCAN: CALL PLAY_NEXT PLAY_CONT: RET Z CALL NOTE JR C,PLAY_NOTE RST $30 DEFW L2D1B ; NUMERIC JR NC,NOTE_LENGTH LD HL,PLAY_TAB PLAY_INDEX: PUSH BC LD C,A CALL INDEXER JR NC,PLAY_ERROR_NC INDEXER_JP: LD C,(HL) LD B,$00 ADD HL,BC POP BC JP (HL) PLAY_REST: PUSH BC PUSH DE JP PLAY_DURATION PLAY_SHARP: CALL PLAY_STEP CALL NOTE JR NC,PLAY_ERROR_NC INC A JR PLAY_NOTE PLAY_FLAT: CALL PLAY_STEP CALL NOTE PLAY_ERROR_NC: JP NC,PLAY_ERROR DEC A PLAY_NOTE: INC A PLAY_FNOTE: PUSH BC PUSH DE EX AF,AF' LD A,(IX+PSG_CH) CP 3 JR NC,PLAY_OTHER EX AF,AF' ADD A,A CP $18 JR C,PLAY_LOW SUB A,$18 PLAY_LOW: LD C,A LD A,(IX+OCTAVE) SBC A,$FF LD B,0 LD HL,NOTES ADD HL,BC LD E,(HL) INC HL LD D,(HL) OR A LD B,A LD A,C RRCA JR Z,NOTE_DONE ; octave 0 ADD A,12 DEC B JR Z,NOTE_DONE ; octave 1 NOTE_L: ADD A,12 PLAY_TOO_LOW: SRL D RR E DJNZ NOTE_L JR NC,NOTE_DONE INC DE NOTE_DONE: INC B ; ignore DJNZ if too low BIT 4,D JR NZ,PLAY_TOO_LOW DEC A EX AF,AF' LD A,E LD E,(IX+PSG_CH) SLA E CALL OUTAY INC E LD A,D CALL OUTAY LD D,(IX+VOLUME) CALL AY_VOLUME LD A,(IX+ENVELOPE) LD E,13 OR A CALL NZ,OUTAY LD B,$FF LD A,7 OUT (C),A IN A,(C) RRCA RRCA RRCA LD B,(IX+PSG_CH) INC B PLAY_NOISE: RRCA DJNZ PLAY_NOISE JR C,PLAY_DURATION EX AF,AF' CPL AND $7C RRCA RRCA LD E,6 CALL OUTAY PLAY_DURATION: XOR A PLAY_OTHER: ADD A,A CALL C,PLAY_MIDI LD DE,125 ; change this to 150 for 60Hz machines LD L,(IX+DURATION) LD H,D RST $30 DEFW L30A9 ; HLxDE LD E,(IX+COUNTER) AND A SBC HL,DE PLAY_HOLD: PUSH HL LD BC,(FRAMES) PLAY_HALT: PUSH BC CALL PLAY_YIELD POP BC LD HL,(FRAMES) AND A SBC HL,BC JR Z,PLAY_HALT LD A,(TEMPO) LD E,A LD D,0 RST $30 DEFW L30A9 ; HLxDE EX DE,HL AND A POP HL SBC HL,DE JR Z,PLAY_DONE JR NC,PLAY_HOLD PLAY_DONE: CALL AY_VOLUME0 POP DE LD A,L NEG LD (IX+COUNTER),A BIT 6,(IX+PLAY_THREAD) RES 6,(IX+PLAY_THREAD) POP BC JR Z,PLAY_SCAN2 POP AF DEC A JP NZ,PLAY_TL POP HL LD (IX+DURATION),H PLAY_SCAN2: JP PLAY_SCAN PLAY_STEP: CALL PLAY_NEXT RET NZ PLAY_ERROR: CALL PLAY_SILENCE RST $30 DEFW L34E7 ; A Invalid argument PLAY_NEXT: LD A,B OR C RET Z LD A,(DE) INC DE DEC BC RET PLAY_NUM: CALL PLAY_STEP RST $30 DEFW L2D1B ; NUMERIC JR C,PLAY_ERROR PLAY_NUMERIC: SUB A,"0" LD L,A LD H,0 PLAYNL: CALL PLAY_NEXT RET Z ; end-of-string RST $30 DEFW L2D1B ; NUMERIC RET C SUB A,"0" PUSH BC LD C,L LD B,H ADD HL,HL ; HL * 2 ADD HL,HL ; HL * 4 ADD HL,BC ; HL * 5 note 9999*5=49995<65536 POP BC ADD HL,HL ; HL * 10 JR C,PLAY_ERROR ADD A,L LD L,A JR NC,PLAYNL INC H JR NZ,PLAYNL JR PLAY_ERROR PLAY_RANGE12: LD A,12 PLAY_RANGE: CP L JR C,PLAY_ERROR DEC H INC H RET Z JR PLAY_ERROR NO_MIDI:BIT 7,(IX+PSG_CH) RET Z JR PLAY_ERROR ENVELOPES: DEFB $09, $0F, $0B, $0D, $08, $0C, $0E, $0A DURATIONS: ; multiply by 125 for BPM with 50Hz frame counter ; 150 for BPM with 60Hz frame counter DEFB 3, 6, 9, 12, 18, 24, 36, 48, 72, 96, 4, 8, 16 NOTES: DEFW $1C0E ; Cb0 15.43 Hz DEFW $1A7B ; C0 16.35 Hz DEFW $18FE ; C#0 17.32 Hz DEFW $1797 ; D0 18.35 Hz DEFW $1644 ; D#0 19.45 Hz DEFW $1504 ; E0 20.60 Hz DEFW $13D6 ; F0 21.83 Hz DEFW $12B9 ; F#0 23.12 Hz DEFW $11AC ; G0 24.50 Hz DEFW $10AE ; G#0 25.96 Hz DEFW $0FBF ; A0 27.50 Hz DEFW $0EDC ; A#0 29.14 Hz DEFW $0E07 ; B0 30.87 Hz DEFW $0D3D ; C1 32.70 Hz NOTE: RST $30 DEFW L2C8D ; ALPHA RET NC CP "h" RET NC BIT 5,A JR NZ,NOTE1 CP "H" RET NC OR $20 CALL NOTE1 SUB A,-12 ; sets CF RET NOTE1: SUB A,"c" JR NC,NOTE2 ADD A,7 NOTE2: ADD A,A CP 5 ADC A,$FF ; sets CF RET PLAY_SILENCE: LD E,10 XOR A CALL OUTAY DEC E CALL OUTAY DEC E JR OUTAY AY_VOLUME0: LD D,0 AY_VOLUME: LD A,(IX+PSG_CH) CP 3 JR NC,MIDI_VOLUME ADD 8 LD E,A LD A,D OUTAY: LD BC,$FFFD OUT (C),E LD B,$BF OUT (C),A RET MIDI_VOLUME: RLCA RET NC RRCA CALL MIDI_O LD A,(IX+ENVELOPE) CALL MIDI_O LD A,$40 JR MIDI_J PLAY_MIDI: EX AF,AF' PUSH AF ; save note EX AF,AF' RRA OR $90 CALL MIDI_O LD A,(IX+OCTAVE) LD C,A ADD A,A ADD A,C ADD A,A ADD A,A ; octave * 12 POP BC ; restore note ADD A,B ; octave * 12 + note DEC A LD (IX+ENVELOPE),A CALL MIDI_O LD A,(IX+VOLUME) ADD A,A ADD A,A ADD A,A MIDI_J: JP MIDI_O
; ; IOCLA, Buffer management ; ; Fill buffer with data and print it. ; Buffer is stored in .data section (initialized data). ; extern printf extern puts section .data buffer: times 64 db 5 len: equ $-buffer buffer_intro_message: db "buffer is:", 0 byte_format: db " %02X", 0 null_string: db 0 section .text global main main: push ebp mov ebp, esp ; Fill data in buffer: buffer[i] = i+1 ; ecx is buffer index (i), dl is buffer value (i+1). dl needs to be ecx+1. ; Buffer length is 64 bytes. xor ecx, ecx fill_byte: mov dl, cl inc dl mov byte [buffer+ecx], dl inc ecx cmp ecx, len jl fill_byte ; Print data in buffer. push buffer_intro_message call printf add esp, 4 xor ecx, ecx print_byte: xor eax, eax mov al, byte[buffer+ecx] push ecx ; save ecx ; Print current byte. push eax push byte_format call printf add esp, 8 pop ecx ; restore ecx inc ecx cmp ecx, len jl print_byte ; Print new line. C equivalent instruction is puts(""). push null_string call puts add esp, 4 leave ret
TITLE Standard MSDOS NAME MSDOS_2 ; Number of disk I/O buffers INCLUDE STDSW.ASM INCLUDE MSHEAD.ASM INCLUDE MSDATA.ASM END 
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r15 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x192c5, %r15 nop nop nop nop nop xor $17791, %rbp mov (%r15), %ebx nop xor $4219, %r9 lea addresses_WT_ht+0x4d9b, %r13 nop nop nop xor $55220, %r12 vmovups (%r13), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $1, %xmm5, %rsi nop nop nop nop cmp $51661, %r9 lea addresses_UC_ht+0x3805, %rbx nop nop nop nop nop add $1762, %r9 and $0xffffffffffffffc0, %rbx movaps (%rbx), %xmm7 vpextrq $1, %xmm7, %rbp nop nop nop sub $31630, %rbx lea addresses_WT_ht+0x9405, %rbx nop nop nop cmp %r9, %r9 movb $0x61, (%rbx) nop nop cmp %r13, %r13 lea addresses_WT_ht+0xc805, %rsi lea addresses_A_ht+0xf085, %rdi nop xor $52069, %rbx mov $96, %rcx rep movsb nop nop nop nop and $53540, %rcx lea addresses_A_ht+0x3005, %rsi lea addresses_WC_ht+0x19a01, %rdi nop nop nop nop xor %rbp, %rbp mov $96, %rcx rep movsl nop sub %rbx, %rbx lea addresses_A_ht+0x12005, %rcx nop nop nop xor $45724, %rsi mov (%rcx), %r13w nop nop nop and %r12, %r12 lea addresses_A_ht+0x6099, %rsi lea addresses_UC_ht+0x69ed, %rdi nop nop nop nop nop sub %rbx, %rbx mov $32, %rcx rep movsb dec %r9 lea addresses_UC_ht+0x1a3a0, %rbp nop add $51393, %r12 and $0xffffffffffffffc0, %rbp movntdqa (%rbp), %xmm6 vpextrq $0, %xmm6, %r13 nop nop dec %r9 lea addresses_D_ht+0x18d78, %rdi nop nop nop nop nop add $2164, %r9 mov (%rdi), %r13 nop nop nop and %r15, %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r15 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r14 push %r8 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi // Store lea addresses_A+0x9305, %r14 nop nop nop nop cmp $41770, %rbp movw $0x5152, (%r14) sub %r8, %r8 // REPMOV lea addresses_UC+0xf235, %rsi lea addresses_D+0x1dc5, %rdi nop nop nop inc %rbx mov $84, %rcx rep movsq nop xor %rcx, %rcx // REPMOV lea addresses_WC+0x19005, %rsi lea addresses_normal+0x2805, %rdi clflush (%rsi) nop nop and %rbx, %rbx mov $126, %rcx rep movsb nop nop nop sub $13278, %rcx // Store lea addresses_UC+0xc635, %rsi nop nop nop add %rcx, %rcx mov $0x5152535455565758, %r8 movq %r8, (%rsi) nop nop nop nop and $45143, %r8 // Store lea addresses_normal+0xe805, %rsi nop nop nop xor $53287, %r9 mov $0x5152535455565758, %rdi movq %rdi, %xmm3 movups %xmm3, (%rsi) nop nop nop and %rbp, %rbp // Store lea addresses_normal+0x2805, %rcx nop nop nop add %r8, %r8 movl $0x51525354, (%rcx) nop xor %rsi, %rsi // Load lea addresses_WT+0x1cb05, %rdi nop nop dec %rcx mov (%rdi), %r9w nop nop nop nop and $19517, %r14 // Store lea addresses_A+0x5d45, %r9 clflush (%r9) nop nop nop nop and %rsi, %rsi movw $0x5152, (%r9) nop nop nop nop nop xor %rdi, %rdi // Load lea addresses_D+0xe205, %rdi nop nop nop cmp $47379, %r14 vmovups (%rdi), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $1, %xmm5, %r9 nop nop nop sub %r9, %r9 // Faulty Load lea addresses_normal+0x2805, %rbx nop nop nop xor %r14, %r14 mov (%rbx), %rdi lea oracles, %rbp and $0xff, %rdi shlq $12, %rdi mov (%rbp,%rdi,1), %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r8 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_D', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_normal', 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': True, 'NT': True, 'congruent': 11, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'54': 163} 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 */
NewElderCode: { LDA $8A : CMP #$1B : BEQ .newCodeContinue ;Restore Jump we can keep the RTL so JML JML $05F0CD .newCodeContinue PHB : PHK : PLB LDA.b #$07 : STA $0F50, X ;Palette JSR Elder_Draw JSL Sprite_PlayerCantPassThrough JSR Elder_Code PLB RTL Elder_Draw: { LDA.b #$02 : STA $06 : STZ $07 ;Number of Tiles LDA $0DC0, X : ASL #04 ADC.b #.animation_states : STA $08 LDA.b #.animation_states>>8 : ADC.b #$00 : STA $09 JSL Sprite_DrawMultiple_player_deferred JSL Sprite_DrawShadowLong RTS .animation_states ;Frame0 dw 0, -9 : db $C6, $00, $00, $02 dw 0, 0 : db $C8, $00, $00, $02 ;Frame1 dw 0, -8 : db $C6, $00, $00, $02 dw 0, 0 : db $CA, $40, $00, $02 } Elder_Code: { LDA GoalItemRequirement : ORA GoalItemRequirement+1 : BEQ .despawn LDA InvincibleGanon : CMP #$05 : BEQ .despawn LDA TurnInGoalItems : BNE + .despawn STZ $0DD0, X ; despawn self RTS + LDA.b #$96 LDY.b #$01 JSL Sprite_ShowSolicitedMessageIfPlayerFacing_PreserveMessage : BCC .dont_show REP #$20 LDA.l !GOAL_COUNTER CMP.l GoalItemRequirement : !BLT + SEP #$20 JSL.l ActivateGoal + SEP #$20 .dont_show .done LDA $1A : LSR #5 : AND.b #$01 : STA $0DC0, X RTS }
; A106231: Least j > 1 such that j^2 = (4*n^2 + 2)*(k^2) + (4*n^2 + 2)*k + 1. ; 11,19,77,199,409,731,1189,1807,2609,3619,4861,6359,8137,10219,12629,15391,18529,22067,26029,30439,35321,40699,46597,53039,60049,67651,75869,84727,94249,104459,115381,127039,139457,152659,166669,181511,197209,213787 pow $1,$0 mul $1,10 add $1,1 mov $2,$0 mul $2,6 add $1,$2 mov $3,$0 mul $3,$0 mov $2,$3 mul $2,8 add $1,$2 mul $3,$0 mov $2,$3 mul $2,4 add $1,$2
blit_save: ldx #$00 !: .for(var i=0; i<4; i++){ lda [$0400 + (i * $100)] ,x sta [blit_buf + (i * $100)] ,x lda [$d800 + (i * $100)] ,x sta [blit_buf + $0400 + (i * $100)] ,x } inx bne !- rts blit_load: ldx #$00 !: .for(var i=0; i<4; i++){ lda [blit_buf + (i * $100)] ,x sta [$0400 + (i * $100)] ,x lda [blit_buf + $0400 + (i * $100)] ,x sta [$d800 + (i * $100)] ,x } inx bne !- rts blit_buf: .fill $800, $00
HallofFameRoom_h: db GYM ; tileset db HALL_OF_FAME_HEIGHT, HALL_OF_FAME_WIDTH ; dimensions (y, x) dw HallofFameRoomBlocks, HallofFameRoomTextPointers, HallofFameRoomScript ; blocks, texts, scripts db $00 ; connections dw HallofFameRoomObject ; objects
; A250141: Number of length 2+2 0..n arrays with the medians of every three consecutive terms nondecreasing. ; 14,67,204,485,986,1799,3032,4809,7270,10571,14884,20397,27314,35855,46256,58769,73662,91219,111740,135541,162954,194327,230024,270425,315926,366939,423892,487229,557410,634911,720224,813857,916334,1028195,1149996,1282309,1425722,1580839,1748280,1928681,2122694,2330987,2554244,2793165,3048466,3320879,3611152,3920049,4248350,4596851,4966364,5357717,5771754,6209335,6671336,7158649,7672182,8212859,8781620,9379421,10007234,10666047,11356864,12080705,12838606,13631619,14460812,15327269,16232090,17176391,18161304,19187977,20257574,21371275,22530276,23735789,24989042,26291279,27643760,29047761,30504574,32015507,33581884,35205045,36886346,38627159,40428872,42292889,44220630,46213531,48273044,50400637,52597794,54866015,57206816,59621729,62112302,64680099,67326700,70053701 mov $1,1 add $1,$0 mov $2,$0 mov $0,$1 add $0,1 mov $3,$2 add $3,3 mov $4,$1 mul $4,2 mov $2,$4 mov $5,$0 add $0,1 mul $5,$3 mul $5,2 mul $2,$5 add $2,6 mul $0,$2 sub $0,90 div $0,6 add $0,14
bits 64 section .rodata GPFString: db "General Protection Fault occured", 0xA, 0 SegmentGPF: db "it is a segment error, segment selector index: ", 0 section .data SegmentIndexString: resb 32 section .text extern divByZErr ;INT 0x0 extern dbg ;INT 0x1 extern NMI ;INT 0x2 extern bkpt ;INT 0x3 extern overflow ;INT 0x4 extern boundRangeExceeded ;INT 0x5 extern invalidOPCode ;INT 0x6 extern deviceNotAvailable ;INT 0x7 extern doubleFault ;INT 0x8 extern invalidTSS ;INT 0xa extern segmentNotPresent ;INT 0xb extern stackSegmentFault ;INT 0xc extern gpf ;INT 0xd extern pageFault ;INT 0xe extern x87FloatingPoint ;INT 0x10 extern alignmentCheck ;INT 0x11 extern machineCheck ;INT 0x12 extern SIMDFloatingPoint ;INT 0x13 extern virtualizationException ;INT 0x14 extern controlProtection ;INT 0x15 extern hypervisorInjection ;INT 0x1c extern VMMCommunication ;INT 0x1d extern securityException ;INT 0x1e extern kbIRQ ;INT 0x20 extern divByZErr_asm ;INT 0x0 extern dbg_asm ;INT 0x1 extern NMI_asm ;INT 0x2 extern bkpt_asm ;INT 0x3 extern overflow_asm ;INT 0x4 extern boundRangeExceeded_asm ;INT 0x5 extern invalidOPCode_asm ;INT 0x6 extern deviceNotAvailable_asm ;INT 0x7 extern doubleFault_asm ;INT 0x8 extern invalidTSS_asm ;INT 0xa extern segmentNotPresent_asm ;INT 0xb extern stackSegmentFault_asm ;INT 0xc extern GeneralProtectionFault_asm ;INT 0xd extern pageFault_asm ;INT 0xe extern x87FloatingPoint_asm ;INT 0x10 extern alignmentCheck_asm ;INT 0x11 extern machineCheck_asm ;INT 0x12 extern SIMDFloatingPoint_asm ;INT 0x13 extern virtualizationException_asm ;INT 0x14 extern controlProtection_asm ;INT 0x15 extern hypervisorInjection_asm ;INT 0x1c extern VMMCommunication_asm ;INT 0x1d extern securityException_asm ;INT 0x1e extern kbIRQ_asm ;INT 0x20 divByZErr_asm: mov rdi, [rsp] call divByZErr iretq dbg_asm: call dbg iretq NMI_asm: call NMI iretq bkpt_asm: call bkpt iretq overflow_asm: call overflow iretq boundRangeExceeded_asm: mov rdi, [rsp] call boundRangeExceeded_asm iretq invalidOPCode_asm: mov rdi, [rsp] call invalidOPCode iretq deviceNotAvailable_asm: mov rdi, [rsp] call deviceNotAvailable iretq doubleFault_asm: call doubleFault hlt invalidTSS_asm: pop rsi mov rdi, [rsp] call invalidTSS iretq segmentNotPresent_asm: pop rsi mov rdi, [rsp] call segmentNotPresent iretq stackSegmentFault_asm: pop rsi mov rdi, [rsp] call stackSegmentFault iretq GeneralProtectionFault_asm: pop rsi mov rdi, [rsp] call gpf iretq pageFault_asm: mov rdx, cr2 pop rsi mov rdi, [rsp] call pageFault iretq x87FloatingPoint_asm: mov rdi, [rsp] call x87FloatingPoint iretq alignmentCheck_asm: mov rdi, [rsp] call alignmentCheck iretq machineCheck_asm: mov rdi, [rsp] call machineCheck iretq SIMDFloatingPoint_asm: mov rdi, [rsp] call SIMDFloatingPoint iretq virtualizationException_asm: mov rdi, [rsp] call virtualizationException iretq controlProtection_asm: mov rdi, [rsp] call controlProtection iretq hypervisorInjection_asm: mov rdi, [rsp] call hypervisorInjection iretq VMMCommunication_asm: mov rdi, [rsp] call VMMCommunication iretq securityException_asm: mov rdi, [rsp] call securityException iretq kbIRQ_asm: push rax call kbIRQ mov al, 0x20 out 0x20, al pop rax iretq
; A036453: a(n) = d(d(d(d(d(n))))), the 5th iterate of the number-of-divisors function with initial value n. ; 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 pow $1,$0 gcd $1,2 mov $0,$1
//Author:LanceYu #include<cstring> #include<cmath> #include<cstdio> #include<cctype> #include<cstdlib> #include<ctime> #include<vector> #include<iostream> #include<string> #include<queue> #include<set> #include<algorithm> #include<complex> #include<stack> #include<bitset> #include<iomanip> #define ll long long using namespace std; const double clf=1e-8; const int MMAX=0x7fffffff; const int INF=0xfffffff; const int mod=1e9+7; int t,num=0,a[10001]; void dfs(int sum,int n,int k) { if(sum==k) { num++; return; } for(int i=0;i<n;i++) { if(sum+a[i]<=k) dfs(sum+a[i],n,k); } } int main() { ios::sync_with_stdio(false); //freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin); //freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout); string s; cin>>s; int i=0,n; for(int i=0;i<s.length();i++) if(s[i]==',') s[i]=' '; istringstream ss(s); while(ss>>a[i++]); n=--i; cin>>t; num=0; dfs(0,n,t); cout<<num<<endl; return 0; }
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "AirLoopHVAC.hpp" #include "AirLoopHVACZoneSplitter.hpp" #include "AirLoopHVACZoneSplitter_Impl.hpp" #include "HVACComponent.hpp" #include "HVACComponent_Impl.hpp" #include "Node.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp" #include "AirTerminalSingleDuctUncontrolled.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include <utilities/idd/OS_AirLoopHVAC_ZoneSplitter_FieldEnums.hxx> #include "../utilities/core/Compare.hpp" #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail{ AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle): Splitter_Impl(idfObject,model, keepHandle) { OS_ASSERT(idfObject.iddObject().type() == AirLoopHVACZoneSplitter::iddObjectType()); } AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl( const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : Splitter_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == AirLoopHVACZoneSplitter::iddObjectType()); } AirLoopHVACZoneSplitter_Impl::AirLoopHVACZoneSplitter_Impl( const AirLoopHVACZoneSplitter_Impl& other, Model_Impl* model, bool keepHandle) : Splitter_Impl(other,model,keepHandle) { } AirLoopHVACZoneSplitter_Impl::~AirLoopHVACZoneSplitter_Impl() { } const std::vector<std::string>& AirLoopHVACZoneSplitter_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType AirLoopHVACZoneSplitter_Impl::iddObjectType() const { return AirLoopHVACZoneSplitter::iddObjectType(); } std::vector<openstudio::IdfObject> AirLoopHVACZoneSplitter_Impl::remove() { if( this->airLoopHVAC() ) { return std::vector<openstudio::IdfObject>(); } else { OptionalAirLoopHVACZoneSplitter self = model().getModelObject<AirLoopHVACZoneSplitter>(handle()); model().disconnect(*self,inletPort()); for( int i = 0; i < int(nextBranchIndex()) - 1; i++ ) { model().disconnect(*self,outletPort(i)); } return HVACComponent_Impl::remove(); } } void AirLoopHVACZoneSplitter_Impl::disconnect() { ModelObject mo = this->getObject<ModelObject>(); model().disconnect(mo,inletPort()); for( int i = 0; i < int(nextBranchIndex()); i++ ) { model().disconnect(mo,outletPort(i)); } } unsigned AirLoopHVACZoneSplitter_Impl::inletPort() { return OS_AirLoopHVAC_ZoneSplitterFields::InletNodeName; } unsigned AirLoopHVACZoneSplitter_Impl::outletPort(unsigned branchIndex) { unsigned result; result = numNonextensibleFields(); result = result + branchIndex; return result; } unsigned AirLoopHVACZoneSplitter_Impl::nextOutletPort() { return outletPort( this->nextBranchIndex() ); } std::vector<ThermalZone> AirLoopHVACZoneSplitter_Impl::thermalZones() { std::vector<ThermalZone> zones; std::vector<ModelObject> modelObjects; //std::vector<ModelObject> _outletModelObjects = outletModelObjects(); OptionalAirLoopHVAC _airLoopHVAC = airLoopHVAC(); OptionalNode demandOutletNode; OptionalNode demandInletNode; if( _airLoopHVAC ) { demandOutletNode = _airLoopHVAC->demandOutletNode(); demandInletNode = _airLoopHVAC->demandInletNode(); } else { return zones; } modelObjects = _airLoopHVAC->demandComponents( demandInletNode.get(), demandOutletNode.get(), ThermalZone::iddObjectType() ); for( const auto & modelObject : modelObjects ) { OptionalThermalZone zone; zone = modelObject.optionalCast<ThermalZone>(); if( zone ) { zones.push_back(*zone); } } return zones; } } // detail AirLoopHVACZoneSplitter::AirLoopHVACZoneSplitter(const Model& model) : Splitter(AirLoopHVACZoneSplitter::iddObjectType(),model) { OS_ASSERT(getImpl<detail::AirLoopHVACZoneSplitter_Impl>()); } AirLoopHVACZoneSplitter::AirLoopHVACZoneSplitter(std::shared_ptr<detail::AirLoopHVACZoneSplitter_Impl> p) : Splitter(p) {} std::vector<openstudio::IdfObject> AirLoopHVACZoneSplitter::remove() { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->remove(); } unsigned AirLoopHVACZoneSplitter::inletPort() { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->inletPort(); } unsigned AirLoopHVACZoneSplitter::outletPort(unsigned branchIndex) { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->outletPort(branchIndex); } unsigned AirLoopHVACZoneSplitter::nextOutletPort() { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->nextOutletPort(); } IddObjectType AirLoopHVACZoneSplitter::iddObjectType() { IddObjectType result(IddObjectType::OS_AirLoopHVAC_ZoneSplitter); return result; } std::vector<ThermalZone> AirLoopHVACZoneSplitter::thermalZones() { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->thermalZones(); } void AirLoopHVACZoneSplitter::disconnect() { return getImpl<detail::AirLoopHVACZoneSplitter_Impl>()->disconnect(); } } // model } // openstudio
/*! @file Activate.cpp * @version 3.1.8 * @date Aug 05 2016 * * @brief * Activation process for the STM32 example App. * * Copyright 2016 DJI. All right reserved. * * */ #include "Activate.h" extern Vehicle vehicle; extern Vehicle* v; void userActivate() { //! At your DJI developer account look for: app_key and app ID static char key_buf[65] = "your app_key here"; DJI::OSDK::Vehicle::ActivateData user_act_data; user_act_data.ID = 0000; /*your app ID here*/ user_act_data.encKey = key_buf; v->activate(&user_act_data); }
INCLUDE "graphics/grafix.inc" XLIB w_pointxy ;LIB l_cmp LIB w_pixeladdress XREF COORDS ; ; $Id: w_pointxy.asm,v 1.1 2008/07/17 15:39:56 stefano Exp $ ; ; ****************************************************************** ; ; Get pixel at (x,y) coordinate. ; ; Wide resolution (WORD based parameters) version by Stefano Bodrato ; ; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995 ; ; The (0,0) origin is placed at the top left corner. ; ; in: hl,de = (x,y) coordinate of pixel to test ; ; registers changed after return: ; ......../ixiy same ; afbcdehl/.... different ; .w_pointxy ;push hl ;ld hl,maxy ;call l_cmp ;pop hl ;ret nc ; Return if Y overflows ;push de ;ld de,maxx ;call l_cmp ;pop de ;ret c ; Return if X overflows call w_pixeladdress ld b,a ld a,1 jr z, test_pixel ; pixel is at bit 0... .pix_position rlca djnz pix_position .test_pixel ex af,af ld d,18 ld bc,0d600h out (c),d loop1: in a,(c) rla jp nc,loop1 inc c out (c),h dec c inc d out (c),d loop2: in a,(c) rla jp nc,loop2 inc c out (c),l dec c ld a,31 out (c),a loop3: in a,(c) rla jp nc,loop3 inc c ex af,af in e,(c) and e ret
; A023554: Convolution of natural numbers >= 3 and (Fib(2), Fib(3), Fib(4), ...). ; 3,10,22,43,78,136,231,386,638,1047,1710,2784,4523,7338,11894,19267,31198,50504,81743,132290,214078,346415,560542,907008,1467603,2374666,3842326,6217051,10059438,16276552,26336055,42612674,68948798,111561543,180510414,292072032,472582523,764654634,1237237238,2001891955,3239129278,5241021320,8480150687,13721172098,22201322878,35922495071,58123818046,94046313216,152170131363,246216444682,398386576150,644603020939,1042989597198,1687592618248,2730582215559,4418174833922,7148757049598,11566931883639 add $0,4 mov $1,38 sub $1,$0 seq $0,22308 ; a(n) = a(n-1) + a(n-2) + 1 for n>1, a(0)=0, a(1)=3. mul $1,2 sub $1,4 add $1,$0 sub $1,74 mov $0,$1
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <iterator> #include <vector> #include "vast/concept/printable/core/printer.hpp" #include "vast/concept/support/detail/attr_fold.hpp" namespace vast { template <class Lhs, class Rhs> class list_printer : public printer<list_printer<Lhs, Rhs>> { public: using lhs_attribute = typename Lhs::attribute; using rhs_attribute = typename Rhs::attribute; using attribute = detail::attr_fold_t<std::vector<lhs_attribute>>; list_printer(Lhs lhs, Rhs rhs) : lhs_{std::move(lhs)}, rhs_{std::move(rhs)} { // nop } template <class Iterator, class Attribute> bool print(Iterator& out, const Attribute& a) const { using std::begin; using std::end; auto f = begin(a); auto l = end(a); if (f == l || !lhs_.print(out, *f)) return false; for (++f; f != l; ++f) if (!(rhs_.print(out, unused) && lhs_.print(out, *f))) return false; return true; } private: Lhs lhs_; Rhs rhs_; }; } // namespace vast
; A173009: Expansion of o.g.f. x*(1 - x + x^2)/(1 -3*x +x^2 +3*x^3 -2*x^4). ; 0,1,2,6,13,29,60,124,251,507,1018,2042,4089,8185,16376,32760,65527,131063,262134,524278,1048565,2097141,4194292,8388596,16777203,33554419,67108850,134217714,268435441,536870897,1073741808,2147483632,4294967279,8589934575,17179869166,34359738350,68719476717,137438953453,274877906924,549755813868,1099511627755,2199023255531,4398046511082,8796093022186,17592186044393,35184372088809,70368744177640,140737488355304,281474976710631,562949953421287,1125899906842598,2251799813685222,4503599627370469 mov $1,2 pow $1,$0 div $0,2 sub $1,$0 sub $1,1 mov $0,$1
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: w_uncircle.asm,v 1.2 2015/01/19 01:32:46 pauloscustodio Exp $ ; ;Usage: uncircle(struct *pixels) PUBLIC uncircle EXTERN w_draw_circle EXTERN w_respixel EXTERN swapgfxbk EXTERN swapgfxbk1 .uncircle ld ix,0 add ix,sp ; de = x0, hl = y0, bc = radius, a = scale factor ld a,(ix+2) ;skip ld c,(ix+4) ;radius ld b,(ix+5) ld l,(ix+6) ;y ld h,(ix+7) ld e,(ix+8) ;x ld d,(ix+9) ld ix,w_respixel call swapgfxbk call w_draw_circle jp swapgfxbk1
; A234465: a(n) = 3*binomial(8*n+6,n)/(4*n+3). ; Submitted by Jon Maiga ; 1,6,63,812,11655,178794,2869685,47593176,809172936,14028048650,247039158366,4406956913268,79470057050020,1446283758823470,26529603944225670,489989612605050800,9104498753815680600,170073237411754811568,3192081704235788729043,60166773533065177878900,1138419505082727895859370,21614969001915589014756756,411697677405509050522402215,7864225677011344098638292840,150620489399205850112992667400,2891822984303689816452836284248,55646560948841138094112748602008,1073030817362866983929542150089404 mov $2,$0 mul $2,7 add $2,5 add $0,$2 bin $0,$2 mul $0,12 mov $1,$2 add $1,1 div $0,$1 div $0,2
; A265381: Decimal representation of the middle column of the "Rule 158" elementary cellular automaton starting with a single ON (black) cell. ; 1,3,7,14,29,59,119,238,477,955,1911,3822,7645,15291,30583,61166,122333,244667,489335,978670,1957341,3914683,7829367,15658734,31317469,62634939,125269879,250539758,501079517,1002159035,2004318071,4008636142,8017272285,16034544571,32069089143,64138178286,128276356573,256552713147,513105426295,1026210852590,2052421705181,4104843410363,8209686820727,16419373641454,32838747282909,65677494565819,131354989131639,262709978263278,525419956526557,1050839913053115,2101679826106231,4203359652212462,8406719304424925,16813438608849851,33626877217699703,67253754435399406,134507508870798813,269015017741597627,538030035483195255,1076060070966390510,2152120141932781021,4304240283865562043,8608480567731124087,17216961135462248174,34433922270924496349,68867844541848992699,137735689083697985399,275471378167395970798,550942756334791941597,1101885512669583883195,2203771025339167766391,4407542050678335532782,8815084101356671065565,17630168202713342131131,35260336405426684262263,70520672810853368524526,141041345621706737049053,282082691243413474098107,564165382486826948196215,1128330764973653896392430,2256661529947307792784861,4513323059894615585569723,9026646119789231171139447,18053292239578462342278894,36106584479156924684557789,72213168958313849369115579,144426337916627698738231159,288852675833255397476462318,577705351666510794952924637,1155410703333021589905849275,2310821406666043179811698551,4621642813332086359623397102,9243285626664172719246794205,18486571253328345438493588411,36973142506656690876987176823,73946285013313381753974353646,147892570026626763507948707293,295785140053253527015897414587,591570280106507054031794829175,1183140560213014108063589658350 mov $1,2 pow $1,$0 mul $1,56 div $1,30 mov $0,$1
#Written By Bradley Grose .data array1: .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 string1: .asciiz "Read 1st number: " string2: .asciiz "Read second number: " string3: .asciiz "Sum = " .text la $t3, array1 li $s0, 0 # i = 0 li $s1, 0 # sum = 0 Loop1: bgt $s0, 9, out sll $t4, $s0, 2 #i*4 add $t4, $t4, $t3 #&array[i] lw $t5, ($t4) #array1[i] add $s1, $s1, $t5 #sum = sum + array1[i] addi $s0, $s0, 1 #i++ j Loop1 out: li $v0, 4 #print string3 la $a0, string3 syscall li $v0, 1 move $a0, $t2 syscall li $v0, 10 syscall li $v0, 4 #print string1 la $a0, string1 syscall li $v0, 5 #read 1st num syscall move $t0, $v0 #first input li $v0, 4 #print string2 la $a0, string2 syscall li $v0, 5 syscall move $t1, $v0 #second input add $t2, $t0, $t1 li $v0, 4 #print string3 la $a0, string3 syscall li $v0, 1 move $a0, $t2 syscall li $v0, 10 syscall
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 .globl n0_Decrypt_RIJ128_AES_NI .type n0_Decrypt_RIJ128_AES_NI, @function n0_Decrypt_RIJ128_AES_NI: lea (,%rdx,4), %rax lea (,%rax,4), %rax movdqu (%rdi), %xmm0 pxor (%rcx,%rax), %xmm0 cmp $(12), %rdx jl .Lkey_128gas_1 jz .Lkey_192gas_1 .Lkey_256gas_1: aesdec (208)(%rcx), %xmm0 aesdec (192)(%rcx), %xmm0 .Lkey_192gas_1: aesdec (176)(%rcx), %xmm0 aesdec (160)(%rcx), %xmm0 .Lkey_128gas_1: aesdec (144)(%rcx), %xmm0 aesdec (128)(%rcx), %xmm0 aesdec (112)(%rcx), %xmm0 aesdec (96)(%rcx), %xmm0 aesdec (80)(%rcx), %xmm0 aesdec (64)(%rcx), %xmm0 aesdec (48)(%rcx), %xmm0 aesdec (32)(%rcx), %xmm0 aesdec (16)(%rcx), %xmm0 aesdeclast (%rcx), %xmm0 movdqu %xmm0, (%rsi) ret .Lfe1: .size n0_Decrypt_RIJ128_AES_NI, .Lfe1-(n0_Decrypt_RIJ128_AES_NI)
// // Simu5G // // Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa) // // This file is part of a software released under the license included in file // "license.pdf". Please read LICENSE and README files before using it. // The above files and the present reference are part of the software itself, // and cannot be removed from it. // #include "common/LteControlInfo.h" #include "stack/mac/amc/UserTxParams.h" using namespace inet; UserControlInfo::~UserControlInfo() { if (userTxParams != nullptr) { delete userTxParams; userTxParams = nullptr; } } UserControlInfo::UserControlInfo() : UserControlInfo_Base() { userTxParams = nullptr; grantedBlocks.clear(); } UserControlInfo& UserControlInfo::operator=(const UserControlInfo& other) { if (&other == this) return *this; if (other.userTxParams != nullptr) { const UserTxParams* txParams = check_and_cast<const UserTxParams*>(other.userTxParams); this->userTxParams = txParams->dup(); } else { this->userTxParams = nullptr; } this->grantedBlocks = other.grantedBlocks; this->senderCoord = other.senderCoord; this->feedbackReq = other.feedbackReq; UserControlInfo_Base::operator=(other); return *this; } void UserControlInfo::setCoord(const inet::Coord& coord) { senderCoord = coord; } void UserControlInfo::setUserTxParams(const UserTxParams *newParams) { if(userTxParams != nullptr){ delete userTxParams; } userTxParams = newParams; } inet::Coord UserControlInfo::getCoord() const { return senderCoord; }
; A253622: Centered heptagonal numbers (A069099) which are also centered pentagonal numbers (A005891). ; Submitted by Christian Krause ; 1,106,15016,2132131,302747551,42988020076,6103996103206,866724458635141,123068769130086781,17474898492013687726,2481312517096813570276,352328902529255513291431,50028222846637186073812891,7103655315319951166968139056,1008669026552586428523401933026,143223898115151952899156106350601,20336784863325024725251643699852281,2887680226694038359032834249272673266,410030255405690121957937211753019751456,58221408587381303279668051234679532033451,8267029989152739375590905338112740528998551 mov $3,1 lpb $0 sub $0,1 mov $1,$3 mul $1,10 add $2,$1 add $3,$2 lpe pow $3,2 mov $0,$3 div $0,120 mul $0,105 add $0,1
; A168610: a(n) = 3^n + 5. ; 6,8,14,32,86,248,734,2192,6566,19688,59054,177152,531446,1594328,4782974,14348912,43046726,129140168,387420494,1162261472,3486784406,10460353208,31381059614,94143178832,282429536486,847288609448,2541865828334,7625597484992,22876792454966,68630377364888,205891132094654,617673396283952,1853020188851846,5559060566555528,16677181699666574,50031545098999712,150094635296999126,450283905890997368,1350851717672992094,4052555153018976272,12157665459056928806,36472996377170786408,109418989131512359214 mov $1,3 pow $1,$0 add $1,5 mov $0,$1
#include <stdio.h> #include <dirent.h> #include <string.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <iostream> #include "/opt/rocm/rpp/include/rppi.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> using namespace cv; using namespace std; #include <CL/cl.hpp> int G_IP_CHANNEL = 3; int G_MODE = 1; char src[1000] = {"/home/ulagammai/ulagammai/TESTSUITE_RPP/Input_Images/RGBS"}; char dst[1000] = {"/home/ulagammai/ulagammai/TESTSUITE_RPP/Output_Images"}; char funcName[1000] = {"gamma_correction"}; char funcType[1000] = {"BatchSD_ROIS"}; int main(int argc, char **argv) { int ip_channel = G_IP_CHANNEL; int mode = G_MODE; if(mode == 0) { strcat(funcType,"_CPU"); } else if (mode == 1) { strcat(funcType,"_GPU"); } else { strcat(funcType,"_HIP"); } if(ip_channel == 1) { strcat(funcType,"_PLN"); } else { strcat(funcType,"_PKD"); } int i = 0, j = 0; int minHeight = 30000, minWidth = 30000, maxHeight = 0, maxWidth = 0; unsigned long long count = 0; unsigned long long ioBufferSize = 0; static int noOfImages = 0; Mat image; struct dirent *de; char src1[1000]; strcpy(src1, src); strcat(src1, "/"); strcat(funcName,funcType); strcat(dst,"/"); strcat(dst,funcName); mkdir(dst, 0700); strcat(dst,"/"); DIR *dr = opendir(src); while ((de = readdir(dr)) != NULL) { if(strcmp(de->d_name,".") == 0 || strcmp(de->d_name,"..") == 0) continue; noOfImages += 1; } closedir(dr); RppiSize *srcSize = (RppiSize *)calloc(noOfImages, sizeof(RppiSize)); const int images = noOfImages; char imageNames[images][1000]; DIR *dr1 = opendir(src); while ((de = readdir(dr1)) != NULL) { if(strcmp(de->d_name,".") == 0 || strcmp(de->d_name,"..") == 0) continue; strcpy(imageNames[count],de->d_name); char temp[1000]; strcpy(temp,src1); strcat(temp, imageNames[count]); if(ip_channel == 3) { image = imread(temp, 1); } else { image = imread(temp, 0); } srcSize[count].height = image.rows; srcSize[count].width = image.cols; ioBufferSize += (unsigned long long)srcSize[count].height * (unsigned long long)srcSize[count].width * (unsigned long long)ip_channel; if(minHeight > srcSize[count].height) { minHeight = srcSize[count].height; } if(minWidth > srcSize[count].width) { minWidth = srcSize[count].width; } count++; } closedir(dr1); Rpp8u *input = (Rpp8u *)calloc(ioBufferSize, sizeof(Rpp8u)); Rpp8u *output = (Rpp8u *)calloc(ioBufferSize, sizeof(Rpp8u)); DIR *dr2 = opendir(src); count = 0; i = 0; while ((de = readdir(dr2)) != NULL) { if(strcmp(de->d_name,".") == 0 || strcmp(de->d_name,"..") == 0) continue; char temp[1000]; strcpy(temp,src1); strcat(temp, de->d_name); if(ip_channel == 3) { image = imread(temp, 1); } else { image = imread(temp, 0); } Rpp8u *ip_image = image.data; for(j = 0 ; j < srcSize[i].height * srcSize[i].width * ip_channel ; j++) { input[count] = ip_image[j]; count++; } i++; } closedir(dr2); RppiROI roiPoints; while (1) { roiPoints.x = rand() % minWidth; roiPoints.y = rand() % minHeight; roiPoints.roiHeight = (rand() % minHeight) * 3; roiPoints.roiWidth = (rand() % minWidth) * 3; roiPoints.roiHeight -= roiPoints.y; roiPoints.roiWidth -= roiPoints.x; if((roiPoints.y + roiPoints.roiHeight > roiPoints.y && roiPoints.x + roiPoints.roiWidth > roiPoints.x) && (roiPoints.y + roiPoints.roiHeight < minHeight && roiPoints.x + roiPoints.roiWidth < minWidth)) break; } Rpp32f mingamma = 0.5, maxgamma = 1, gamma[images]; for(i = 0 ; i < images ; i++) { gamma[i] = mingamma; } cl_mem d_input, d_output; cl_platform_id platform_id; cl_device_id device_id; cl_context theContext; cl_command_queue theQueue; cl_int err; err = clGetPlatformIDs(1, &platform_id, NULL); err = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 1, &device_id, NULL); theContext = clCreateContext(0, 1, &device_id, NULL, NULL, &err); theQueue = clCreateCommandQueue(theContext, device_id, 0, &err); d_input = clCreateBuffer(theContext, CL_MEM_READ_ONLY, ioBufferSize * sizeof(Rpp8u), NULL, NULL); d_output = clCreateBuffer(theContext, CL_MEM_READ_ONLY, ioBufferSize * sizeof(Rpp8u), NULL, NULL); err = clEnqueueWriteBuffer(theQueue, d_input, CL_TRUE, 0, ioBufferSize * sizeof(Rpp8u), input, 0, NULL, NULL); rppHandle_t handle; rppCreateWithStreamAndBatchSize(&handle, theQueue, noOfImages); clock_t start, end; double cpu_time_used; start = clock(); rppi_gamma_correction_u8_pkd3_batchSD_ROIS_gpu(d_input, srcSize[0], d_output, gamma, roiPoints, noOfImages, handle); end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; cout<<" BatchSD_ROIS : "<<cpu_time_used<<endl; clEnqueueReadBuffer(theQueue, d_output, CL_TRUE, 0, ioBufferSize * sizeof(Rpp8u), output, 0, NULL, NULL); rppDestroyGPU(handle); count = 0; for(j = 0 ; j < noOfImages ; j++) { int op_size = srcSize[j].height * srcSize[j].width * ip_channel; Rpp8u *temp_output = (Rpp8u *)calloc(op_size, sizeof(Rpp8u)); for(i = 0 ; i < op_size ; i++) { temp_output[i] = output[count]; count++; } char temp[1000]; strcpy(temp,dst); strcat(temp, imageNames[j]); Mat mat_op_image; if(ip_channel == 3) { mat_op_image = Mat(srcSize[j].height, srcSize[j].width, CV_8UC3, temp_output); imwrite(temp, mat_op_image); } if(ip_channel == 1) { mat_op_image = Mat(srcSize[j].height, srcSize[j].width, CV_8UC1, temp_output); imwrite(temp, mat_op_image); } free(temp_output); } free(srcSize); free(input); free(output); return 0; }
; A119975: E.g.f. exp(x)*(Bessel_I(0,2*sqrt(2)x) + Bessel_I(1,2*sqrt(2)x)/sqrt(2)). ; Submitted by Jon Maiga ; 1,2,7,22,77,266,947,3382,12217,44338,161855,593110,2181445,8046650,29759147,110303798,409655281,1524056546,5678827511,21189499030,79164147389,296094973418,1108623865123,4154794910518,15584520425641,58504061139986,219786463328047,826256195599702,3108181488603317,11699222249087002,44060516506265371,166023192094704182,625893662312821217,2360653550537726402,8907426695798885863,33624043443134600470,126974218872305893165,479667313257516264650,1812656008854424695955,6852258243902997860662 mov $1,1 mov $3,$0 mov $4,1 lpb $3 mul $1,$4 mul $1,$3 mod $4,2 add $5,$4 div $1,$5 div $2,2 add $2,$1 mul $2,2 sub $3,1 add $4,1 lpe mov $0,$2 div $0,2 add $0,1
lda {m2}+1 lsr sta {m1}+1 lda {m2} ror sta {m1} lsr {m1}+1 ror {m1} lsr {m1}+1 ror {m1}
; Dn-FamiTracker exported music data: love_3_option.0cc ; ; Module header .word ft_song_list .word ft_instrument_list .word ft_sample_list .word ft_samples .word ft_groove_list .byte 4 ; flags .word 3840 ; NTSC speed .word 3840 ; PAL speed ; Instrument pointer list ft_instrument_list: .word ft_inst_0 .word ft_inst_1 .word ft_inst_2 .word ft_inst_3 ; Instruments ft_inst_0: .byte 0 .byte $00 ft_inst_1: .byte 0 .byte $01 .word ft_seq_2a03_0 ft_inst_2: .byte 0 .byte $05 .word ft_seq_2a03_5 .word ft_seq_2a03_7 ft_inst_3: .byte 0 .byte $05 .word ft_seq_2a03_10 .word ft_seq_2a03_2 ; Sequences ft_seq_2a03_0: .byte $09, $FF, $00, $00, $0A, $04, $05, $05, $02, $02, $02, $02, $00 ft_seq_2a03_2: .byte $02, $FF, $00, $00, $0F, $F1 ft_seq_2a03_5: .byte $09, $FF, $00, $00, $0F, $0D, $0B, $0A, $08, $07, $05, $03, $02 ft_seq_2a03_7: .byte $01, $FF, $00, $00, $FE ft_seq_2a03_10: .byte $02, $FF, $00, $00, $0F, $0C ; DPCM instrument list (pitch, sample index) ft_sample_list: .byte 15, 44, 0 .byte 15, 44, 3 ; DPCM samples list (location, size, bank) ft_samples: .byte <((ft_sample_0 - $C000) >> 6), 11, <.bank(ft_sample_0) .byte <((ft_sample_1 - $C000) >> 6), 39, <.bank(ft_sample_1) ; Groove list ft_groove_list: .byte $00 ; Grooves (size, terms) ; Song pointer list ft_song_list: .word ft_song_0 ; Song info ft_song_0: .word ft_s0_frames .byte 21 ; frame count .byte 64 ; pattern length .byte 3 ; speed .byte 160 ; tempo .byte 0 ; groove position .byte 0 ; initial bank ; ; Pattern and frame data for all songs below ; ; Bank 0 ft_s0_frames: .word ft_s0f0 .word ft_s0f1 .word ft_s0f2 .word ft_s0f3 .word ft_s0f4 .word ft_s0f5 .word ft_s0f6 .word ft_s0f7 .word ft_s0f8 .word ft_s0f9 .word ft_s0f10 .word ft_s0f11 .word ft_s0f12 .word ft_s0f13 .word ft_s0f14 .word ft_s0f15 .word ft_s0f16 .word ft_s0f17 .word ft_s0f18 .word ft_s0f19 .word ft_s0f20 ft_s0f0: .word ft_s0p0c0, ft_s0p0c0, ft_s0p0c2, ft_s0p0c0, ft_s0p2c4 ft_s0f1: .word ft_s0p0c0, ft_s0p0c0, ft_s0p0c2, ft_s0p0c3, ft_s0p0c4 ft_s0f2: .word ft_s0p1c0, ft_s0p1c1, ft_s0p1c2, ft_s0p1c3, ft_s0p1c4 ft_s0f3: .word ft_s0p1c0, ft_s0p1c1, ft_s0p1c2, ft_s0p1c3, ft_s0p3c4 ft_s0f4: .word ft_s0p2c0, ft_s0p2c1, ft_s0p3c2, ft_s0p1c3, ft_s0p1c4 ft_s0f5: .word ft_s0p3c0, ft_s0p3c1, ft_s0p3c2, ft_s0p1c3, ft_s0p3c4 ft_s0f6: .word ft_s0p12c0, ft_s0p4c1, ft_s0p4c2, ft_s0p1c3, ft_s0p1c4 ft_s0f7: .word ft_s0p12c0, ft_s0p0c0, ft_s0p4c2, ft_s0p1c3, ft_s0p1c4 ft_s0f8: .word ft_s0p5c0, ft_s0p5c1, ft_s0p5c2, ft_s0p1c3, ft_s0p1c4 ft_s0f9: .word ft_s0p4c0, ft_s0p6c1, ft_s0p6c2, ft_s0p1c3, ft_s0p1c4 ft_s0f10: .word ft_s0p5c0, ft_s0p5c1, ft_s0p5c2, ft_s0p1c3, ft_s0p1c4 ft_s0f11: .word ft_s0p4c0, ft_s0p6c1, ft_s0p6c2, ft_s0p1c3, ft_s0p1c4 ft_s0f12: .word ft_s0p6c0, ft_s0p1c1, ft_s0p1c2, ft_s0p1c3, ft_s0p1c4 ft_s0f13: .word ft_s0p6c0, ft_s0p1c1, ft_s0p1c2, ft_s0p1c3, ft_s0p3c4 ft_s0f14: .word ft_s0p7c0, ft_s0p2c1, ft_s0p3c2, ft_s0p1c3, ft_s0p1c4 ft_s0f15: .word ft_s0p8c0, ft_s0p3c1, ft_s0p3c2, ft_s0p1c3, ft_s0p4c4 ft_s0f16: .word ft_s0p9c0, ft_s0p9c1, ft_s0p3c2, ft_s0p1c3, ft_s0p1c4 ft_s0f17: .word ft_s0p8c0, ft_s0p3c1, ft_s0p3c2, ft_s0p1c3, ft_s0p3c4 ft_s0f18: .word ft_s0p10c0, ft_s0p4c1, ft_s0p4c2, ft_s0p1c3, ft_s0p1c4 ft_s0f19: .word ft_s0p12c0, ft_s0p7c1, ft_s0p4c2, ft_s0p1c3, ft_s0p1c4 ft_s0f20: .word ft_s0p11c0, ft_s0p8c1, ft_s0p0c2, ft_s0p0c0, ft_s0p0c0 ; Bank 0 ft_s0p0c0: .byte $00, $3F ; Bank 0 ft_s0p0c2: .byte $00, $04, $94, $01, $00, $07, $94, $01, $00, $07, $94, $01, $00, $07, $94, $01, $00, $22 ; Bank 0 ft_s0p0c3: .byte $E1, $FF, $1C, $07, $1C, $07, $1C, $07, $1C, $06, $87, $01, $00, $20 ; Bank 0 ft_s0p0c4: .byte $00, $14, $94, $01, $01, $02, $02, $02, $01, $01, $94, $01, $02, $22 ; Bank 0 ft_s0p1c0: .byte $E2, $93, $02, $FA, $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $2C, $02 .byte $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $2C, $01, $94, $01, $3D, $02, $21, $02, $2D, $01 .byte $94, $01, $34, $02, $21, $02, $2D, $01, $94, $01, $34, $02, $33, $02, $23, $01, $94, $01, $2F, $02 .byte $33, $02, $23, $01, $94, $01, $2F, $02 ; Bank 0 ft_s0p1c1: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $35, $02, $FD, $31, $01, $94, $01, $FD, $33, $02, $93, $01, $FD .byte $35, $02, $FD, $36, $01, $94, $01, $FD, $36, $00, $E0, $8D, $14, $FA, $38, $09, $E3, $8A, $FD, $38 .byte $02, $FD, $35, $01, $94, $01, $FD, $31, $02, $FD, $34, $02, $FD, $2D, $01, $94, $01, $FD, $31, $02 .byte $FD, $33, $00, $E0, $8D, $0A, $FA, $34, $06, $E3, $8A, $FD, $33, $02, $FD, $2F, $01, $94, $01, $FD .byte $2A, $02, $FD, $31, $00, $E0, $8D, $14, $FA, $33, $06 ; Bank 0 ft_s0p1c2: .byte $E0, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $31, $02, $9B .byte $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B .byte $08, $19, $02, $9B, $08, $31, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $2F, $02, $9B, $08, $2D .byte $02, $9B, $06, $21, $01, $94, $01, $9B, $08, $28, $02, $9B, $08, $2D, $02, $9B, $06, $21, $01, $94 .byte $01, $9B, $08, $28, $02, $9B, $08, $2F, $02, $9B, $06, $23, $01, $94, $01, $9B, $08, $2A, $02, $9B .byte $08, $2F, $02, $9B, $06, $23, $01, $94, $01, $9B, $08, $2A, $02 ; Bank 0 ft_s0p1c3: .byte $E1, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C, $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C .byte $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C, $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C .byte $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C, $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C .byte $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C, $02, $FF, $1C, $02, $F8, $1C, $01, $94, $01, $1C .byte $02 ; Bank 0 ft_s0p1c4: .byte $01, $07, $02, $07, $01, $04, $94, $01, $01, $02, $02, $07, $01, $07, $02, $07, $01, $04, $94, $01 .byte $01, $02, $02, $07 ; Bank 0 ft_s0p2c0: .byte $E2, $93, $02, $FA, $2D, $02, $34, $01, $94, $01, $39, $02, $2D, $02, $34, $01, $94, $01, $39, $02 .byte $2D, $02, $31, $01, $94, $01, $34, $02, $31, $02, $34, $01, $94, $01, $39, $02, $36, $02, $2F, $01 .byte $94, $01, $36, $02, $3B, $02, $36, $01, $94, $01, $2F, $02, $36, $02, $34, $01, $94, $01, $33, $02 .byte $2F, $02, $7F, $01, $94, $01, $36, $02 ; Bank 0 ft_s0p2c1: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $2D, $02, $FD, $28, $01, $94, $01, $FD, $2D, $02, $FD, $31, $02 .byte $FD, $2D, $01, $94, $01, $FD, $33, $00, $E0, $8D, $0A, $FA, $34, $06, $94, $01, $00, $02, $E3, $8A .byte $FD, $34, $02, $FD, $36, $01, $94, $01, $FD, $34, $02, $FD, $33, $02, $FD, $2F, $01, $94, $01, $FD .byte $33, $02, $FD, $35, $00, $E0, $8D, $0A, $FA, $36, $03, $94, $01, $00, $02, $E3, $8A, $FD, $33, $02 .byte $FD, $31, $01, $94, $01, $FD, $2F, $02, $FD, $2D, $00, $E0, $8D, $14, $FA, $2F, $03, $94, $01, $00 .byte $02 ; Bank 0 ft_s0p2c4: .byte $96, $38, $00, $02, $87, $01, $00, $3C ; Bank 0 ft_s0p3c0: .byte $E2, $93, $02, $FA, $2D, $02, $34, $01, $94, $01, $39, $02, $2D, $02, $34, $01, $94, $01, $39, $02 .byte $2D, $02, $31, $01, $94, $01, $34, $02, $31, $02, $34, $01, $94, $01, $39, $02, $36, $02, $2F, $01 .byte $94, $01, $36, $02, $3B, $02, $36, $01, $94, $01, $2F, $02, $36, $02, $34, $01, $94, $01, $33, $02 .byte $2F, $02, $33, $01, $94, $01, $36, $02 ; Bank 0 ft_s0p3c1: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $2C, $00, $E0, $8D, $0A, $FA, $2D, $03, $94, $01, $00, $02, $E3 .byte $8A, $FD, $2F, $02, $FD, $31, $01, $94, $01, $FD, $33, $00, $E0, $8D, $0A, $FA, $34, $06, $94, $01 .byte $00, $02, $E3, $8A, $FD, $31, $02, $FD, $33, $01, $94, $01, $FD, $34, $02, $FD, $33, $02, $FD, $31 .byte $01, $94, $01, $FD, $2F, $02, $FD, $2D, $00, $E0, $8D, $14, $FA, $2F, $03, $94, $01, $00, $02, $E3 .byte $8A, $FD, $36, $02, $FD, $34, $01, $94, $01, $FD, $33, $02, $FD, $34, $00, $E0, $8D, $14, $FA, $36 .byte $03, $94, $01, $00, $02 ; Bank 0 ft_s0p3c2: .byte $E0, $9B, $08, $15, $02, $9B, $06, $21, $01, $94, $01, $9B, $08, $15, $02, $9B, $08, $28, $02, $9B .byte $06, $15, $01, $94, $01, $9B, $08, $21, $02, $9B, $08, $15, $02, $9B, $06, $21, $01, $94, $01, $9B .byte $08, $15, $02, $9B, $08, $28, $02, $9B, $06, $21, $01, $94, $01, $9B, $08, $15, $02, $9B, $08, $17 .byte $02, $9B, $06, $23, $01, $94, $01, $9B, $08, $17, $02, $9B, $08, $2A, $02, $9B, $06, $17, $01, $94 .byte $01, $9B, $08, $21, $02, $9B, $08, $17, $02, $9B, $06, $23, $01, $94, $01, $9B, $08, $17, $02, $9B .byte $08, $2A, $02, $9B, $06, $17, $01, $94, $01, $9B, $08, $2C, $02 ; Bank 0 ft_s0p3c4: .byte $01, $07, $02, $07, $01, $04, $94, $01, $01, $02, $02, $07, $01, $07, $02, $04, $94, $01, $02, $02 .byte $01, $04, $94, $01, $01, $02, $02, $02, $02, $01, $94, $01, $02, $02 ; Bank 0 ft_s0p4c0: .byte $E2, $93, $02, $8A, $FA, $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $2C .byte $02, $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $2C, $01, $94, $01, $3D, $02, $25, $02, $2C .byte $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $2C, $02, $25, $02, $2C, $01, $94, $01, $31 .byte $02, $38, $02, $2C, $01, $94, $01, $3D, $02 ; Bank 0 ft_s0p4c1: .byte $E3, $93, $01, $9A, $00, $8A, $FD, $36, $00, $E0, $8D, $14, $FA, $38, $09, $E3, $93, $01, $8A, $F8 .byte $36, $00, $E0, $8D, $14, $F6, $38, $08, $94, $01, $E3, $93, $01, $8A, $F5, $36, $00, $94, $01, $E0 .byte $8D, $14, $F3, $38, $09, $E3, $93, $01, $8A, $F3, $36, $00, $E0, $8D, $14, $F2, $38, $08, $E3, $93 .byte $01, $8A, $F2, $36, $00, $E0, $8D, $14, $F1, $38, $09, $94, $01, $7F, $0A ; Bank 0 ft_s0p4c2: .byte $E0, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $31, $02, $9B .byte $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B .byte $08, $19, $02, $9B, $08, $31, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $2F, $02, $9B, $08, $25 .byte $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $31, $02, $9B, $06, $19, $01, $94 .byte $01, $9B, $08, $19, $02, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B .byte $08, $31, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $2F, $02 ; Bank 0 ft_s0p4c4: .byte $01, $07, $02, $07, $01, $04, $94, $01, $01, $02, $02, $07, $01, $07, $02, $04, $94, $01, $02, $02 .byte $01, $04, $94, $01, $01, $02, $02, $02, $01, $01, $94, $01, $02, $02 ; Bank 0 ft_s0p5c0: .byte $E2, $93, $02, $FA, $23, $02, $2A, $01, $94, $01, $2F, $02, $36, $02, $2F, $01, $94, $01, $2A, $02 .byte $23, $02, $2A, $01, $94, $01, $2F, $02, $23, $02, $2A, $01, $94, $01, $2F, $02, $1E, $02, $25, $01 .byte $94, $01, $2A, $02, $1E, $02, $25, $01, $94, $01, $2A, $02, $2C, $02, $2E, $01, $94, $01, $25, $02 .byte $1E, $02, $2E, $01, $94, $01, $2A, $02 ; Bank 0 ft_s0p5c1: .byte $E0, $9A, $00, $93, $00, $8A, $FD, $2A, $02, $23, $01, $94, $01, $2A, $02, $2F, $02, $2A, $01, $94 .byte $01, $31, $02, $33, $01, $9A, $03, $00, $02, $94, $01, $9A, $00, $FD, $31, $01, $9A, $03, $00, $03 .byte $9A, $00, $FD, $2F, $01, $94, $01, $9A, $03, $00, $02, $9A, $00, $FD, $2C, $00, $8D, $14, $2E, $03 .byte $94, $01, $00, $00, $F4, $00, $01, $8A, $FD, $2C, $04, $94, $01, $00, $00, $F4, $00, $01, $FD, $2A .byte $04, $94, $01, $00, $00, $F4, $00, $01, $FD, $2C, $02, $2A, $01, $94, $01, $29, $02 ; Bank 0 ft_s0p5c2: .byte $E0, $9B, $08, $17, $02, $9B, $06, $17, $01, $94, $01, $9B, $08, $17, $02, $9B, $08, $23, $02, $9B .byte $06, $17, $01, $94, $01, $9B, $08, $1E, $02, $9B, $08, $17, $02, $9B, $06, $17, $01, $94, $01, $9B .byte $08, $17, $02, $9B, $08, $23, $02, $9B, $06, $17, $01, $94, $01, $9B, $08, $23, $02, $9B, $08, $12 .byte $02, $9B, $06, $12, $01, $94, $01, $9B, $08, $12, $02, $9B, $08, $1E, $02, $9B, $06, $12, $01, $94 .byte $01, $9B, $08, $2A, $02, $9B, $08, $12, $02, $9B, $06, $12, $01, $94, $01, $9B, $08, $12, $02, $9B .byte $08, $1E, $02, $9B, $06, $12, $01, $94, $01, $9B, $08, $2A, $02 ; Bank 0 ft_s0p6c0: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $2C, $02, $FD, $29, $01, $94, $01, $FD, $2C, $02, $93, $01, $FD .byte $31, $02, $FD, $33, $01, $94, $01, $FD, $33, $00, $E0, $8D, $14, $FA, $35, $09, $E3, $8A, $FD, $35 .byte $02, $FD, $31, $01, $94, $01, $FD, $2C, $02, $FD, $2D, $02, $FD, $28, $01, $94, $01, $FD, $2D, $02 .byte $FD, $30, $00, $E0, $8D, $0A, $FA, $31, $06, $E3, $8A, $FD, $2F, $02, $FD, $2A, $01, $94, $01, $FD .byte $2F, $02, $FD, $2D, $00, $E0, $8D, $14, $FA, $2F, $06 ; Bank 0 ft_s0p6c1: .byte $E0, $9A, $00, $93, $00, $FD, $23, $00, $8D, $14, $25, $04, $F4, $00, $01, $8A, $FD, $23, $00, $8D .byte $14, $25, $09, $9A, $01, $F4, $00, $0C, $9A, $00, $8A, $FD, $33, $00, $8D, $14, $35, $04, $F4, $00 .byte $01, $8A, $FD, $2F, $00, $8D, $14, $31, $09, $9A, $01, $F4, $00, $0C ; Bank 0 ft_s0p6c2: .byte $E0, $9B, $08, $19, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $25, $02, $9B .byte $06, $19, $01, $94, $01, $9B, $08, $23, $02, $9B, $08, $19, $02, $9B, $06, $19, $01, $94, $01, $9B .byte $08, $19, $02, $9B, $08, $25, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $29, $02, $9B, $08, $19 .byte $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $19, $02, $9B, $08, $25, $02, $9B, $06, $19, $01, $94 .byte $01, $9B, $08, $22, $02, $9B, $08, $21, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $1E, $02, $9B .byte $08, $1D, $02, $9B, $06, $19, $01, $94, $01, $9B, $08, $25, $02 ; Bank 0 ft_s0p7c0: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $28, $02, $FD, $25, $01, $94, $01, $FD, $28, $02, $FD, $2D, $02 .byte $FD, $28, $01, $94, $01, $FD, $2F, $00, $E0, $8D, $14, $FA, $31, $06, $94, $01, $00, $02, $E3, $8A .byte $FD, $31, $02, $FD, $33, $01, $94, $01, $FD, $31, $02, $FD, $2F, $02, $FD, $2A, $01, $94, $01, $FD .byte $2F, $02, $FD, $2D, $00, $E0, $8D, $0A, $FA, $2F, $03, $94, $01, $00, $02, $E3, $8A, $FD, $36, $02 .byte $FD, $34, $01, $94, $01, $FD, $33, $02, $FD, $34, $00, $E0, $8D, $14, $FA, $36, $03, $94, $01, $00 .byte $02 ; Bank 0 ft_s0p7c1: .byte $00, $3C, $94, $01, $E2, $93, $02, $8A, $F5, $38, $02 ; Bank 0 ft_s0p8c0: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $33, $00, $E0, $8D, $0A, $FA, $34, $03, $94, $01, $00, $02, $E3 .byte $8A, $FD, $28, $02, $FD, $2D, $01, $94, $01, $FD, $2F, $00, $E0, $8D, $14, $FA, $31, $06, $94, $01 .byte $00, $02, $E3, $8A, $FD, $2D, $02, $FD, $2F, $01, $94, $01, $FD, $31, $02, $FD, $2F, $02, $FD, $2A .byte $01, $94, $01, $FD, $27, $02, $FD, $25, $00, $E0, $8D, $14, $FA, $27, $03, $94, $01, $00, $02, $E3 .byte $8A, $FD, $2F, $02, $FD, $2A, $01, $94, $01, $FD, $2F, $02, $FD, $31, $00, $E0, $8D, $14, $FA, $33 .byte $03, $94, $01, $00, $02 ; Bank 0 ft_s0p8c1: .byte $E2, $31, $02, $3D, $04, $F2, $38, $02, $31, $01, $94, $01, $3D, $09, $88, $00, $00, $28 ; Bank 0 ft_s0p9c0: .byte $E2, $93, $02, $8A, $9A, $00, $FA, $2D, $02, $34, $01, $94, $01, $39, $02, $2D, $02, $34, $01, $94 .byte $01, $39, $02, $2D, $02, $31, $01, $94, $01, $34, $02, $31, $02, $34, $01, $94, $01, $39, $02, $36 .byte $02, $2F, $01, $94, $01, $36, $02, $3B, $02, $36, $01, $94, $01, $2F, $02, $36, $02, $34, $01, $94 .byte $01, $33, $02, $2F, $02, $33, $01, $94, $01, $36, $02 ; Bank 0 ft_s0p9c1: .byte $E3, $93, $01, $9A, $01, $8A, $FD, $2D, $02, $FD, $28, $01, $94, $01, $FD, $2D, $02, $FD, $31, $02 .byte $FD, $2D, $01, $94, $01, $FD, $33, $00, $E0, $8D, $0A, $FA, $34, $06, $94, $01, $00, $02, $E3, $8A .byte $FD, $31, $02, $FD, $33, $01, $94, $01, $FD, $34, $02, $FD, $33, $02, $FD, $31, $01, $94, $01, $FD .byte $2F, $02, $FD, $2D, $00, $E0, $8D, $14, $FA, $2F, $03, $94, $01, $00, $02, $E3, $8A, $FD, $36, $02 .byte $FD, $34, $01, $94, $01, $FD, $33, $02, $FD, $35, $00, $E0, $8D, $0A, $FA, $36, $03, $94, $01, $00 .byte $02 ; Bank 0 ft_s0p10c0: .byte $E3, $93, $01, $9A, $00, $8A, $FD, $27, $00, $E0, $8D, $14, $FA, $29, $09, $E3, $93, $01, $8A, $F8 .byte $27, $00, $E0, $8D, $14, $F6, $29, $08, $94, $01, $E3, $93, $01, $8A, $F5, $27, $00, $94, $01, $E0 .byte $8D, $14, $F3, $29, $09, $E3, $93, $01, $8A, $F3, $27, $00, $E0, $8D, $14, $F2, $29, $08, $E3, $93 .byte $01, $8A, $F2, $27, $00, $E0, $8D, $14, $F1, $29, $09, $94, $01, $7F, $0A ; Bank 0 ft_s0p11c0: .byte $00, $02, $E2, $93, $02, $F3, $38, $01, $94, $01, $31, $02, $3D, $04, $94, $01, $F1, $38, $02, $31 .byte $02, $3D, $2C ; Bank 0 ft_s0p12c0: .byte $E2, $93, $02, $8A, $FA, $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $2C .byte $02, $25, $02, $2C, $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $3D, $02, $25, $02, $2C .byte $01, $94, $01, $31, $02, $38, $02, $31, $01, $94, $01, $2C, $02, $25, $02, $2C, $01, $94, $01, $31 .byte $02, $38, $02, $31, $01, $94, $01, $3D, $02 ; DPCM samples (located at DPCM segment) .segment "DPCM_0" ft_sample_0: ; Nes Kick .byte $55, $00, $E0, $DB, $EF, $FD, $F7, $AF, $AA, $AA, $AA, $AA, $C2, $81, $86, $00, $41, $80, $40, $55 .byte $55, $55, $55, $55, $55, $55, $55, $55, $55, $55, $F5, $F3, $EF, $F7, $FD, $EF, $AA, $AA, $AA, $AA .byte $AA, $AA, $AA, $AA, $AA, $AA, $8A, $34, $0C, $19, $0C, $04, $04, $08, $55, $55, $55, $55, $55, $55 .byte $55, $55, $55, $55, $55, $F5, $D3, $F8, $F7, $E7, $FD, $F7, $F4, $AA, $AA, $B2, $E2, $74, $0A, $AF .byte $AA, $0A, $AC, $05, $04, $04, $04, $3E, $0A, $48, $D5, $9A, $52, $D5, $9C, $AA, $DA, $D2, $19, $3C .byte $8F, $B7, $8D, $35, $6F, $5F, $CE, $9B, $DC, $67, $9D, $37, $57, $AE, $2C, $E3, $9A, $AC, $32, $9B .byte $52, $97, $B2, $B2, $8A, $0C, $6D, $F3, $AC, $E2, $6C, $90, $F3, $42, $86, $2D, $B9, $C8, $C1, $D2 .byte $C0, $09, $4D, $1A, $24, $D3, $C8, $C1, $C0, $24, $4D, $55, $55, $55, $55, $55, $55, $55, $55, $55 .byte $55, $55, $55, $55, $55, $55, $AB, $F2, $FF, $FF, $9B, $55, $55, $55, $55, $55, $55 .align 64 ft_sample_1: ; NES Snare .byte $03, $00, $50, $55, $55, $55, $55, $55, $55, $55, $55, $FD, $EF, $FF, $3F, $CD, $83, $91, $0F, $1C .byte $E3, $40, $00, $00, $55, $55, $55, $D5, $F3, $0F, $7E, $D0, $FF, $FD, $FF, $79, $55, $45, $1C, $00 .byte $0E, $14, $00, $40, $55, $55, $D5, $FE, $FF, $F3, $E3, $FF, $73, $56, $55, $55, $95, $00, $10, $00 .byte $10, $50, $55, $55, $55, $55, $D5, $FF, $7F, $FF, $FF, $C9, $5A, $55, $55, $55, $01, $C2, $21, $08 .byte $00, $90, $0B, $55, $55, $55, $55, $D5, $FF, $BF, $FF, $F9, $5F, $55, $55, $55, $55, $C0, $0D, $02 .byte $02, $00, $88, $34, $55, $55, $55, $F5, $F1, $FF, $77, $7C, $5E, $FE, $F3, $69, $55, $78, $25, $07 .byte $01, $02, $80, $07, $08, $6C, $4A, $55, $55, $55, $DF, $EF, $FF, $CF, $3F, $7E, $55, $55, $55, $19 .byte $00, $1C, $0C, $18, $0E, $16, $03, $F0, $97, $F1, $6F, $7E, $E3, $F9, $F1, $E7, $C1, $1F, $BD, $B2 .byte $55, $E0, $20, $21, $10, $07, $03, $C7, $A0, $7D, $7E, $38, $72, $E3, $F3, $E7, $07, $1F, $FF, $68 .byte $F1, $10, $86, $18, $1C, $47, $0D, $07, $79, $00, $78, $A0, $FE, $F1, $F9, $B8, $3B, $C6, $B5, $E3 .byte $07, $3C, $9E, $8B, $23, $51, $C7, $C0, $4D, $48, $1E, $03, $87, $70, $C7, $39, $E3, $9F, $E3, $D7 .byte $3B, $F6, $C3, $70, $03, $1F, $82, $B1, $00, $F0, $88, $63, $FC, $78, $F0, $7C, $EE, $E3, $1D, $A7 .byte $8F, $83, $8F, $83, $35, $1C, $0F, $9C, $6A, $E0, $98, $30, $2F, $C7, $63, $F8, $4D, $C6, $43, $EE .byte $C4, $67, $55, $E7, $38, $F4, $E6, $C0, $E1, $03, $E0, $1E, $3C, $9E, $18, $79, $F0, $E8, $F1, $93 .byte $17, $C7, $1E, $75, $8E, $1B, $7C, $1C, $D9, $31, $59, $8C, $35, $55, $B1, $70, $6B, $C4, $38, $C3 .byte $B1, $C7, $C7, $1D, $3F, $8E, $71, $E2, $C7, $1C, $37, $38, $46, $E4, $30, $DE, $F0, $43, $E1, $15 .byte $DC, $61, $F8, $E0, $EB, $39, $8B, $8F, $0F, $7E, $86, $7C, $00, $76, $64, $C7, $51, $43, $0C, $7C .byte $EC, $B8, $C3, $CD, $71, $9A, $47, $78, $4E, $FC, $91, $DC, $83, $C7, $05, $4F, $C0, $D3, $31, $67 .byte $38, $1A, $37, $38, $8E, $E3, $1C, $5F, $47, $D5, $D1, $FC, $07, $1F, $B9, $71, $1C, $60, $04, $F0 .byte $01, $7E, $0C, $C8, $E1, $F3, $FB, $B1, $F7, $91, $DD, $8E, $E7, $71, $E1, $00, $46, $C1, $68, $C3 .byte $F1, $C1, $E5, $E0, $C3, $70, $E7, $F8, $71, $E5, $19, $C7, $A9, $1C, $CF, $63, $70, $94, $E3, $91 .byte $C7, $70, $E3, $C0, $CE, $71, $0C, $E4, $F4, $1C, $73, $C7, $93, $E3, $C7, $E9, $C3, $4E, $27, $71 .byte $18, $84, $F8, $C1, $06, $07, $61, $7B, $9C, $E7, $F1, $39, $0E, $D7, $1C, $C7, $5C, $C6, $E7, $C0 .byte $F9, $40, $86, $A5, $1C, $CB, $2C, $CE, $23, $37, $C4, $C7, $4E, $78, $CE, $71, $CD, $61, $2D, $CB .byte $07, $A7, $59, $3C, $71, $16, $33, $16, $83, $65, $19, $27, $8E, $E7, $F8, $5C, $C6, $39, $4E, $CD .byte $EC, $1C, $DC, $70, $38, $66, $59, $CC, $38, $0D, $87, $8F, $89, $9E, $38, $E3, $F8, $74, $E3, $E1 .byte $C6, $E1, $94, $73, $F3, $E0, $C4, $E1, $19, $C7, $07, $87, $55, $0D, $27, $C7, $71, $F0, $49, $8E .byte $E3, $74, $95, $55, $9C, $5D, $1C, $3B, $0C, $57, $59, $06, $1F, $67, $1C, $67, $42, $0F, $3D, $1E .byte $D7, $73, $E0, $34, $53, $F5, $C4, $97, $89, $71, $54, $F1, $54, $D5, $8C, $65, $89, $34, $7D, $30 .byte $7E, $9C, $65, $55, $81, $E3, $D3, $6D, $A3, $E7, $06, $5C, $4C, $F5, $11, $73, $8C, $E3, $24, $EC .byte $38, $F1, $34, $ED, $38, $D6, $58, $55, $55, $55, $55, $55, $55, $55, $55, $55, $65, $D5, $CE, $E5 .byte $55, $55, $55, $55, $55 .align 64
title fmsghdr - far message header and finder ;-------------------------------------------------------------------------- ; ; Microsoft C Compiler Runtime for MS-DOS ; ; (C)Copyright Microsoft Corporation, 1986 ; ;-------------------------------------------------------------------------- ; ; Revision History ; ; 04/17/86 Randy Nevin (adapted from Greg Whitten's version ; of nmsghdr.asm) ; ;-------------------------------------------------------------------------- ?DF= 1 ; this is special for c startup include version.inc ?PLM= 1 ; pascal calling conventions .xlist include cmacros.inc include msdos.inc .list createSeg _TEXT, code, byte, public, CODE, <> createSeg _DATA, data, word, public, DATA, DGROUP createSeg FAR_HDR,fhdr, byte, public, FAR_MSG,FMGROUP createSeg FAR_MSG,fmsg, byte, public, FAR_MSG,FMGROUP createSeg FAR_PAD,fpad, byte, common, FAR_MSG,FMGROUP createSeg FAR_EPAD,fepad, byte, common, FAR_MSG,FMGROUP defGrp DGROUP ; define DGROUP defGrp FMGROUP ; define FMGROUP codeOFFSET equ offset _TEXT: fmsgOFFSET equ offset FMGROUP: sBegin fhdr assumes ds,DGROUP db '<<FMSG>>' stfmsg label byte sEnd SBegin fpad assumes ds,DGROUP dw -1 ; message padding marker sEnd sBegin fepad assumes ds,DGROUP db -1 sEnd sBegin code assumes cs,code assumes ds,DGROUP ;------------------------------------------------------------------------ ; ; char far * pascal __FMSG_TEXT ( messagenumber) ; ; This routine returns a far pointer to the message associated with ; messagenumber. If the message does not exist, then a 0:0 is returned. cProc __FMSG_TEXT,<PUBLIC>,<ds,si,di> ; pascal calling parmW msgt cBegin mov ax,FMGROUP mov ds,ax ; ds = FMGROUP (force it always) push ds pop es mov dx,msgt ; dx = message number mov si,fmsgOFFSET stfmsg ; start of far messages tloop: lodsw ; ax = current message number cmp ax,dx je found ; found it - return address inc ax xchg ax,si jz found ; at end and not found - return 0 xchg di,ax xor ax,ax mov cx,-1 repne scasb ; skip until 00 mov si,di jmp tloop ; try next entry found: xchg ax,si cwd ; zero out dx in case NULL or ax,ax jz notfound mov dx,ds ; remember segment selector notfound: cEnd sEnd end 
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x52eb, %rsi lea addresses_A_ht+0x13fab, %rdi nop nop nop nop cmp %rdx, %rdx mov $7, %rcx rep movsb nop nop nop nop nop sub $55472, %r14 lea addresses_normal_ht+0x1defb, %rsi lea addresses_D_ht+0x1b9fb, %rdi clflush (%rsi) nop cmp $17251, %rax mov $79, %rcx rep movsw nop nop add %rcx, %rcx lea addresses_WC_ht+0xd8ab, %r14 nop nop and $23395, %rdx mov $0x6162636465666768, %rsi movq %rsi, %xmm2 movups %xmm2, (%r14) nop nop sub $58673, %r14 lea addresses_normal_ht+0xefab, %rcx nop cmp %r13, %r13 mov (%rcx), %rsi nop cmp $58124, %rdx lea addresses_D_ht+0x174ab, %rsi nop nop nop add %r14, %r14 movl $0x61626364, (%rsi) nop xor $25435, %r13 lea addresses_WT_ht+0xcfab, %rsi lea addresses_normal_ht+0x168b7, %rdi nop nop nop nop nop inc %r11 mov $64, %rcx rep movsw nop nop xor %r11, %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi // Store lea addresses_WC+0x4a2b, %rax nop nop nop nop dec %rbx mov $0x5152535455565758, %r15 movq %r15, (%rax) nop nop nop nop sub $47460, %r15 // Load lea addresses_WC+0x1c7ab, %rdx nop nop nop nop nop add $14028, %rsi mov (%rdx), %r15w nop nop nop inc %rsi // Store lea addresses_PSE+0x18f6b, %rbx nop nop nop nop add %r11, %r11 movw $0x5152, (%rbx) nop add $52607, %rsi // Store lea addresses_normal+0xf4ab, %rdi dec %rdx mov $0x5152535455565758, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%rdi) nop nop nop nop inc %r11 // Store lea addresses_WC+0x1c7ab, %rdi clflush (%rdi) dec %r15 movl $0x51525354, (%rdi) nop nop nop nop sub %rbx, %rbx // Store lea addresses_WC+0x1c7ab, %rdi nop xor $49991, %rdx mov $0x5152535455565758, %r11 movq %r11, (%rdi) nop nop nop xor %rax, %rax // REPMOV lea addresses_PSE+0xf1ab, %rsi lea addresses_WC+0x191ab, %rdi clflush (%rsi) nop nop nop nop nop sub $9325, %rax mov $99, %rcx rep movsb nop nop nop cmp $36322, %rsi // REPMOV lea addresses_WC+0x1c7ab, %rsi lea addresses_WC+0x1c7ab, %rdi clflush (%rdi) nop nop nop nop nop xor %rax, %rax mov $125, %rcx rep movsq nop nop nop sub $41072, %rdx // Store lea addresses_UC+0x47ab, %rdi nop nop nop nop xor %rax, %rax mov $0x5152535455565758, %r11 movq %r11, %xmm0 vmovups %ymm0, (%rdi) nop nop add %rsi, %rsi // Store lea addresses_WT+0x86ab, %rdx nop xor %rsi, %rsi mov $0x5152535455565758, %rcx movq %rcx, %xmm0 movups %xmm0, (%rdx) nop nop nop inc %rax // Store lea addresses_PSE+0x2793, %rcx nop nop nop nop cmp %rax, %rax mov $0x5152535455565758, %rdx movq %rdx, %xmm3 vmovups %ymm3, (%rcx) and $61521, %r15 // Faulty Load lea addresses_WC+0x1c7ab, %rcx cmp %r15, %r15 movb (%rcx), %dl lea oracles, %rsi and $0xff, %rdx shlq $12, %rdx mov (%rsi,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WC', 'size': 8, 'AVXalign': False}} {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_PSE', 'size': 2, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 8, 'AVXalign': False}} {'src': {'type': 'addresses_PSE', 'congruent': 6, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_WC', 'congruent': 0, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC', 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_UC', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_WT', 'size': 16, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_PSE', 'size': 32, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 1, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}} {'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}} {'src': {'same': False, 'congruent': 11, 'NT': True, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': True}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
; A285077: Positions of 0 in A285076; complement of A285078. ; 2,3,5,7,8,10,12,13,15,17,19,20,22,24,25,27,29,31,32,34,36,37,39,41,42,44,46,48,49,51,53,54,56,58,60,61,63,65,66,68,70,71,73,75,77,78,80,82,83,85,87,89,90,92,94,95,97,99,101,102,104,106,107,109,111,112,114,116,118,119,121,123,124,126,128,130,131,133,135,136,138,140,141,143,145,147,148,150,152,153,155,157,159,160,162,164,165,167,169,171,172,174,176,177,179,181,182,184,186,188,189,191,193,194,196,198,200,201,203,205,206,208,210,211,213,215,217,218,220,222,223,225,227,229,230,232,234,235,237,239,240,242,244,246,247,249,251,252,254,256,258,259,261,263,264,266,268,270,271,273,275,276,278,280,281,283,285,287,288,290,292,293,295,297,299,300,302,304,305,307,309,310,312,314,316,317,319,321,322,324,326,328,329,331,333,334,336,338,340,341,343,345,346,348,350,351,353,355,357,358,360,362,363,365,367,369,370,372,374,375,377,379,380,382,384,386,387,389,391,392,394,396,398,399,401,403,404,406,408,409,411,413,415,416,418,420,421,423,425,427 mov $2,$0 pow $0,2 div $0,2 lpb $0,1 add $1,1 sub $0,$1 sub $0,$1 trn $0,1 lpe add $1,2 add $1,$2
/* PURPOSE: (Data recording access functions) PROGRAMMERS: (((Robert W. Bailey) (LinCom Corp) (3/96) (SES upgrades) ((Alex Lin) (NASA) (April 2009) (--) (c++ port))) */ #include "trick/data_record_proto.h" #include "trick/DataRecordDispatcher.hh" #include "trick/DataRecordGroup.hh" extern Trick::DataRecordDispatcher * the_drd ; extern "C" int dr_remove_files() { if ( the_drd != NULL ) { return the_drd->remove_files() ; } return -1 ; } extern "C" int dr_enable() { if ( the_drd != NULL ) { return the_drd->enable() ; } return -1 ; } extern "C" int dr_enable_group( const char * in_name ) { if ( the_drd != NULL ) { return the_drd->enable( in_name ) ; } return -1 ; } extern "C" int dr_disable() { if ( the_drd != NULL ) { return the_drd->disable() ; } return -1 ; } extern "C" int dr_disable_group( const char * in_name ) { if ( the_drd != NULL ) { return the_drd->disable( in_name ) ; } return -1 ; } extern "C" int dr_record_now_group( const char * in_name ) { if ( the_drd != NULL ) { return the_drd->record_now_group( in_name ) ; } return -1 ; } extern "C" int add_data_record_group( Trick::DataRecordGroup * in_group, Trick::DR_Buffering buffering ) { if ( the_drd != NULL ) { return the_drd->add_group(in_group, buffering) ; } return -1 ; } extern "C" int remove_data_record_group( Trick::DataRecordGroup * in_group ) { if ( the_drd != NULL ) { return the_drd->remove_group(in_group) ; } return -1 ; } extern "C" void remove_all_data_record_groups() { the_drd->remove_all_groups() ; } extern "C" Trick::DataRecordGroup * get_data_record_group( std::string in_name ) { if ( the_drd != NULL ) { return the_drd->get_group(in_name) ; } return NULL ; }
; A025777: Expansion of 1/((1-x)*(1-x^5)*(1-x^7)). ; Submitted by Jamie Morken(s2) ; 1,1,1,1,1,2,2,3,3,3,4,4,5,5,6,7,7,8,8,9,10,11,12,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,31,32,34,35,36,38,39,41,42,44,46,47,49,50,52,54,56,58,59,61,63,65,67,69,71,73,75,77,79,81,84 mov $1,$0 mul $0,2 add $1,13 mul $0,$1 div $0,140 add $0,1
; ----------------------------------------------------------------------------- ; Decompress raw LZSA1 block. Create one with lzsa -r <original_file> <compressed_file> ; ; in: ; * LZSA_SRC_LO and LZSA_SRC_HI contain the compressed raw block address ; * LZSA_DST_LO and LZSA_DST_HI contain the destination buffer address ; ; out: ; * LZSA_DST_LO and LZSA_DST_HI contain the last decompressed byte address, +1 ; ; ----------------------------------------------------------------------------- ; Backward decompression is also supported, use lzsa -r -b <original_file> <compressed_file> ; To use it, also define BACKWARD_DECOMPRESS=1 before including this code! ; ; in: ; * LZSA_SRC_LO/LZSA_SRC_HI must contain the address of the last byte of compressed data ; * LZSA_DST_LO/LZSA_DST_HI must contain the address of the last byte of the destination buffer ; ; out: ; * LZSA_DST_LO/LZSA_DST_HI contain the last decompressed byte address, -1 ; ; ----------------------------------------------------------------------------- ; ; Copyright (C) 2019 Emmanuel Marty, Peter Ferrie ; ; This software is provided 'as-is', without any express or implied ; warranty. In no event will the authors be held liable for any damages ; arising from the use of this software. ; ; Permission is granted to anyone to use this software for any purpose, ; including commercial applications, and to alter it and redistribute it ; freely, subject to the following restrictions: ; ; 1. The origin of this software must not be misrepresented; you must not ; claim that you wrote the original software. If you use this software ; in a product, an acknowledgment in the product documentation would be ; appreciated but is not required. ; 2. Altered source versions must be plainly marked as such, and must not be ; misrepresented as being the original software. ; 3. This notice may not be removed or altered from any source distribution. ; ----------------------------------------------------------------------------- DECOMPRESS_LZSA1_FAST LDY #$00 DECODE_TOKEN JSR GETSRC ; read token byte: O|LLL|MMMM PHA ; preserve token on stack AND #$70 ; isolate literals count BEQ NO_LITERALS ; skip if no literals to copy CMP #$70 ; LITERALS_RUN_LEN? BNE PREPARE_COPY_LITERALS ; if not, count is directly embedded in token JSR GETSRC ; get extra byte of variable literals count ; the carry is always set by the CMP above ; GETSRC doesn't change it SBC #$F9 ; (LITERALS_RUN_LEN) BCC PREPARE_COPY_LITERALS_DIRECT BEQ LARGE_VARLEN_LITERALS ; if adding up to zero, go grab 16-bit count JSR GETSRC ; get single extended byte of variable literals count INY ; add 256 to literals count BCS PREPARE_COPY_LITERALS_DIRECT ; (*like JMP PREPARE_COPY_LITERALS_DIRECT but shorter) LARGE_VARLEN_LITERALS ; handle 16 bits literals count ; literals count = directly these 16 bits JSR GETLARGESRC ; grab low 8 bits in X, high 8 bits in A TAY ; put high 8 bits in Y TXA BCS PREPARE_COPY_LARGE_LITERALS ; (*like JMP PREPARE_COPY_LITERALS_DIRECT but shorter) PREPARE_COPY_LITERALS TAX LDA SHIFT_TABLE-1,X ; shift literals length into place ; -1 because position 00 is reserved PREPARE_COPY_LITERALS_DIRECT TAX PREPARE_COPY_LARGE_LITERALS BEQ COPY_LITERALS INY COPY_LITERALS JSR GETPUT ; copy one byte of literals DEX BNE COPY_LITERALS DEY BNE COPY_LITERALS NO_LITERALS PLA ; retrieve token from stack PHA ; preserve token again BMI GET_LONG_OFFSET ; $80: 16 bit offset JSR GETSRC ; get 8 bit offset from stream in A TAX ; save for later LDA #$FF ; high 8 bits BNE GOT_OFFSET ; go prepare match ; (*like JMP GOT_OFFSET but shorter) SHORT_VARLEN_MATCHLEN JSR GETSRC ; get single extended byte of variable match len INY ; add 256 to match length PREPARE_COPY_MATCH TAX PREPARE_COPY_MATCH_Y TXA BEQ COPY_MATCH_LOOP INY COPY_MATCH_LOOP LDA $AAAA ; get one byte of backreference JSR PUTDST ; copy to destination !ifdef BACKWARD_DECOMPRESS { ; Backward decompression -- put backreference bytes backward LDA COPY_MATCH_LOOP+1 BEQ GETMATCH_ADJ_HI GETMATCH_DONE DEC COPY_MATCH_LOOP+1 } else { ; Forward decompression -- put backreference bytes forward INC COPY_MATCH_LOOP+1 BEQ GETMATCH_ADJ_HI GETMATCH_DONE } DEX BNE COPY_MATCH_LOOP DEY BNE COPY_MATCH_LOOP BEQ DECODE_TOKEN ; (*like JMP DECODE_TOKEN but shorter) !ifdef BACKWARD_DECOMPRESS { GETMATCH_ADJ_HI DEC COPY_MATCH_LOOP+2 JMP GETMATCH_DONE } else { GETMATCH_ADJ_HI INC COPY_MATCH_LOOP+2 JMP GETMATCH_DONE } GET_LONG_OFFSET ; handle 16 bit offset: JSR GETLARGESRC ; grab low 8 bits in X, high 8 bits in A GOT_OFFSET !ifdef BACKWARD_DECOMPRESS { ; Backward decompression - substract match offset STA OFFSHI ; store high 8 bits of offset STX OFFSLO SEC ; substract dest - match offset LDA PUTDST+1 OFFSLO = *+1 SBC #$AA ; low 8 bits STA COPY_MATCH_LOOP+1 ; store back reference address LDA PUTDST+2 OFFSHI = *+1 SBC #$AA ; high 8 bits STA COPY_MATCH_LOOP+2 ; store high 8 bits of address SEC } else { ; Forward decompression - add match offset STA OFFSHI ; store high 8 bits of offset TXA CLC ; add dest + match offset ADC PUTDST+1 ; low 8 bits STA COPY_MATCH_LOOP+1 ; store back reference address OFFSHI = *+1 LDA #$AA ; high 8 bits ADC PUTDST+2 STA COPY_MATCH_LOOP+2 ; store high 8 bits of address } PLA ; retrieve token from stack again AND #$0F ; isolate match len (MMMM) ADC #$02 ; plus carry which is always set by the high ADC CMP #$12 ; MATCH_RUN_LEN? BCC PREPARE_COPY_MATCH ; if not, count is directly embedded in token JSR GETSRC ; get extra byte of variable match length ; the carry is always set by the CMP above ; GETSRC doesn't change it SBC #$EE ; add MATCH_RUN_LEN and MIN_MATCH_SIZE to match length BCC PREPARE_COPY_MATCH BNE SHORT_VARLEN_MATCHLEN ; Handle 16 bits match length JSR GETLARGESRC ; grab low 8 bits in X, high 8 bits in A TAY ; put high 8 bits in Y ; large match length with zero high byte? BNE PREPARE_COPY_MATCH_Y ; if not, continue DECOMPRESSION_DONE RTS SHIFT_TABLE !BYTE $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 !BYTE $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01 !BYTE $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02 !BYTE $03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03 !BYTE $04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04,$04 !BYTE $05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05,$05 !BYTE $06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06,$06 !BYTE $07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07 !ifdef BACKWARD_DECOMPRESS { ; Backward decompression -- get and put bytes backward GETPUT JSR GETSRC PUTDST LZSA_DST_LO = *+1 LZSA_DST_HI = *+2 STA $AAAA LDA PUTDST+1 BEQ PUTDST_ADJ_HI DEC PUTDST+1 RTS PUTDST_ADJ_HI DEC PUTDST+2 DEC PUTDST+1 RTS GETLARGESRC JSR GETSRC ; grab low 8 bits TAX ; move to X ; fall through grab high 8 bits GETSRC LZSA_SRC_LO = *+1 LZSA_SRC_HI = *+2 LDA $AAAA PHA LDA GETSRC+1 BEQ GETSRC_ADJ_HI DEC GETSRC+1 PLA RTS GETSRC_ADJ_HI DEC GETSRC+2 DEC GETSRC+1 PLA RTS } else { ; Forward decompression -- get and put bytes forward GETPUT JSR GETSRC PUTDST LZSA_DST_LO = *+1 LZSA_DST_HI = *+2 STA $AAAA INC PUTDST+1 BEQ PUTDST_ADJ_HI RTS PUTDST_ADJ_HI INC PUTDST+2 RTS GETLARGESRC JSR GETSRC ; grab low 8 bits TAX ; move to X ; fall through grab high 8 bits GETSRC LZSA_SRC_LO = *+1 LZSA_SRC_HI = *+2 LDA $AAAA INC GETSRC+1 BEQ GETSRC_ADJ_HI RTS GETSRC_ADJ_HI INC GETSRC+2 RTS }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: seriesHighLow.asm AUTHOR: Chris Boyke ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- cdb 6/15/92 Initial version. DESCRIPTION: $Id: seriesHighLow.asm,v 1.1 97/04/04 17:47:08 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HighLowRealize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: PASS: *ds:si = HighLowClass object ds:di = HighLowClass instance data es = segment of HihLowClass RETURN: DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- cdb 6/15/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HighLowRealize method dynamic HighLowClass, MSG_CHART_OBJECT_REALIZE uses ax,cx,dx locals local SeriesDrawLocalVars .enter inherit call SeriesCreateGString mov di, locals.SDLV_gstate ; Draw line from series 0 to series 1 mov dx, locals.SDLV_categoryNum clr cl ; series 0 call SeriesGetDataPointPosition ; ax, bx jc abort push ax, bx inc cl call SeriesGetDataPointPosition pop cx, dx jc abort call GrDrawLine ; For series 2, draw a tick off to the left cmp locals.SDLV_seriesCount, 2 jle setIt mov cl, 2 mov dx, locals.SDLV_categoryNum call SeriesGetDataPointPosition jc setIt mov cx, ax mov dx, bx sub ax, MARKER_STD_SIZE/2 call GrDrawLine ; for series 3, draw a tick off to the right cmp locals.SDLV_seriesCount, 3 jle setIt mov cl, 3 mov dx, locals.SDLV_categoryNum call SeriesGetDataPointPosition jc setIt mov cx, ax mov dx, bx add ax, MARKER_STD_SIZE/2 call GrDrawLine setIt: mov cx, CODT_PICTURE call ChartObjectDualGetGrObj call SeriesSetGrObjGString mov cx, CODT_PICTURE call ChartObjectDualSetGrObj done: inc locals.SDLV_categoryNum .leave mov di, offset HighLowClass GOTO ObjCallSuperNoLock abort: push si clr di ;di <- no GState mov si, locals.SDLV_gstate mov dl, GSKT_KILL_DATA call GrDestroyGString pop si mov cx, CODT_PICTURE call ChartObjectDualClearGrObj jmp done HighLowRealize endm
#include <marnav/nmea/rsd.hpp> #include <marnav/nmea/io.hpp> namespace marnav { namespace nmea { constexpr sentence_id rsd::ID; constexpr const char * rsd::TAG; rsd::rsd() : sentence(ID, TAG, talker_id::integrated_instrumentation) , unknowns_({{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}) { } rsd::rsd(talker talk, fields::const_iterator first, fields::const_iterator last) : sentence(ID, TAG, talk) { if (std::distance(first, last) != 13) throw std::invalid_argument{"invalid number of fields in rsd"}; for (decltype(unknowns_.size()) i = 0; i < unknowns_.size(); ++i) read(*(first + i), unknowns_[i]); read(*(first + 8), cursor_range_); read(*(first + 9), cursor_bearing_); read(*(first + 10), range_scale_); read(*(first + 11), range_unit_); read(*(first + 12), unknown_); } void rsd::set_cursor(double range, double bearing) noexcept { cursor_range_ = range; cursor_bearing_ = bearing; } void rsd::set_range(double scale, char unit) noexcept { range_scale_ = scale; range_unit_ = unit; } void rsd::append_data_to(std::string & s) const { for (auto const & t : unknowns_) append(s, to_string(t)); append(s, to_string(cursor_range_)); append(s, to_string(cursor_bearing_)); append(s, to_string(range_scale_)); append(s, to_string(range_unit_)); append(s, to_string(unknown_)); } } }
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. #if (defined(_WIN32) || defined(__MINGW32__)) && !defined(__CYGWIN__) && !defined(__CYGWIN32) # define PLATFORM_WINDOWS 1 #endif #include <ctype.h> // for isspace() #include <stdlib.h> // for getenv() #include <stdio.h> // for snprintf(), sscanf() #include <string.h> // for memmove(), memchr(), etc. #include <fcntl.h> // for open() #include <errno.h> // for errno #ifdef HAVE_UNISTD_H #include <unistd.h> // for read() #endif #if defined __MACH__ // Mac OS X, almost certainly #include <sys/types.h> #include <sys/sysctl.h> // how we figure out numcpu's on OS X #elif defined __FreeBSD__ #include <sys/sysctl.h> #elif defined __sun__ // Solaris #include <procfs.h> // for, e.g., prmap_t #elif defined(PLATFORM_WINDOWS) #include <process.h> // for getpid() (actually, _getpid()) #include <shlwapi.h> // for SHGetValueA() #include <tlhelp32.h> // for Module32First() #endif #include <mutex> #include <thread> #include <gflags/gflags.h> #include <glog/logging.h> #include "yb/gutil/casts.h" #include "yb/gutil/dynamic_annotations.h" // for RunningOnValgrind #include "yb/gutil/macros.h" #include "yb/gutil/sysinfo.h" #include "yb/gutil/walltime.h" #include "yb/util/logging.h" DEFINE_int32(num_cpus, 0, "Number of CPU cores used in calculations"); // This isn't in the 'base' namespace in tcmallc. But, tcmalloc // exports these functions, so we need to namespace them to avoid // the conflict. namespace base { // ---------------------------------------------------------------------- // CyclesPerSecond() // NumCPUs() // It's important this not call malloc! -- they may be called at // global-construct time, before we've set up all our proper malloc // hooks and such. // ---------------------------------------------------------------------- static double cpuinfo_cycles_per_second = 1.0; // 0.0 might be dangerous static int cpuinfo_num_cpus = 1; // Conservative guess static int cpuinfo_max_cpu_index = -1; void SleepForNanoseconds(int64_t nanoseconds) { // Sleep for nanosecond duration struct timespec sleep_time; sleep_time.tv_sec = nanoseconds / 1000 / 1000 / 1000; sleep_time.tv_nsec = (nanoseconds % (1000 * 1000 * 1000)); // Ignore signals and wait for the full interval to elapse. while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {} } void SleepForMilliseconds(int64_t milliseconds) { SleepForNanoseconds(milliseconds * 1000 * 1000); } // Helper function estimates cycles/sec by observing cycles elapsed during // sleep(). Using small sleep time decreases accuracy significantly. static int64 EstimateCyclesPerSecond(const int estimate_time_ms) { CHECK_GT(estimate_time_ms, 0); if (estimate_time_ms <= 0) return 1; double multiplier = 1000.0 / estimate_time_ms; // scale by this much const int64 start_ticks = CycleClock::Now(); SleepForMilliseconds(estimate_time_ms); const int64 guess = static_cast<int64>(multiplier * (CycleClock::Now() - start_ticks)); return guess; } // ReadIntFromFile is only called on linux and cygwin platforms. #if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__) // Slurp a file with a single read() call into 'buf'. This is only safe to use on small // files in places like /proc where we are guaranteed not to get a partial read. // Any remaining bytes in the buffer are zeroed. // // 'buflen' must be more than large enough to hold the whole file, or else this will // issue a FATAL error. static bool SlurpSmallTextFile(const char* file, char* buf, int buflen) { bool ret = false; int fd = open(file, O_RDONLY); if (fd == -1) return ret; memset(buf, '\0', buflen); auto n = read(fd, buf, buflen - 1); CHECK_NE(n, buflen - 1) << "buffer of len " << buflen << " not large enough to store " << "contents of " << file; if (n > 0) { ret = true; } close(fd); return ret; } // Helper function for reading an int from a file. Returns true if successful // and the memory location pointed to by value is set to the value read. static bool ReadIntFromFile(const char *file, int *value) { char line[1024]; if (!SlurpSmallTextFile(file, line, arraysize(line))) { return false; } char* err; const auto temp_value = strtol(line, &err, 10); if (line[0] != '\0' && (*err == '\n' || *err == '\0')) { *value = narrow_cast<int>(temp_value); return true; } return false; } static int ReadMaxCPUIndex() { char buf[1024]; CHECK(SlurpSmallTextFile("/sys/devices/system/cpu/present", buf, arraysize(buf))); // On a single-core machine, 'buf' will contain the string '0' with a newline. if (strcmp(buf, "0\n") == 0) { return 0; } // On multi-core, it will have a CPU range like '0-7'. CHECK_EQ(0, memcmp(buf, "0-", 2)) << "bad list of possible CPUs: " << buf; char* max_cpu_str = &buf[2]; char* err; auto val = strtol(max_cpu_str, &err, 10); CHECK(*err == '\n' || *err == '\0') << "unable to parse max CPU index from: " << buf; return narrow_cast<int>(val); } #endif // WARNING: logging calls back to InitializeSystemInfo() so it must // not invoke any logging code. Also, InitializeSystemInfo() can be // called before main() -- in fact it *must* be since already_called // isn't protected -- before malloc hooks are properly set up, so // we make an effort not to call any routines which might allocate // memory. static void InitializeSystemInfo() { bool saw_mhz = false; if (YbRunningOnValgrind()) { // Valgrind may slow the progress of time artificially (--scale-time=N // option). We thus can't rely on CPU Mhz info stored in /sys or /proc // files. Thus, actually measure the cps. cpuinfo_cycles_per_second = EstimateCyclesPerSecond(100); saw_mhz = true; } #if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__) char line[1024]; char* err; int freq; // If the kernel is exporting the tsc frequency use that. There are issues // where cpuinfo_max_freq cannot be relied on because the BIOS may be // exporintg an invalid p-state (on x86) or p-states may be used to put the // processor in a new mode (turbo mode). Essentially, those frequencies // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as // well. if (!saw_mhz && ReadIntFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) { // The value is in kHz (as the file name suggests). For example, on a // 2GHz warpstation, the file contains the value "2000000". cpuinfo_cycles_per_second = freq * 1000.0; saw_mhz = true; } // If CPU scaling is in effect, we want to use the *maximum* frequency, // not whatever CPU speed some random processor happens to be using now. if (!saw_mhz && ReadIntFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", &freq)) { // The value is in kHz. For example, on a 2GHz machine, the file // contains the value "2000000". cpuinfo_cycles_per_second = freq * 1000.0; saw_mhz = true; } // Read /proc/cpuinfo for other values, and if there is no cpuinfo_max_freq. const char* pname = "/proc/cpuinfo"; int fd = open(pname, O_RDONLY); if (fd == -1) { PLOG(FATAL) << "Unable to read CPU info from /proc. procfs must be mounted."; } double bogo_clock = 1.0; bool saw_bogo = false; int num_cpus = 0; line[0] = line[1] = '\0'; ssize_t chars_read = 0; do { // we'll exit when the last read didn't read anything // Move the next line to the beginning of the buffer const auto oldlinelen = strlen(line); if (sizeof(line) == oldlinelen + 1) // oldlinelen took up entire line line[0] = '\0'; else // still other lines left to save memmove(line, line + oldlinelen+1, sizeof(line) - (oldlinelen+1)); // Terminate the new line, reading more if we can't find the newline char* newline = strchr(line, '\n'); if (newline == NULL) { const auto linelen = strlen(line); const int64_t bytes_to_read = sizeof(line)-1 - linelen; CHECK_GT(bytes_to_read, 0); // because the memmove recovered >=1 bytes chars_read = read(fd, line + linelen, bytes_to_read); line[linelen + chars_read] = '\0'; newline = strchr(line, '\n'); } if (newline != NULL) *newline = '\0'; #if defined(__powerpc__) || defined(__ppc__) // PowerPC cpus report the frequency in "clock" line if (strncasecmp(line, "clock", sizeof("clock")-1) == 0) { const char* freqstr = strchr(line, ':'); if (freqstr) { // PowerPC frequencies are only reported as MHz (check 'show_cpuinfo' // function at arch/powerpc/kernel/setup-common.c) char *endp = strstr(line, "MHz"); if (endp) { *endp = 0; cpuinfo_cycles_per_second = strtod(freqstr+1, &err) * 1000000.0; if (freqstr[1] != '\0' && *err == '\0' && cpuinfo_cycles_per_second > 0) saw_mhz = true; } } #else // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only // accept postive values. Some environments (virtual machines) report zero, // which would cause infinite looping in WallTime_Init. if (!saw_mhz && strncasecmp(line, "cpu MHz", sizeof("cpu MHz")-1) == 0) { const char* freqstr = strchr(line, ':'); if (freqstr) { cpuinfo_cycles_per_second = strtod(freqstr+1, &err) * 1000000.0; if (freqstr[1] != '\0' && *err == '\0' && cpuinfo_cycles_per_second > 0) saw_mhz = true; } } else if (strncasecmp(line, "bogomips", sizeof("bogomips")-1) == 0) { const char* freqstr = strchr(line, ':'); if (freqstr) { bogo_clock = strtod(freqstr+1, &err) * 1000000.0; if (freqstr[1] != '\0' && *err == '\0' && bogo_clock > 0) saw_bogo = true; } #endif } else if (strncasecmp(line, "processor", sizeof("processor")-1) == 0) { num_cpus++; // count up every time we see an "processor :" entry } } while (chars_read > 0); close(fd); if (!saw_mhz) { if (saw_bogo) { // If we didn't find anything better, we'll use bogomips, but // we're not happy about it. cpuinfo_cycles_per_second = bogo_clock; } else { // If we don't even have bogomips, we'll use the slow estimation. cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); } } if (cpuinfo_cycles_per_second == 0.0) { cpuinfo_cycles_per_second = 1.0; // maybe unnecessary, but safe } if (num_cpus > 0) { cpuinfo_num_cpus = num_cpus; } cpuinfo_max_cpu_index = ReadMaxCPUIndex(); #elif defined __FreeBSD__ // For this sysctl to work, the machine must be configured without // SMP, APIC, or APM support. hz should be 64-bit in freebsd 7.0 // and later. Before that, it's a 32-bit quantity (and gives the // wrong answer on machines faster than 2^32 Hz). See // http://lists.freebsd.org/pipermail/freebsd-i386/2004-November/001846.html // But also compare FreeBSD 7.0: // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG70#L223 // 231 error = sysctl_handle_quad(oidp, &freq, 0, req); // To FreeBSD 6.3 (it's the same in 6-STABLE): // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG6#L131 // 139 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req); #if __FreeBSD__ >= 7 uint64_t hz = 0; #else unsigned int hz = 0; #endif size_t sz = sizeof(hz); const char *sysctl_path = "machdep.tsc_freq"; if ( sysctlbyname(sysctl_path, &hz, &sz, NULL, 0) != 0 ) { fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", sysctl_path, strerror(errno)); cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); } else { cpuinfo_cycles_per_second = hz; } // TODO(csilvers): also figure out cpuinfo_num_cpus #elif defined(PLATFORM_WINDOWS) # pragma comment(lib, "shlwapi.lib") // for SHGetValue() // In NT, read MHz from the registry. If we fail to do so or we're in win9x // then make a crude estimate. OSVERSIONINFO os; os.dwOSVersionInfoSize = sizeof(os); DWORD data, data_size = sizeof(data); if (GetVersionEx(&os) && os.dwPlatformId == VER_PLATFORM_WIN32_NT && SUCCEEDED(SHGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "~MHz", NULL, &data, &data_size))) { cpuinfo_cycles_per_second = static_cast<int64>(data) * (1000 * 1000); // was mhz } else { cpuinfo_cycles_per_second = EstimateCyclesPerSecond(500); // TODO <500? } // Get the number of processors. SYSTEM_INFO info; GetSystemInfo(&info); cpuinfo_num_cpus = info.dwNumberOfProcessors; #elif defined(__MACH__) && defined(__APPLE__) // returning "mach time units" per second. the current number of elapsed // mach time units can be found by calling uint64 mach_absolute_time(); // while not as precise as actual CPU cycles, it is accurate in the face // of CPU frequency scaling and multi-cpu/core machines. // Our mac users have these types of machines, and accuracy // (i.e. correctness) trumps precision. // See cycleclock.h: CycleClock::Now(), which returns number of mach time // units on Mac OS X. mach_timebase_info_data_t timebase_info; mach_timebase_info(&timebase_info); double mach_time_units_per_nanosecond = static_cast<double>(timebase_info.denom) / static_cast<double>(timebase_info.numer); cpuinfo_cycles_per_second = mach_time_units_per_nanosecond * 1e9; int num_cpus = 0; size_t size = sizeof(num_cpus); int numcpus_name[] = { CTL_HW, HW_NCPU }; if (::sysctl(numcpus_name, arraysize(numcpus_name), &num_cpus, &size, nullptr, 0) == 0 && (size == sizeof(num_cpus))) cpuinfo_num_cpus = num_cpus; #else // Generic cycles per second counter cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); #endif int std_num_cpus = std::thread::hardware_concurrency(); if (std_num_cpus > 0) { cpuinfo_num_cpus = std_num_cpus; } // On platforms where we can't determine the max CPU index, just use the // number of CPUs. This might break if CPUs are taken offline, but // better than a wild guess. if (cpuinfo_max_cpu_index < 0) { cpuinfo_max_cpu_index = cpuinfo_num_cpus - 1; } } std::once_flag init_sys_info_flag; double CyclesPerSecond(void) { std::call_once(init_sys_info_flag, &InitializeSystemInfo); return cpuinfo_cycles_per_second; } int NumCPUs(void) { std::call_once(init_sys_info_flag, &InitializeSystemInfo); if (FLAGS_num_cpus != 0) { return FLAGS_num_cpus; } else { return cpuinfo_num_cpus; } } int RawNumCPUs(void) { std::call_once(init_sys_info_flag, &InitializeSystemInfo); return cpuinfo_num_cpus; } int MaxCPUIndex(void) { std::call_once(init_sys_info_flag, &InitializeSystemInfo); return cpuinfo_max_cpu_index; } } // namespace base
; A127752: Row sums of inverse of number triangle A(n,k) = 1/(3n+1) if k <= n <= 2k, 0 otherwise. ; 1,4,3,7,3,6,3,10,3,6,3,9,3,6,3,13,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,16,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,19,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,18,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,22,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,18,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,21,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,18,3,6,3,9,3,6,3,12,3,6,3,9,3,6,3,15,3,6,3,9,3,6,3,12,3,6 mov $4,$0 mov $5,2 lpb $5,1 mov $0,$4 sub $5,1 add $0,$5 sub $0,1 mov $2,$0 mov $6,1 lpb $0,1 mul $0,4 add $0,1 sub $0,$2 sub $2,1 div $2,2 add $6,$0 mov $0,$2 lpe mov $3,$5 lpb $3,1 mov $1,$6 sub $3,1 lpe lpe lpb $4,1 sub $1,$6 mov $4,0 lpe
/*========================================================================= Program: Visualization Toolkit Module: vtkTreeReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTreeReader.h" #include "vtkByteSwap.h" #include "vtkCellArray.h" #include "vtkFieldData.h" #include "vtkTree.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include "vtkStreamingDemandDrivenPipeline.h" vtkCxxRevisionMacro(vtkTreeReader, "1.3"); vtkStandardNewMacro(vtkTreeReader); #ifdef read #undef read #endif //---------------------------------------------------------------------------- vtkTreeReader::vtkTreeReader() { vtkTree *output = vtkTree::New(); this->SetOutput(output); // Releasing data for pipeline parallism. // Filters will know it is empty. output->ReleaseData(); output->Delete(); } //---------------------------------------------------------------------------- vtkTreeReader::~vtkTreeReader() { } //---------------------------------------------------------------------------- vtkTree* vtkTreeReader::GetOutput() { return this->GetOutput(0); } //---------------------------------------------------------------------------- vtkTree* vtkTreeReader::GetOutput(int idx) { return vtkTree::SafeDownCast(this->GetOutputDataObject(idx)); } //---------------------------------------------------------------------------- void vtkTreeReader::SetOutput(vtkTree *output) { this->GetExecutive()->SetOutputData(0, output); } //---------------------------------------------------------------------------- // I do not think this should be here, but I do not want to remove it now. int vtkTreeReader::RequestUpdateExtent( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); int piece, numPieces; piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // make sure piece is valid if (piece < 0 || piece >= numPieces) { return 1; } return 1; } //---------------------------------------------------------------------------- int vtkTreeReader::RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // Return all data in the first piece ... if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkDebugMacro(<<"Reading vtk tree ..."); if(!this->OpenVTKFile() || !this->ReadHeader()) { return 1; } // Read table-specific stuff char line[256]; if(!this->ReadString(line)) { vtkErrorMacro(<<"Data file ends prematurely!"); this->CloseVTKFile(); return 1; } if(strncmp(this->LowerCase(line),"dataset", (unsigned long)7)) { vtkErrorMacro(<< "Unrecognized keyword: " << line); this->CloseVTKFile(); return 1; } if(!this->ReadString(line)) { vtkErrorMacro(<<"Data file ends prematurely!"); this->CloseVTKFile (); return 1; } if(strncmp(this->LowerCase(line),"tree", 4)) { vtkErrorMacro(<< "Cannot read dataset type: " << line); this->CloseVTKFile(); return 1; } vtkTree* const output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int done = 0; while(!done) { if(!this->ReadString(line)) { break; } if(!strncmp(this->LowerCase(line), "field", 5)) { vtkFieldData* const field_data = this->ReadFieldData(); output->SetFieldData(field_data); field_data->Delete(); continue; } if(!strncmp(this->LowerCase(line), "points", 6)) { int point_count = 0; if(!this->Read(&point_count)) { vtkErrorMacro(<<"Cannot read number of points!"); this->CloseVTKFile (); return 1; } this->ReadPoints(output, point_count); continue; } if(!strncmp(this->LowerCase(line), "edges", 4)) { int edge_count = 0; if(!this->Read(&edge_count)) { vtkErrorMacro(<<"Cannot read number of edges!"); this->CloseVTKFile(); return 1; } vtkSmartPointer<vtkMutableDirectedGraph> builder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); // Create all of the tree vertices (number of edges + 1) for(int edge = 0; edge <= edge_count; ++edge) { builder->AddVertex(); } // Reparent the existing vertices so their order and topology match the original int child = 0; int parent = 0; for(int edge = 0; edge != edge_count; ++edge) { if(!(this->Read(&child) && this->Read(&parent))) { vtkErrorMacro(<<"Cannot read edge!"); this->CloseVTKFile(); return 1; } builder->AddEdge(parent, child); } if (!output->CheckedShallowCopy(builder)) { vtkErrorMacro(<<"Edges do not create a valid tree."); this->CloseVTKFile(); return 1; } continue; } if(!strncmp(this->LowerCase(line), "vertex_data", 10)) { int vertex_count = 0; if(!this->Read(&vertex_count)) { vtkErrorMacro(<<"Cannot read number of vertices!"); this->CloseVTKFile (); return 1; } this->ReadVertexData(output, vertex_count); continue; } if(!strncmp(this->LowerCase(line), "edge_data", 9)) { int edge_count = 0; if(!this->Read(&edge_count)) { vtkErrorMacro(<<"Cannot read number of edges!"); this->CloseVTKFile (); return 1; } this->ReadEdgeData(output, edge_count); continue; } vtkErrorMacro(<< "Unrecognized keyword: " << line); } vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and " << output->GetNumberOfEdges() <<" edges.\n"); this->CloseVTKFile (); return 1; } //---------------------------------------------------------------------------- int vtkTreeReader::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree"); return 1; } //---------------------------------------------------------------------------- void vtkTreeReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
db "ACORN@" ; species name db "It attaches itself" next "to a tree branch" next "using the top of" page "its head. Strong" next "winds can make it" next "sometimes fall.@"
; A016838: a(n) = (4n + 3)^2. ; 9,49,121,225,361,529,729,961,1225,1521,1849,2209,2601,3025,3481,3969,4489,5041,5625,6241,6889,7569,8281,9025,9801,10609,11449,12321,13225,14161,15129,16129,17161,18225,19321,20449,21609,22801,24025,25281,26569,27889,29241,30625,32041,33489,34969,36481,38025,39601,41209,42849,44521,46225,47961,49729,51529,53361,55225,57121,59049,61009,63001,65025,67081,69169,71289,73441,75625,77841,80089,82369,84681,87025,89401,91809,94249,96721,99225,101761,104329,106929,109561,112225,114921,117649,120409,123201,126025,128881,131769,134689,137641,140625,143641,146689,149769,152881,156025,159201,162409,165649,168921,172225,175561,178929,182329,185761,189225,192721,196249,199809,203401,207025,210681,214369,218089,221841,225625,229441,233289,237169,241081,245025,249001,253009,257049,261121,265225,269361,273529,277729,281961,286225,290521,294849,299209,303601,308025,312481,316969,321489,326041,330625,335241,339889,344569,349281,354025,358801,363609,368449,373321,378225,383161,388129,393129,398161,403225,408321,413449,418609,423801,429025,434281,439569,444889,450241,455625,461041,466489,471969,477481,483025,488601,494209,499849,505521,511225,516961,522729,528529,534361,540225,546121,552049,558009,564001,570025,576081,582169,588289,594441,600625,606841,613089,619369,625681,632025,638401,644809,651249,657721,664225,670761,677329,683929,690561,697225,703921,710649,717409,724201,731025,737881,744769,751689,758641,765625,772641,779689,786769,793881,801025,808201,815409,822649,829921,837225,844561,851929,859329,866761,874225,881721,889249,896809,904401,912025,919681,927369,935089,942841,950625,958441,966289,974169,982081,990025,998001 mul $0,4 add $0,3 pow $0,2 mov $1,$0
#include <iostream> #include <GL/glut.h> #include <math.h> #include "FrameTimer.h" ///OBJ loader globals GLuint elephant; float elephantrot; ///camera rotation in degrees float angle=0; float angley=0; ///last location of click int lastx; int lasty; ///button boolean float button = false; /// float id; /// the angle resolved into a direction vector float direction[3]={0,0,-1}; /// the inverted position of the camera. float position[3]={0,-2,0}; /// the target position of the camera (not inverted) float target[3]={0,2,8}; /// the strength of the spring. Higher values make the camera more rigid. float spring_strength=0.5; //------------------------------------------------------------------------------- DampenedSpring() // void DampenedSpring(float *CurrentPosition, float *TargetPosition, float *NewPosition, float &dt) { // copy current position into new position just incase we do nothing memcpy(NewPosition,CurrentPosition,sizeof(float)*3); // calculate the displacement between the target and the current position float Displacement[3]; memcpy(Displacement,NewPosition,sizeof(float)*3); Displacement[0] += TargetPosition[0]; Displacement[1] += TargetPosition[1]; Displacement[2] += TargetPosition[2]; // whats the distance between them? float DisplacementLength=sqrt(Displacement[0]*Displacement[0] + Displacement[1]*Displacement[1] + Displacement[2]*Displacement[2] ); float DampConstant=0.00065; // Something v.small to offset 1/ displacement length // Stops small position fluctuations (integration errors probably - since only using euler) if (DisplacementLength<0.001) return; // the strength of the spring increases the further away the camera is from // the target. float SpringMagitude = 10 * DisplacementLength + DampConstant * (1 / DisplacementLength); // Normalise the displacement and scale by the spring magnitude // and the amount of time passed float scalar = (1.0f/DisplacementLength) * SpringMagitude * dt; Displacement[0] *= scalar; Displacement[1] *= scalar; Displacement[2] *= scalar; // move the camera a bit towards the target NewPosition[0] -= Displacement[0]; NewPosition[1] -= Displacement[1]; NewPosition[2] -= Displacement[2]; } void loadObj(const char* fname) { FILE *fp; int read; GLfloat x, y, z; char ch; elephant=glGenLists(1); fp=fopen(fname,"r"); if (!fp) { printf("can't open file %s\n", fname); exit(1); } glPointSize(2.0); glNewList(elephant, GL_COMPILE); { glPushMatrix(); glBegin(GL_POINTS); while(!(feof(fp))) { read=fscanf(fp,"%c %f %f %f",&ch,&x,&y,&z); if(read==4&&ch=='v') { glVertex3f(x,y+2,z); } } glEnd(); } glPopMatrix(); glEndList(); fclose(fp); } void OnInit() { glutSetCursor(GLUT_CURSOR_NONE); InitFrameTimer(); loadObj("data/teapot.obj"); } void OnDisplay() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); // set camera angle glRotatef(angley,direction[2]*2.0f,0,0); glRotatef(angle,0,1,0); // set camera position glTranslatef(position[0],position[1],position[2]); glBegin(GL_LINES); // draw grid for(int i=-10;i<=10;++i) { glVertex3f(i,0,-10); glVertex3f(i,0,10); glVertex3f(10,0,i); glVertex3f(-10,0,i); } glEnd(); //render & rotate teapot glPushMatrix(); glRotatef(elephantrot,0,1,0); glCallList(elephant); elephantrot=elephantrot+0.1; if(elephantrot>360)elephantrot=elephantrot-360; glPopMatrix(); //optional lol text /* glTranslatef(-15,20,0); glScalef(0.1,0.1,0.1); glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, 'l'); glTranslatef(0,0,0); glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, 'o'); glTranslatef(10,0,0); glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, 'l'); */ glutSwapBuffers(); } void OnReshape(int w, int h) { // prevent divide by 0 error when minimised if(w==0) h = 1; glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45,(float)w/h,0.1,100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /// cursor key states bool g_keys[128]={false}; void OnIdle() { // update frame timer SortFrameTimer(); // hold the new position for the camera float NewPosition[3]; // get the frame time float dt = FrameTime(); // calculate the direction vector from the angle direction[0] = sin(angle*3.14159f/180.0f); direction[2] = -cos(angle*3.14159f/180.0f); direction[1] = 0.0f; //move left if (g_keys['a']) { target[0] -= sin((angle+90)*3.14159f/180.0f)*dt*5.0f; target[1] -= direction[1]*dt*5.0f; target[2] -= -cos((angle+90)*3.14159f/180.0f)*dt*5.0f; } // move right if (g_keys['d']) { target[0] -= sin((angle-90)*3.14159f/180.0f)*dt*5.0f; target[1] -= direction[1]*dt*5.0f; target[2] -= -cos((angle-90)*3.14159f/180.0f)*dt*5.0f; } // move forward if (g_keys['w']) { target[0] += direction[0]*dt*5.0f; target[1] += direction[1]*dt*5.0f; target[2] += direction[2]*dt*5.0f; } // move backwards if (g_keys['s']) { target[0] -= direction[0]*dt*5.0f; target[1] -= direction[1]*dt*5.0f; target[2] -= direction[2]*dt*5.0f; } // calculate new position for camera DampenedSpring(position,target,NewPosition,dt); // update the position position[0] = NewPosition[0]; position[1] = NewPosition[1]; position[2] = NewPosition[2]; // redraw the scene glutPostRedisplay(); } // key input void OnKey(unsigned char key,int,int) { g_keys[key]=true; } // mouse input void onMouse(int b, int s, int x, int y){ lastx=x; lasty=y; button = true; } // mouse motion input void onMotion(int x, int y){ int diffx=x-lastx; int diffy=y-lasty; lastx=x; lasty=y; if (button){ angle -= (float) 0.3f * diffx; angley -= (float) 0.3f * diffy; } } // update key press void OnKeyUp(unsigned char key,int,int) { g_keys[key]=false; if (key == ''){ glutDestroyWindow(id); } } //main function int main(int argc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); glutInitWindowSize(640,480); glutInitWindowPosition(100,100); id = glutCreateWindow("Camera v1.3 + .obj loading"); // set glut callbacks glutDisplayFunc(OnDisplay); glutReshapeFunc(OnReshape); // set key callbacks glutKeyboardFunc(OnKey); glutKeyboardUpFunc(OnKeyUp); // set mouse callbacks glutPassiveMotionFunc(onMotion); glutMouseFunc(onMouse); // set idle function glutIdleFunc(OnIdle); // initialize camera OnInit(); glutMainLoop(); }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x76e4, %rdi nop nop nop xor $17934, %r14 mov (%rdi), %r10d nop nop nop nop nop xor $12765, %rcx lea addresses_normal_ht+0xf784, %rbp clflush (%rbp) nop and $48565, %rbx movl $0x61626364, (%rbp) nop nop nop add $27625, %rdi lea addresses_normal_ht+0x78e4, %r10 dec %rdx movl $0x61626364, (%r10) nop nop nop xor $25902, %rdi lea addresses_WT_ht+0x931c, %rdi nop nop nop xor $15719, %rbp mov $0x6162636465666768, %rdx movq %rdx, (%rdi) nop nop nop nop dec %rbx lea addresses_D_ht+0x18404, %rbp nop sub $50164, %rbx mov $0x6162636465666768, %rcx movq %rcx, (%rbp) nop nop and %rdx, %rdx lea addresses_D_ht+0x4e4, %rdi nop nop and $17090, %r14 movups (%rdi), %xmm3 vpextrq $1, %xmm3, %rbp nop nop nop nop nop cmp %rbx, %rbx lea addresses_UC_ht+0xbde4, %rsi lea addresses_WT_ht+0x24e4, %rdi clflush (%rdi) nop nop nop nop xor $34001, %r10 mov $7, %rcx rep movsl nop inc %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r8 push %rax push %rbx push %rcx push %rdi // Store lea addresses_WC+0xb8e4, %rbx nop nop nop nop nop sub $42301, %rdi movl $0x51525354, (%rbx) nop nop nop inc %rcx // Store mov $0x1aa0f500000008e4, %rdi nop nop nop xor %rbx, %rbx mov $0x5152535455565758, %r10 movq %r10, %xmm4 movups %xmm4, (%rdi) nop nop nop nop nop inc %r10 // Store lea addresses_normal+0x1e8e4, %r10 xor %r12, %r12 movl $0x51525354, (%r10) nop nop and $37031, %r10 // Load lea addresses_D+0x1b7e4, %rdi nop and $22627, %r8 movaps (%rdi), %xmm1 vpextrq $0, %xmm1, %rax cmp %rdi, %rdi // Store lea addresses_PSE+0x59e4, %r8 nop nop nop nop nop add $2996, %r12 mov $0x5152535455565758, %rax movq %rax, (%r8) nop nop nop nop nop cmp %rbx, %rbx // Faulty Load lea addresses_WT+0xa0e4, %r8 nop and $60641, %rdi movb (%r8), %r10b lea oracles, %rcx and $0xff, %r10 shlq $12, %r10 mov (%rcx,%r10,1), %r10 pop %rdi pop %rcx pop %rbx pop %rax pop %r8 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 1, 'type': 'addresses_WT', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WC', 'congruent': 10}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_NC', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal', 'congruent': 10}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_D', 'congruent': 5}} {'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 8, 'type': 'addresses_PSE', 'congruent': 7}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT', 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 7}} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 4}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 9}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 0}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 8, 'type': 'addresses_D_ht', 'congruent': 5}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 7}} {'dst': {'same': True, 'congruent': 9, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}} {'39': 5} 39 39 39 39 39 */
// Minimal struct with C-Standard behavior - address-of // Commodore 64 PRG executable file .file [name="struct-21.prg", type="prg", segments="Program"] .segmentdef Program [segments="Basic, Code, Data"] .segmentdef Basic [start=$0801] .segmentdef Code [start=$80d] .segmentdef Data [startAfter="Code"] .segment Basic :BasicUpstart(main) .const SIZEOF_STRUCT_POINT = 2 .const OFFSET_STRUCT_POINT_Y = 1 .label SCREEN = $400 .segment Code main: { .label ptr = point1 .label point1 = 2 // __ma struct Point point1 = { 2, 3 } ldy #SIZEOF_STRUCT_POINT !: lda __0-1,y sta point1-1,y dey bne !- // SCREEN[0] = ptr->x lda.z ptr sta SCREEN // SCREEN[1] = ptr->y lda.z ptr+OFFSET_STRUCT_POINT_Y sta SCREEN+1 // } rts } .segment Data __0: .byte 2, 3
//================================================================================================= /*! // \file src/mathtest/dmatsmatmult/M3x3bMIb.cpp // \brief Source file for the M3x3bMIb dense matrix/sparse matrix multiplication math test // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/IdentityMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatsmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'M3x3bMIb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::StaticMatrix<TypeB,3UL,3UL> M3x3b; typedef blaze::IdentityMatrix<TypeB> MIb; // Creator type definitions typedef blazetest::Creator<M3x3b> CM3x3b; typedef blazetest::Creator<MIb> CMIb; // Running the tests RUN_DMATSMATMULT_OPERATION_TEST( CM3x3b(), CMIb( 3UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
; A054899: a(n) = Sum_{k>0} floor(n/10^k). ; 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26 div $0,10 mul $0,11 mov $1,$0 div $1,10
db DEX_SEEL ; pokedex id db 65, 45, 55, 45, 70 ; hp atk def spd spc db WATER, WATER ; type db 190 ; catch rate db 100 ; base exp INCBIN "gfx/pokemon/front/seel.pic", 0, 1 ; sprite dimensions dw SeelPicFront, SeelPicBack db HEADBUTT, BUBBLE, GROWL, NO_MOVE ; level 1 learnset db GROWTH_MEDIUM_FAST ; growth rate ; tm/hm learnset tmhm TOXIC, COUNTER, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, \ BUBBLEBEAM, WATER_GUN, ICE_BEAM, BLIZZARD, PAY_DAY, \ RAGE, MIMIC, DOUBLE_TEAM, BIDE, SKULL_BASH, \ REST, SUBSTITUTE, SURF, STRENGTH ; end db 0 ; padding
; ; Startup for V-Tech VZ-350/500/700? ; module vz700_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- EXTERN _main ;main() is always external to crt0 code PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) ; 2 columns on left and 2 column on right are lost defc CONSOLE_COLUMNS = 40 defc CONSOLE_ROWS = 24 defc TAR__no_ansifont = 1 defc CRT_KEY_DEL = 12 defc __CPU_CLOCK = 3694700 IF startup = 2 INCLUDE "target/laser500/classic/rom.asm" ELSE INCLUDE "target/laser500/def/maths_mbf.def" INCLUDE "target/laser500/classic/ram.asm" ENDIF ; The extra key rows aren't implemented by Mame, so disable ; scanning of them by default PUBLIC __CLIB_LASER500_SCAN_EXTRA_ROWS IFDEF CLIB_LASER500_SCAN_EXTRA_ROWS defc __CLIB_LASER500_SCAN_EXTRA_ROWS = CLIB_LASER500_SCAN_EXTRA_ROWS ELSE defc __CLIB_LASER500_SCAN_EXTRA_ROWS = 0 ENDIF INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm"
; A008491: Expansion of (1-x^9 ) / (1-x)^9. ; Submitted by Jamie Morken(s4) ; 1,9,45,165,495,1287,3003,6435,12870,24309,43749,75537,125805,202995,318483,487311,729036,1068705,1537965,2176317,3032523,4166175,5649435,7568955,10027986,13148685,17074629,21973545,28040265,35499915,44611347,55670823,69015960,85029945,104146029,126852309,153696807,185292855,222324795,265554003,315825246,374073381,441330405,518732865,607529637,709090083,824912595,956633535,1106036580,1275062481,1465819245,1680592749,1921857795,2192289615,2494775835,2832428907,3208599018,3626887485,4091160645 mov $2,$0 add $0,8 bin $0,8 trn $2,1 bin $2,8 sub $0,$2
; A285197: Expansion of (1-6*x+11*x^2-5*x^3) / ((1-x)*(1-3*x)*(1-3*x+x^2)). ; Submitted by Jamie Morken(s1) ; 1,1,2,6,20,67,221,717,2294,7258,22760,70863,219353,675769,2073674,6342414,19345052,58867195,178779893,542042565,1641058046,4962262306,14989121072,45235277511,136407241265,411058035697,1237981634066,3726531171222,11212544793764,33723901952563,101397557291405,304783958604093,915899884568198,2751752393242474,8265867389585144,24825380058790719,74548863636620297,223836983400570025,672009404213589338,2017333182185696670,6055416001179996716,18175192397863781611,54548993921939812517 mov $2,1 mov $3,1 lpb $0 sub $0,1 add $2,$1 add $1,$3 add $1,$2 mul $3,3 lpe mov $0,$2 div $0,2 add $0,1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r9 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x14258, %rbx nop nop add %r9, %r9 mov $0x6162636465666768, %r13 movq %r13, %xmm1 movups %xmm1, (%rbx) nop nop nop cmp $54496, %rsi lea addresses_UC_ht+0x14350, %rbx cmp $15147, %r13 mov (%rbx), %r11 nop nop nop nop sub %r13, %r13 lea addresses_WT_ht+0x18858, %rsi lea addresses_D_ht+0x14b58, %rdi nop nop cmp $60349, %r13 mov $81, %rcx rep movsl nop nop nop nop inc %rsi lea addresses_normal_ht+0x1df58, %rbx clflush (%rbx) nop nop nop sub $34791, %r13 movb (%rbx), %r11b nop nop nop nop nop xor $50224, %r11 lea addresses_WT_ht+0x7486, %rcx nop nop nop nop and $12355, %r9 mov (%rcx), %r11d nop nop add %rdi, %rdi lea addresses_WT_ht+0xe2d8, %rbx nop nop nop nop nop xor $23600, %rcx mov $0x6162636465666768, %rsi movq %rsi, %xmm5 vmovups %ymm5, (%rbx) nop nop nop nop inc %rcx lea addresses_D_ht+0xde58, %rsi lea addresses_WC_ht+0x5cad, %rdi cmp $57550, %rdx mov $103, %rcx rep movsl xor $57939, %rbx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r15 push %rax push %rsi // Load lea addresses_normal+0x1fd58, %rsi nop nop nop nop and $37040, %r10 movb (%rsi), %r12b nop nop nop nop add %rax, %rax // Store mov $0xeb8, %r12 nop nop cmp $30233, %rsi movl $0x51525354, (%r12) nop nop nop nop and $30360, %r15 // Store lea addresses_WT+0x4278, %rax nop nop nop nop cmp %r10, %r10 mov $0x5152535455565758, %r13 movq %r13, (%rax) add %r10, %r10 // Store lea addresses_UC+0x1a948, %rsi clflush (%rsi) nop nop nop add %r11, %r11 mov $0x5152535455565758, %r10 movq %r10, %xmm3 movups %xmm3, (%rsi) nop nop add %r13, %r13 // Store lea addresses_WT+0x4ff8, %r12 nop cmp $7690, %rax movw $0x5152, (%r12) nop nop add $48126, %r11 // Store lea addresses_normal+0x172fe, %r15 nop nop nop nop nop add %rsi, %rsi movl $0x51525354, (%r15) nop nop nop nop inc %rsi // Faulty Load lea addresses_UC+0x8358, %r15 nop nop nop nop nop sub %r10, %r10 vmovntdqa (%r15), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $1, %xmm3, %r11 lea oracles, %r13 and $0xff, %r11 shlq $12, %r11 mov (%r13,%r11,1), %r11 pop %rsi pop %rax pop %r15 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_P', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC', 'same': True, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 1}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 32, 'NT': True, 'type': 'addresses_UC', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC_ht', 'same': True, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_UC_ht', 'same': True, 'AVXalign': True, 'congruent': 3}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 11}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 0}} {'49': 9942, '00': 2, '46': 11885} 00 46 49 46 49 49 49 49 49 46 46 46 49 46 49 49 46 46 49 49 49 49 49 49 46 46 46 46 49 46 46 46 49 46 46 46 49 49 49 49 49 49 49 49 49 46 49 46 46 46 49 49 49 46 49 49 49 49 49 49 46 49 49 49 49 49 49 49 46 46 46 49 46 49 49 49 46 49 49 46 46 49 49 49 49 49 49 49 46 49 49 46 46 46 46 46 46 49 49 49 46 46 46 49 46 49 46 49 49 49 49 49 49 46 46 46 46 49 46 49 49 49 46 46 46 49 49 49 49 46 46 49 49 46 46 49 49 46 46 49 46 49 49 46 46 49 49 46 46 46 46 46 49 46 46 46 49 46 46 46 49 49 49 49 46 46 49 46 46 46 49 49 49 49 49 46 46 46 49 46 46 46 49 46 49 49 49 49 49 49 49 49 46 46 49 49 46 46 49 46 49 49 49 49 49 49 46 46 46 46 49 49 49 46 49 49 49 49 49 49 49 49 49 49 46 46 49 46 49 46 46 46 49 49 49 49 46 46 46 46 46 46 49 46 46 46 46 49 49 46 46 49 46 46 46 46 46 49 49 49 46 49 49 49 46 49 46 49 49 46 46 49 49 49 49 46 46 49 46 46 46 49 49 49 46 49 46 46 46 46 46 46 46 49 49 49 49 46 46 49 46 49 49 49 46 46 46 49 49 46 46 49 49 49 46 49 46 46 46 46 46 49 46 46 46 49 46 46 46 49 46 49 46 46 46 46 46 49 46 46 46 46 46 46 49 46 49 49 46 46 49 49 46 46 46 46 46 46 46 46 46 46 46 49 46 49 49 49 46 49 49 49 49 46 46 49 46 49 49 46 46 49 49 49 49 49 49 46 46 46 46 49 49 49 49 49 46 49 49 49 46 49 46 49 46 46 46 49 49 46 46 49 49 49 46 46 46 49 49 49 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 49 49 49 49 49 49 49 49 49 49 46 46 49 49 46 46 49 49 49 49 46 46 49 49 49 49 46 46 49 49 49 46 46 46 49 49 49 46 46 46 49 46 46 46 46 46 49 49 49 46 49 46 49 49 49 49 49 46 49 49 49 49 49 49 46 46 46 46 46 46 49 49 49 49 49 46 46 46 49 46 46 46 49 49 49 49 49 46 46 49 46 46 46 49 49 49 49 46 46 46 46 46 46 49 46 46 46 49 49 46 46 49 49 49 49 49 49 49 49 49 46 46 46 46 46 49 46 46 46 49 49 49 49 46 46 49 46 46 46 49 46 46 46 49 46 46 46 49 46 46 46 46 46 46 46 49 46 46 46 46 46 49 46 46 46 49 49 49 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 49 49 49 46 49 49 49 46 46 46 46 46 49 49 49 49 49 49 49 46 49 49 49 49 49 49 49 46 46 46 49 46 46 46 49 46 46 46 49 46 46 46 46 46 49 46 46 46 49 46 46 46 49 46 46 46 49 46 46 46 49 46 49 49 49 46 46 46 49 49 49 49 46 46 49 46 46 46 49 46 46 46 46 46 46 46 49 46 49 46 46 46 46 46 46 49 46 46 46 46 46 46 46 49 49 46 46 49 46 46 46 49 46 49 49 49 46 46 46 49 46 46 46 46 46 46 46 46 46 46 46 49 49 49 49 49 49 49 49 46 46 46 46 46 46 49 46 49 49 46 46 46 46 49 46 49 46 46 46 46 46 49 46 49 46 46 46 49 49 46 46 46 46 49 49 49 46 49 49 49 49 49 49 49 46 46 46 46 46 46 46 46 46 46 49 49 49 49 46 46 49 49 49 49 49 46 46 46 49 49 49 49 49 46 46 46 49 46 46 46 49 46 49 49 46 46 46 46 46 46 49 49 49 49 49 49 49 49 49 49 46 46 46 46 46 46 46 46 49 49 49 49 46 46 49 49 49 49 49 46 49 49 46 46 49 46 46 46 49 46 46 46 46 46 49 46 46 46 46 46 46 46 46 49 49 46 46 49 46 46 46 49 49 49 49 49 49 49 49 49 46 46 46 46 46 49 49 49 49 46 46 49 49 49 49 46 46 49 49 49 49 49 46 46 46 49 49 49 49 49 46 46 46 49 46 46 46 46 46 49 49 46 46 46 46 49 49 49 49 49 46 46 46 46 46 49 46 46 46 49 49 46 46 49 49 49 49 49 49 49 46 46 46 46 49 46 49 46 46 */
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %r9 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x10af5, %rsi lea addresses_D_ht+0x42f5, %rdi clflush (%rdi) nop nop dec %r11 mov $4, %rcx rep movsl nop dec %rsi lea addresses_D_ht+0x4af5, %r9 nop nop xor $30909, %rbp movw $0x6162, (%r9) nop nop add %r9, %r9 lea addresses_WT_ht+0x142d8, %rcx nop nop nop nop nop xor %r11, %r11 movb $0x61, (%rcx) nop nop nop add %r8, %r8 lea addresses_D_ht+0x17379, %rbp nop sub $46564, %rsi movw $0x6162, (%rbp) nop cmp %rbp, %rbp lea addresses_A_ht+0xf3f5, %r11 nop cmp $30092, %r8 mov (%r11), %rdi nop nop xor %rcx, %rcx lea addresses_A_ht+0x96dd, %rsi nop nop nop xor $55641, %rcx mov $0x6162636465666768, %rbp movq %rbp, %xmm5 vmovups %ymm5, (%rsi) nop dec %rbp lea addresses_UC_ht+0x12d65, %rsi lea addresses_normal_ht+0x97b5, %rdi cmp %rbp, %rbp mov $98, %rcx rep movsb nop nop nop sub %rdi, %rdi lea addresses_WT_ht+0x151ad, %rsi lea addresses_WT_ht+0x132e5, %rdi nop nop nop nop sub $17281, %r15 mov $69, %rcx rep movsw nop nop add $35906, %r15 lea addresses_A_ht+0x197c1, %r8 clflush (%r8) nop and $28200, %rbp movb (%r8), %r15b nop nop nop nop nop sub %r11, %r11 lea addresses_A_ht+0x92f5, %rsi lea addresses_D_ht+0x55b5, %rdi cmp %r15, %r15 mov $70, %rcx rep movsb nop nop nop mfence lea addresses_WC_ht+0xb6f5, %rdi add %r9, %r9 mov $0x6162636465666768, %r8 movq %r8, %xmm7 movups %xmm7, (%rdi) nop nop nop nop nop and %r8, %r8 pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r15 push %r8 push %rcx push %rdi push %rsi // Store lea addresses_PSE+0x7bad, %rcx and $35832, %r15 mov $0x5152535455565758, %rdi movq %rdi, (%rcx) nop and %r15, %r15 // Store lea addresses_normal+0x152f5, %r15 nop mfence mov $0x5152535455565758, %r12 movq %r12, %xmm4 movups %xmm4, (%r15) nop nop nop nop nop add %rdi, %rdi // Store lea addresses_PSE+0x55f5, %r8 nop nop nop nop nop dec %rsi movb $0x51, (%r8) nop nop and %r13, %r13 // Faulty Load lea addresses_WT+0x22f5, %rdi nop nop nop nop inc %rcx mov (%rdi), %r8d lea oracles, %r13 and $0xff, %r8 shlq $12, %r8 mov (%r13,%r8,1), %r8 pop %rsi pop %rdi pop %rcx pop %r8 pop %r15 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WT', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal', 'same': False, 'size': 16, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 8, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_WT', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 2, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 2, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A_ht', 'same': True, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/passwords/well_known_change_password_navigation_throttle.h" #include "base/logging.h" #include "chrome/browser/password_manager/affiliation_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" #include "components/password_manager/core/browser/site_affiliation/affiliation_service.h" #include "components/password_manager/core/browser/well_known_change_password_state.h" #include "components/password_manager/core/browser/well_known_change_password_util.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/ukm/content/source_url_recorder.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_user_data.h" #include "net/base/isolation_info.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "ui/base/page_transition_types.h" #include "url/gurl.h" #include "url/origin.h" namespace { using content::NavigationHandle; using content::NavigationThrottle; using content::WebContents; using password_manager::IsWellKnownChangePasswordUrl; using password_manager::WellKnownChangePasswordResult; using password_manager::WellKnownChangePasswordState; bool IsTriggeredByGoogleOwnedUI(NavigationHandle* handle) { ui::PageTransition page_transition = handle->GetPageTransition(); // `PAGE_TRANSITION_FROM_API` covers cases where Chrome is opened as a CCT. // This happens on Android if Chrome is opened from the Password Check(up) in // Chrome settings or the Google Password Manager app. if (page_transition & ui::PAGE_TRANSITION_FROM_API) return true; // In case where the user clicked on a link, we require that the origin is // either chrome://settings or https://passwords.google.com. if (ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_LINK)) { url::Origin origin = handle->GetInitiatorOrigin().value_or(url::Origin()); return origin == url::Origin::Create(GURL(chrome::kChromeUISettingsURL)) || origin == url::Origin::Create(GURL(chrome::kGooglePasswordManagerURL)); } return false; } } // namespace // static std::unique_ptr<WellKnownChangePasswordNavigationThrottle> WellKnownChangePasswordNavigationThrottle::MaybeCreateThrottleFor( NavigationHandle* handle) { if (handle->IsInMainFrame() && IsWellKnownChangePasswordUrl(handle->GetURL()) && IsTriggeredByGoogleOwnedUI(handle)) { return std::make_unique<WellKnownChangePasswordNavigationThrottle>(handle); } return nullptr; } WellKnownChangePasswordNavigationThrottle:: WellKnownChangePasswordNavigationThrottle(NavigationHandle* handle) : NavigationThrottle(handle), request_url_(handle->GetURL()), source_id_( ukm::GetSourceIdForWebContentsDocument(handle->GetWebContents())) { // If we're in a non-primary frame tree (e.g. prerendering) we're only // constructing the throttle so it can cancel the prerender. if (!handle->IsInPrimaryMainFrame()) return; affiliation_service_ = AffiliationServiceFactory::GetForProfile(Profile::FromBrowserContext( handle->GetWebContents()->GetBrowserContext())); if (affiliation_service_->GetChangePasswordURL(request_url_).is_empty()) { well_known_change_password_state_.PrefetchChangePasswordURLs( affiliation_service_, {request_url_}); } } WellKnownChangePasswordNavigationThrottle:: ~WellKnownChangePasswordNavigationThrottle() = default; NavigationThrottle::ThrottleCheckResult WellKnownChangePasswordNavigationThrottle::WillStartRequest() { // The logic in Redirect will navigate the primary FrameTree if we're in a // prerender. We don't have a way to navigate the prerendered page so just // cancel the prerender. if (!navigation_handle()->IsInPrimaryMainFrame()) { return NavigationThrottle::CANCEL; } auto url_loader_factory = navigation_handle() ->GetWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition() ->GetURLLoaderFactoryForBrowserProcess(); // In order to avoid bypassing Sec-Fetch-Site headers and extracting user data // across redirects, we need to set both the initiator origin and network // isolation key when fetching the well-known non-existing resource. // See the discussion in blink-dev/UN1BRg4qTbs for more details. // TODO(crbug.com/1127520): Confirm that this works correctly within // redirects. network::ResourceRequest::TrustedParams trusted_params; trusted_params.isolation_info = net::IsolationInfo::CreatePartial( net::IsolationInfo::RequestType::kOther, navigation_handle()->GetIsolationInfo().network_isolation_key()); well_known_change_password_state_.FetchNonExistingResource( url_loader_factory.get(), request_url_, navigation_handle()->GetInitiatorOrigin(), std::move(trusted_params)); return NavigationThrottle::PROCEED; } NavigationThrottle::ThrottleCheckResult WellKnownChangePasswordNavigationThrottle::WillFailRequest() { return NavigationThrottle::PROCEED; } NavigationThrottle::ThrottleCheckResult WellKnownChangePasswordNavigationThrottle::WillProcessResponse() { // PostTask because the Throttle needs to be deferred before the status code // is set. After setting the status code Resume() can be called synchronous // and thereby before the throttle is deferred. This would result in a crash. // Unretained is safe because the NavigationThrottle is deferred and can only // be continued after the callback finished. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &WellKnownChangePasswordState::SetChangePasswordResponseCode, base::Unretained(&well_known_change_password_state_), navigation_handle()->GetResponseHeaders()->response_code())); return NavigationThrottle::DEFER; } const char* WellKnownChangePasswordNavigationThrottle::GetNameForLogging() { return "WellKnownChangePasswordNavigationThrottle"; } void WellKnownChangePasswordNavigationThrottle::OnProcessingFinished( bool is_supported) { GURL redirect_url = affiliation_service_->GetChangePasswordURL(request_url_); // If affiliation service returns .well-known/change-password as change // password url - show it even if Chrome doesn't detect it as supported. if (is_supported || redirect_url == request_url_) { RecordMetric(WellKnownChangePasswordResult::kUsedWellKnownChangePassword); Resume(); return; } if (redirect_url.is_valid()) { RecordMetric(WellKnownChangePasswordResult::kFallbackToOverrideUrl); Redirect(redirect_url); } else { RecordMetric(WellKnownChangePasswordResult::kFallbackToOriginUrl); Redirect(request_url_.DeprecatedGetOriginAsURL()); } CancelDeferredNavigation(NavigationThrottle::CANCEL); } void WellKnownChangePasswordNavigationThrottle::Redirect(const GURL& url) { content::OpenURLParams params = content::OpenURLParams::FromNavigationHandle(navigation_handle()); params.url = url; params.transition = ui::PAGE_TRANSITION_CLIENT_REDIRECT; WebContents* web_contents = navigation_handle()->GetWebContents(); if (!web_contents) return; base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<content::WebContents> web_contents, const content::OpenURLParams& params) { if (!web_contents) return; web_contents->OpenURL(params); }, web_contents->GetWeakPtr(), std::move(params))); } void WellKnownChangePasswordNavigationThrottle::RecordMetric( WellKnownChangePasswordResult result) { ukm::builders::PasswordManager_WellKnownChangePasswordResult(source_id_) .SetWellKnownChangePasswordResult(static_cast<int64_t>(result)) .Record(ukm::UkmRecorder::Get()); }
; A116774: Number of permutations of length n which avoid the patterns 2143, 2341, 4312; or avoid the patterns 1234, 1432, 3412. ; 1,2,6,21,69,198,498,1121,2305,4402,7910,13509,22101,34854,53250,79137,114785,162946,226918,310613,418629,556326,729906,946497,1214241,1542386,1941382,2422981,3000341,3688134 mov $12,$0 mov $14,$0 add $14,1 lpb $14,1 clr $0,12 mov $0,$12 sub $14,1 sub $0,$14 mov $9,$0 mov $11,$0 add $11,1 lpb $11,1 mov $0,$9 sub $11,1 sub $0,$11 mov $7,$0 bin $7,2 mov $0,$7 add $0,1 pow $0,2 mov $3,1 add $3,$0 add $3,2 mov $7,$8 mov $8,1 lpb $0,1 mov $0,$7 mov $5,40 lpe mul $3,26 add $3,$5 mov $1,$3 sub $1,105 div $1,39 mov $5,$2 add $10,$1 lpe add $13,$10 lpe mov $1,$13
; A195158: Concentric 24-gonal numbers. ; 0,1,24,49,96,145,216,289,384,481,600,721,864,1009,1176,1345,1536,1729,1944,2161,2400,2641,2904,3169,3456,3745,4056,4369,4704,5041,5400,5761,6144,6529,6936,7345,7776,8209,8664,9121,9600,10081,10584,11089,11616,12145,12696,13249,13824,14401,15000,15601,16224,16849,17496,18145,18816,19489,20184,20881,21600,22321,23064,23809,24576,25345,26136,26929,27744,28561,29400,30241,31104,31969,32856,33745,34656,35569,36504,37441,38400,39361,40344,41329,42336,43345,44376,45409,46464,47521,48600,49681,50784 pow $0,2 mov $1,$0 div $0,2 mul $0,10 add $0,$1
; Startup for VZ200/300 ; ; Stefano Bodrato - Apr. 2000 ; ; If an error occurs eg break we just drop back to BASIC ; ; $Id: vz_crt0.asm,v 1.27 2016-07-15 21:03:25 dom Exp $ ; MODULE vz_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- EXTERN _main ;main() is always external to crt0 code PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) IF !DEFINED_CRT_ORG_CODE IF (startup=3) defc CRT_ORG_CODE = 32768 ; clean binary block ELSE IF (startup=2) defc CRT_ORG_CODE = $7ae9 ; BASIC startup mode ELSE defc CRT_ORG_CODE = $7b00 ; Direct M/C mode ENDIF ENDIF ENDIF defc CONSOLE_ROWS = 16 defc CONSOLE_COLUMNS = 32 ; Now, getting to the real stuff now! defc TAR__no_ansifont = 1 defc TAR__clib_exit_stack_size = 32 defc TAR__register_sp = -1 defc __CPU_CLOCK = 3800000 INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE-24 IF (startup=3) ; STARTUP=3 -> plain binary block ELSE defb $20,$20,0,0 defm "z80.mc" defb 0,0,0,0,0,0,0,0,0,0,0 IF (startup=2) ; BASIC startup mode defb $f0 ELSE ; native M/C startup mode defb $f1 ENDIF defw CRT_ORG_CODE IF (startup=2) defw $7b04 defw 1 defb $B1 ;POKE defm " 30862,18:" defb $B1 ;POKE defm " 30863,123" defb 0 ; this block is 27 bytes long defw $7b0f defw 2 defb $b2 ; PRINT defb ' ' defb $c1 ; USR defm "(0)" defb 0 ; this block is 11 bytes long defw 0 defb 4 ; Header ends here: 65 bytes ENDIF ENDIF start: ld (start1+1),sp INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld (exitsp),sp ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF call _main cleanup: ; ; Deallocate memory which has been allocated here! ; push hl IF CRT_ENABLE_STDIO = 1 EXTERN closeall call closeall ENDIF pop bc start1: ld sp,0 jp 1A19h l_dcal: jp (hl) INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm" SECTION code_crt_init ld hl,$7000 ld (base_graphics),hl
; A289999: Sierpinski cuboctahedral numbers: a(n) = 16*4^n - 12*2^n + 9. ; 13,49,217,937,3913,16009,64777,260617,1045513,4188169,16764937,67084297,268386313,1073643529,4294770697,17179475977,68718690313,274876334089,1099508482057,4398040219657,17592173461513,70368719011849,281474926379017,1125899806179337,4503599426043913,18014398106828809,72057593232621577,288230374541099017,1152921501385621513,4611686011984936969,18446744060824649737,73786976269068402697,295147905127813218313,1180591620614332088329,4722366482663486783497,18889465931066263994377 add $0,2 mov $1,2 pow $1,$0 sub $1,1 bin $1,2 div $1,6 mul $1,12 add $1,13 mov $0,$1
Map_361A18: dc.w Frame_361A24-Map_361A18 dc.w Frame_361A2C-Map_361A18 dc.w Frame_361A34-Map_361A18 dc.w Frame_361A3C-Map_361A18 dc.w Frame_361A50-Map_361A18 dc.w Frame_361A64-Map_361A18 Frame_361A24: dc.w 1 dc.b $F8, 5, 0, 0,$FF,$F8 Frame_361A2C: dc.w 1 dc.b $F4, 6, 0, 4,$FF,$F8 Frame_361A34: dc.w 1 dc.b $F8, 5, 0, $A,$FF,$F8 Frame_361A3C: dc.w 3 dc.b $EC, 5, 0, $E, 0, 0 dc.b $FC, 8, 0,$17, 0, 0 dc.b 4, 5,$10, $E, 0, 0 Frame_361A50: dc.w 3 dc.b $EC, 5, 0,$12, 0, 0 dc.b $FC, 4, 0,$1A, 0, 5 dc.b 4, 5,$10,$12, 0, 0 Frame_361A64: dc.w 3 dc.b $F4, 0, 0,$16, 0, 8 dc.b $FC, 0, 0,$1C, 0,$10 dc.b 4, 0,$10,$16, 0, 8
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Copyright (c) Microsoft Corporation. All rights reserved. // Implementation for MCBSTM32E board (STM32): Copyright (c) Oberon microsystems, Inc. // // *** Block Storage Configuration for External M25P64 Serial Flash *** // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> //--// #define FLASH_BLOCK_COUNT 128 #define FLASH_BYTES_PER_BLOCK 65536 #define FLASH_BYTES_PER_SECTOR 256 #define FLASH_SECTOR_WRITE_TYPICAL_TIME_USEC 1400 // not used #define FLASH_BLOCK_ERASE_ACTUAL_TIME_USEC 1000000 // not used #define FLASH_BLOCK_ERASE_MAX_TIME_USEC 3000000 // not used //--// // EBIU Information #define M25P64__SIZE_IN_BYTES FLASH_BLOCK_COUNT * FLASH_BYTES_PER_BLOCK #define M25P64__WP_GPIO_PIN GPIO_PIN_NONE #define M25P64__WP_ACTIVE FALSE //--// // BlockDeviceInformation #define M25P64__IS_REMOVABLE FALSE #define M25P64__SUPPORTS_XIP FALSE #define M25P64__WRITE_PROTECTED FALSE #define M25P64__SUPP_COPY_BACK FALSE #define M25P64__NUM_REGIONS 1 //--// const BlockRange g_M25P64_BlockRange[] = { { BlockRange::BLOCKTYPE_DEPLOYMENT, 0, 63 }, // 4M { BlockRange::BLOCKTYPE_FILESYSTEM, 64, 127 } // 4M }; const BlockRegionInfo g_M25P64_BlkRegion[M25P64__NUM_REGIONS] = { { 0, // ByteAddress Start; // Starting Sector address FLASH_BLOCK_COUNT, // UINT32 NumBlocks; // total number of blocks in this region FLASH_BYTES_PER_BLOCK, // UINT32 BytesPerBlock; // Total number of bytes per block ARRAYSIZE_CONST_EXPR(g_M25P64_BlockRange), g_M25P64_BlockRange, } }; //--// const BlockDeviceInfo g_M25P64_DeviceInfo= { { M25P64__IS_REMOVABLE, // BOOL Removable; M25P64__SUPPORTS_XIP, // BOOL SupportsXIP; M25P64__WRITE_PROTECTED, // BOOL WriteProtected; M25P64__SUPP_COPY_BACK // BOOL SupportsCopyBack }, FLASH_SECTOR_WRITE_TYPICAL_TIME_USEC, // UINT32 MaxSectorWrite_uSec; FLASH_BLOCK_ERASE_ACTUAL_TIME_USEC, // UINT32 MaxBlockErase_uSec; FLASH_BYTES_PER_SECTOR, // UINT32 BytesPerSector; FLASH_MEMORY_Size, // UINT32 Size; M25P64__NUM_REGIONS, // UINT32 NumRegions; g_M25P64_BlkRegion, // const BlockRegionInfo* pRegions; }; struct BLOCK_CONFIG g_M25P64_BS_Config = { { M25P64__WP_GPIO_PIN, // GPIO_PIN Pin; M25P64__WP_ACTIVE, // BOOL ActiveState; }, &g_M25P64_DeviceInfo, // BlockDeviceinfo }; //--// #if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED) #pragma arm section rodata = "g_M25P64_BS" #endif struct BlockStorageDevice g_M25P64_BS; #if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED) #pragma arm section rodata #endif //--//
format MZ use16 entry main:start segment main start: mov bx,program_data mov ds,bx mov ah,09h mov dx,TKomunikat int 21h mov ah,0ah mov dx,BFileName int 21h movzx di,byte [FileNameCounter] lea bx,[FileName] add di,bx xor ah,ah mov [di],ah sub di,4 mov ax,[di] cmp ax,'.b' jne zly_plik add di,2 mov ax,[di] cmp ax,'mp' jne zly_plik mov ah,3dh mov al,010b lea dx,[FileName] int 21h jc blad mov bx,ax mov ah,3fh mov cx,54 lea dx,[BFile1] int 21h jc blad xor si,si mov cx,4 ustawpalete: mov ah,3fh mov dx,b int 21h mov dl,[r] ;shl dl,2 mov [BPaleta+si],dl mov dl,[g] ;shl dl,2 mov [BPaleta+si+1],dl mov dl,[b] ;shl dl,2 mov [BPaleta+si+2],dl mov dl,[x] ;shl dl,2 mov byte [BPaleta+si+3],dl add si,4 cmp si,1024 jb ustawpalete push file_buffer1 pop ds mov dx,0 mov cx,08000h mov ah,3fh int 21h mov dx,cx mov ah,3fh int 21h push file_buffer2 pop ds mov dx,0 mov cx,08000h mov ah,3fh int 21h mov dx,cx mov ah,3fh int 21h push file_buffer3 pop ds mov dx,0 mov cx,08000h mov ah,3fh int 21h mov dx,cx mov ah,3fh int 21h push file_buffer4 pop ds mov dx,0 mov cx,08000h mov ah,3fh int 21h mov dx,cx mov ah,3fh int 21h push file_buffer5 pop ds mov dx,0 mov cx,0b000h mov ah,3fh int 21h mov ax,program_data mov ds,ax mov ax,'pf' mov [di],ax sub di,2 mov ax,'.g' mov [di],ax mov ah,3ch xor cx,cx lea dx,[FileName] int 21h jc blad mov bx,ax mov ah,40h mov cx,1024 lea dx,[BPaleta] int 21h push file_buffer5 pop ds mov dx,0b000h mov cx,640 filepetla1: sub dx,cx mov ah,40h int 21h cmp dx,cx ja filepetla1 push dx ;dx-to co nie miesci sie w linijkach mov bp,dx mov cx,640 ;cx-ilosc pikseli z nastej czesci sub cx,bp mov dx,0ffffh sub dx,cx inc dx push file_buffer4 pop ds mov ah,40h int 21h sub dx,cx mov gs,dx xor dx,dx push file_buffer5 pop ds pop cx mov ah,40h int 21h mov dx,gs sub dx,bp mov cx,640 add dx,cx push file_buffer4 pop ds filepetla2: sub dx,cx mov ah,40h int 21h cmp dx,cx jae filepetla2 push dx ;dx-to co nie miesci sie w linijkach mov bp,dx mov cx,640 ;cx-ilosc pikseli z nastej czesci sub cx,bp mov dx,0ffffh sub dx,cx inc dx push file_buffer3 pop ds mov ah,40h int 21h sub dx,cx mov gs,dx xor dx,dx push file_buffer4 pop ds pop cx mov ah,40h int 21h mov dx,gs sub dx,bp mov cx,640 add dx,cx push file_buffer3 pop ds filepetla3: sub dx,cx mov ah,40h int 21h cmp dx,cx jae filepetla3 push dx ;dx-to co nie miesci sie w linijkach mov bp,dx mov cx,640 ;cx-ilosc pikseli z nastej czesci sub cx,bp mov dx,0ffffh sub dx,cx inc dx push file_buffer2 pop ds mov ah,40h int 21h sub dx,cx mov gs,dx xor dx,dx push file_buffer3 pop ds pop cx mov ah,40h int 21h mov dx,gs sub dx,bp mov cx,640 add dx,cx push file_buffer2 pop ds filepetla4: sub dx,cx mov ah,40h int 21h cmp dx,cx jae filepetla4 push dx ;dx-to co nie miesci sie w linijkach mov bp,dx mov cx,640 ;cx-ilosc pikseli z nastej czesci sub cx,bp mov dx,0ffffh sub dx,cx inc dx push file_buffer1 pop ds mov ah,40h int 21h sub dx,cx mov gs,dx xor dx,dx push file_buffer2 pop ds pop cx mov ah,40h int 21h mov dx,gs sub dx,bp mov cx,640 add dx,cx push file_buffer1 pop ds filepetla5: sub dx,cx mov ah,40h int 21h cmp dx,cx jae filepetla5 mov cx,dx xor dx,dx mov ah,40h int 21h koniec: xor ah,ah int 16h Koniec: mov ax,4c00h int 21h zly_plik: mov ah,09h mov dx,TZlyPlik int 21h jmp koniec blad: mov ah,09h mov dx,TBlad int 21h jmp koniec segment program_data TZlyPlik db 'Niewlasciwa nazwa pliku$' TBlad db 'Blad pliku $' TKomunikat db 'Wpisz nazwe pliku, ktory chcesz przekonwertowac z bmp na gpf',10,13,'$' BFileName db 199 FileNameCounter db 0 FileName: times 200 db 0 b db 0 g db 0 r db 0 x db 0 BPaleta: times 1024 db 0 segment file_buffer1 BFile1: times 10000h db 0 segment file_buffer2 BFile2: times 10000h db 0 segment file_buffer3 BFile3: times 10000h db 0 segment file_buffer4 BFile4: times 10000h db 0 segment file_buffer5 BFile5: times 0b000h db 0 Virtual at BFile1 bftype dw ? bfsize dd ? bfreserved dd ? bfoffbits dd ? bmprozmiar dd ? bmpszerokosc dd ? bmpwysokosc dd ? biplanes dw ? bibitcount dw ? bicompression dd ? bisizeimag dd ? bixpelspermeter dd ? biypelspermeter dd ? bmpliczbakolorow dd ? biclrimportant dd ? end virtual
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <coins.h> #include <compat/byteswap.h> #include <consensus/validation.h> #include <core_io.h> #include <index/txindex.h> #include <key_io.h> #include <merkleblock.h> #include <node/coin.h> #include <node/psbt.h> #include <node/transaction.h> #include <policy/rbf.h> #include <primitives/transaction.h> #include <psbt.h> #include <rpc/rawtransaction_util.h> #include <rpc/server.h> #include <rpc/util.h> #include <script/script.h> #include <script/script_error.h> #include <script/sign.h> #include <script/signingprovider.h> #include <script/standard.h> #include <uint256.h> #include <util/moneystr.h> #include <util/strencodings.h> #include <validation.h> #include <validationinterface.h> #include <numeric> #include <stdint.h> #include <univalue.h> /** High fee for sendrawtransaction and testmempoolaccept. * By default, transaction with a fee higher than this will be rejected by the * RPCs. This can be overridden with the maxfeerate argument. */ constexpr static CAmount DEFAULT_MAX_RAW_TX_FEE{COIN / 10}; static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) { // Call into TxToUniv() in bitcoin-common to decode the transaction hex. // // Blockchain contextual information (confirmations and blocktime) is not // available to code in bitcoin-common, so we query them here and push the // data into the returned UniValue. TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags()); if (!hashBlock.IsNull()) { LOCK(cs_main); entry.pushKV("blockhash", hashBlock.GetHex()); CBlockIndex* pindex = LookupBlockIndex(hashBlock); if (pindex) { if (::ChainActive().Contains(pindex)) { entry.pushKV("confirmations", 1 + ::ChainActive().Height() - pindex->nHeight); entry.pushKV("time", pindex->GetBlockTime()); entry.pushKV("blocktime", pindex->GetBlockTime()); } else entry.pushKV("confirmations", 0); } } } static UniValue getrawtransaction(const JSONRPCRequest& request) { RPCHelpMan{ "getrawtransaction", "\nReturn the raw transaction data.\n" "\nBy default this function only works for mempool transactions. When called with a blockhash\n" "argument, getrawtransaction will return the transaction if the specified block is available and\n" "the transaction is found in that block. When called without a blockhash argument, getrawtransaction\n" "will return the transaction if it is in the mempool, or if -txindex is enabled and the transaction\n" "is in a block in the blockchain.\n" "\nHint: Use gettransaction for wallet transactions.\n" "\nIf verbose is 'true', returns an Object with information about 'txid'.\n" "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"verbose", RPCArg::Type::BOOL, /* default */ "false", "If false, return a string, otherwise return a json object"}, {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "The block in which to look for the transaction"}, }, { RPCResult{"if verbose is not set or set to false", "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" }, RPCResult{"if verbose is set to true", "{\n" " \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n" " \"size\" : n, (numeric) The serialized transaction size\n" " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n" " \"weight\" : n, (numeric) The transaction's weight (between vsize*4-3 and vsize*4)\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"address\" (string) bitcoin address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"time\" : ttt, (numeric) Same as \"blocktime\"\n" "}\n" }, }, RPCExamples{ HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" true") + HelpExampleRpc("getrawtransaction", "\"mytxid\", true") + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"") }, }.Check(request); bool in_active_chain = true; uint256 hash = ParseHashV(request.params[0], "parameter 1"); CBlockIndex* blockindex = nullptr; if (hash == Params().GenesisBlock().hashMerkleRoot) { // Special exception for the genesis block coinbase transaction throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved"); } // Accept either a bool (true) or a num (>=1) to indicate verbose output. bool fVerbose = false; if (!request.params[1].isNull()) { fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool(); } if (!request.params[2].isNull()) { LOCK(cs_main); uint256 blockhash = ParseHashV(request.params[2], "parameter 3"); blockindex = LookupBlockIndex(blockhash); if (!blockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found"); } in_active_chain = ::ChainActive().Contains(blockindex); } bool f_txindex_ready = false; if (g_txindex && !blockindex) { f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain(); } CTransactionRef tx; uint256 hash_block; if (!GetTransaction(hash, tx, Params().GetConsensus(), hash_block, blockindex)) { std::string errmsg; if (blockindex) { if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) { throw JSONRPCError(RPC_MISC_ERROR, "Block not available"); } errmsg = "No such transaction found in the provided block"; } else if (!g_txindex) { errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries"; } else if (!f_txindex_ready) { errmsg = "No such mempool transaction. Blockchain transactions are still in the process of being indexed"; } else { errmsg = "No such mempool or blockchain transaction"; } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions."); } if (!fVerbose) { return EncodeHexTx(*tx, RPCSerializationFlags()); } UniValue result(UniValue::VOBJ); if (blockindex) result.pushKV("in_active_chain", in_active_chain); TxToJSON(*tx, hash_block, result); return result; } static UniValue gettxoutproof(const JSONRPCRequest& request) { RPCHelpMan{"gettxoutproof", "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n" "\nNOTE: By default this function only works sometimes. This is when there is an\n" "unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option or\n" "specify the block in which the transaction is included manually (by blockhash).\n", { {"txids", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of txids to filter", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A transaction hash"}, }, }, {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "If specified, looks for txid in the block with this hash"}, }, RPCResult{ "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n" }, RPCExamples{""}, }.Check(request); std::set<uint256> setTxids; uint256 oneTxid; UniValue txids = request.params[0].get_array(); for (unsigned int idx = 0; idx < txids.size(); idx++) { const UniValue& txid = txids[idx]; uint256 hash(ParseHashV(txid, "txid")); if (setTxids.count(hash)) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str()); setTxids.insert(hash); oneTxid = hash; } CBlockIndex* pblockindex = nullptr; uint256 hashBlock; if (!request.params[1].isNull()) { LOCK(cs_main); hashBlock = ParseHashV(request.params[1], "blockhash"); pblockindex = LookupBlockIndex(hashBlock); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } } else { LOCK(cs_main); // Loop through txids and try to find which block they're in. Exit loop once a block is found. for (const auto& tx : setTxids) { const Coin& coin = AccessByTxid(::ChainstateActive().CoinsTip(), tx); if (!coin.IsSpent()) { pblockindex = ::ChainActive()[coin.nHeight]; break; } } } // Allow txindex to catch up if we need to query it and before we acquire cs_main. if (g_txindex && !pblockindex) { g_txindex->BlockUntilSyncedToCurrentChain(); } LOCK(cs_main); if (pblockindex == nullptr) { CTransactionRef tx; if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); pblockindex = LookupBlockIndex(hashBlock); if (!pblockindex) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); } } CBlock block; if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; for (const auto& tx : block.vtx) if (setTxids.count(tx->GetHash())) ntxFound++; if (ntxFound != setTxids.size()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block"); CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS); CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB.begin(), ssMB.end()); return strHex; } static UniValue verifytxoutproof(const JSONRPCRequest& request) { RPCHelpMan{"verifytxoutproof", "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n" "and throwing an RPC error if the block is not in our best chain\n", { {"proof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded proof generated by gettxoutproof"}, }, RPCResult{ "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof can not be validated.\n" }, RPCExamples{""}, }.Check(request); CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS); CMerkleBlock merkleBlock; ssMB >> merkleBlock; UniValue res(UniValue::VARR); std::vector<uint256> vMatch; std::vector<unsigned int> vIndex; if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) return res; LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash()); if (!pindex || !::ChainActive().Contains(pindex) || pindex->nTx == 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } // Check if proof is valid, only add results if so if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) { for (const uint256& hash : vMatch) { res.push_back(hash.GetHex()); } } return res; } static UniValue createrawtransaction(const JSONRPCRequest& request) { RPCHelpMan{"createrawtransaction", "\nCreate a transaction spending the given inputs and creating new outputs.\n" "Outputs can be addresses or data.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n", { {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of json objects", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"sequence", RPCArg::Type::NUM, /* default */ "depends on the value of the 'replaceable' and 'locktime' arguments", "The sequence number"}, }, }, }, }, {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "a json array with outputs (key-value pairs), where none of the keys are duplicated.\n" "That is, each address can only appear once and there can only be one 'data' object.\n" "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" " accepted as second parameter.", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT}, }, }, {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"}, }, }, }, }, {"locktime", RPCArg::Type::NUM, /* default */ "0", "Raw locktime. Non-0 value also locktime-activates inputs"}, {"replaceable", RPCArg::Type::BOOL, /* default */ "false", "Marks this transaction as BIP125-replaceable.\n" " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."}, }, RPCResult{ "\"transaction\" (string) hex string of the transaction\n" }, RPCExamples{ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"") + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"") }, }.Check(request); RPCTypeCheck(request.params, { UniValue::VARR, UniValueType(), // ARR or OBJ, checked later UniValue::VNUM, UniValue::VBOOL }, true ); bool rbf = false; if (!request.params[3].isNull()) { rbf = request.params[3].isTrue(); } CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf); return EncodeHexTx(CTransaction(rawTx)); } static UniValue decoderawtransaction(const JSONRPCRequest& request) { RPCHelpMan{"decoderawtransaction", "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction hex string"}, {"iswitness", RPCArg::Type::BOOL, /* default */ "depends on heuristic tests", "Whether the transaction hex is a serialized witness transaction.\n" "If iswitness is not present, heuristic tests will be used in decoding.\n" "If true, only witness deserialization will be tried.\n" "If false, only non-witness deserialization will be tried.\n" "This boolean should reflect whether the transaction has inputs\n" "(e.g. fully valid, or on-chain transactions), if known by the caller." }, }, RPCResult{ "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n" " \"size\" : n, (numeric) The transaction size\n" " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n" " \"weight\" : n, (numeric) The transaction's weight (between vsize*4 - 3 and vsize*4)\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" "}\n" }, RPCExamples{ HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}); CMutableTransaction mtx; bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool(); bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool(); if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } UniValue result(UniValue::VOBJ); TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false); return result; } static std::string GetAllOutputTypes() { std::string ret; for (int i = TX_NONSTANDARD; i <= TX_WITNESS_UNKNOWN; ++i) { if (i != TX_NONSTANDARD) ret += ", "; ret += GetTxnOutputType(static_cast<txnouttype>(i)); } return ret; } static UniValue decodescript(const JSONRPCRequest& request) { RPCHelpMan{"decodescript", "\nDecode a hex-encoded script.\n", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded script"}, }, RPCResult{ "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"type\":\"type\", (string) The output type (e.g. "+GetAllOutputTypes()+")\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) bitcoin address\n" " ,...\n" " ],\n" " \"p2sh\":\"str\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n" " \"segwit\": { (json object) Result of a witness script public key wrapping this redeem script (not returned if the script is a P2SH or witness).\n" " \"asm\":\"str\", (string) String representation of the script public key\n" " \"hex\":\"hexstr\", (string) Hex string of the script public key\n" " \"type\":\"str\", (string) The type of the script public key (e.g. witness_v0_keyhash or witness_v0_scripthash)\n" " \"reqSigs\": n, (numeric) The required signatures (always 1)\n" " \"addresses\": [ (json array of string) (always length 1)\n" " \"address\" (string) segwit address\n" " ,...\n" " ],\n" " \"p2sh-segwit\":\"str\" (string) address of the P2SH script wrapping this witness redeem script.\n" "}\n" }, RPCExamples{ HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR}); UniValue r(UniValue::VOBJ); CScript script; if (request.params[0].get_str().size() > 0){ std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false); UniValue type; type = find_value(r, "type"); if (type.isStr() && type.get_str() != "scripthash") { // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH, // don't return the address for a P2SH of the P2SH. r.pushKV("p2sh", EncodeDestination(ScriptHash(script))); // P2SH and witness programs cannot be wrapped in P2WSH, if this script // is a witness program, don't return addresses for a segwit programs. if (type.get_str() == "pubkey" || type.get_str() == "pubkeyhash" || type.get_str() == "multisig" || type.get_str() == "nonstandard") { std::vector<std::vector<unsigned char>> solutions_data; txnouttype which_type = Solver(script, solutions_data); // Uncompressed pubkeys cannot be used with segwit checksigs. // If the script contains an uncompressed pubkey, skip encoding of a segwit program. if ((which_type == TX_PUBKEY) || (which_type == TX_MULTISIG)) { for (const auto& solution : solutions_data) { if ((solution.size() != 1) && !CPubKey(solution).IsCompressed()) { return r; } } } UniValue sr(UniValue::VOBJ); CScript segwitScr; if (which_type == TX_PUBKEY) { segwitScr = GetScriptForDestination(WitnessV0KeyHash(Hash160(solutions_data[0].begin(), solutions_data[0].end()))); } else if (which_type == TX_PUBKEYHASH) { segwitScr = GetScriptForDestination(WitnessV0KeyHash(solutions_data[0])); } else { // Scripts that are not fit for P2WPKH are encoded as P2WSH. // Newer segwit program versions should be considered when then become available. segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script)); } ScriptPubKeyToUniv(segwitScr, sr, /* fIncludeHex */ true); sr.pushKV("p2sh-segwit", EncodeDestination(ScriptHash(segwitScr))); r.pushKV("segwit", sr); } } return r; } static UniValue combinerawtransaction(const JSONRPCRequest& request) { RPCHelpMan{"combinerawtransaction", "\nCombine multiple partially signed transactions into one transaction.\n" "The combined transaction may be another partially signed transaction or a \n" "fully signed transaction.", { {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of hex strings of partially signed transactions", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A transaction hash"}, }, }, }, RPCResult{ "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n" }, RPCExamples{ HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]") }, }.Check(request); UniValue txs = request.params[0].get_array(); std::vector<CMutableTransaction> txVariants(txs.size()); for (unsigned int idx = 0; idx < txs.size(); idx++) { if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx)); } } if (txVariants.empty()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions"); } // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(cs_main); LOCK(mempool.cs); CCoinsViewCache &viewChain = ::ChainstateActive().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view for (const CTxIn& txin : mergedTx.vin) { view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail. } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } // Use CTransaction for the constant parts of the // transaction to avoid rehashing. const CTransaction txConst(mergedTx); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent"); } SignatureData sigdata; // ... and merge in other signatures: for (const CMutableTransaction& txv : txVariants) { if (txv.vin.size() > i) { sigdata.MergeSignatureData(DataFromTransaction(txv, i, coin.out)); } } ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(&mergedTx, i, coin.out.nValue, 1), coin.out.scriptPubKey, sigdata); UpdateInput(txin, sigdata); } return EncodeHexTx(CTransaction(mergedTx)); } static UniValue signrawtransactionwithkey(const JSONRPCRequest& request) { RPCHelpMan{"signrawtransactionwithkey", "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second argument is an array of base58-encoded private\n" "keys that will be the only keys used to sign the transaction.\n" "The third optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n", { {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"}, {"privkeys", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of base58-encoded private keys for signing", { {"privatekey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "private key in base58-encoding"}, }, }, {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "A json array of previous dependent transaction outputs", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "script key"}, {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"}, {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"}, {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"}, }, }, }, }, {"sighashtype", RPCArg::Type::STR, /* default */ "ALL", "The signature hash type. Must be one of:\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" }, }, RPCResult{ "{\n" " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n" " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n" " {\n" " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n" " \"vout\" : n, (numeric) The index of the output to spent and used as input\n" " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n" " \"sequence\" : n, (numeric) Script sequence number\n" " \"error\" : \"text\" (string) Verification or signing error related to the input\n" " }\n" " ,...\n" " ]\n" "}\n" }, RPCExamples{ HelpExampleCli("signrawtransactionwithkey", "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"") + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true); CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } FillableSigningProvider keystore; const UniValue& keys = request.params[1].get_array(); for (unsigned int idx = 0; idx < keys.size(); ++idx) { UniValue k = keys[idx]; CKey key = DecodeSecret(k.get_str()); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } keystore.AddKey(key); } // Fetch previous transactions (inputs): std::map<COutPoint, Coin> coins; for (const CTxIn& txin : mtx.vin) { coins[txin.prevout]; // Create empty map entry keyed by prevout. } FindCoins(coins); return SignTransaction(mtx, request.params[2], &keystore, coins, true, request.params[3]); } static UniValue sendrawtransaction(const JSONRPCRequest& request) { RPCHelpMan{"sendrawtransaction", "\nSubmit a raw transaction (serialized, hex-encoded) to local node and network.\n" "\nNote that the transaction will be sent unconditionally to all peers, so using this\n" "for manual rebroadcast may degrade privacy by leaking the transaction's origin, as\n" "nodes will normally not rebroadcast non-wallet transactions already in their mempool.\n" "\nAlso see createrawtransaction and signrawtransactionwithkey calls.\n", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"}, {"maxfeerate", RPCArg::Type::AMOUNT, /* default */ FormatMoney(DEFAULT_MAX_RAW_TX_FEE), "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT + "/kB.\nSet to 0 to accept any fee rate.\n"}, }, RPCResult{ "\"hex\" (string) The transaction hash in hex\n" }, RPCExamples{ "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"") }, }.Check(request); RPCTypeCheck(request.params, { UniValue::VSTR, UniValueType(), // NUM or BOOL, checked later }); // parse hex string from parameter CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); CTransactionRef tx(MakeTransactionRef(std::move(mtx))); CAmount max_raw_tx_fee = DEFAULT_MAX_RAW_TX_FEE; // TODO: temporary migration code for old clients. Remove in v0.20 if (request.params[1].isBool()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Second argument must be numeric (maxfeerate) and no longer supports a boolean. To allow a transaction with high fees, set maxfeerate to 0."); } else if (!request.params[1].isNull()) { size_t weight = GetTransactionWeight(*tx); CFeeRate fr(AmountFromValue(request.params[1])); // the +3/4 part rounds the value up, and is the same formula used when // calculating the fee for a transaction // (see GetVirtualTransactionSize) max_raw_tx_fee = fr.GetFee((weight+3)/4); } std::string err_string; AssertLockNotHeld(cs_main); const TransactionError err = BroadcastTransaction(tx, err_string, max_raw_tx_fee, /*relay*/ true, /*wait_callback*/ true); if (TransactionError::OK != err) { throw JSONRPCTransactionError(err, err_string); } return tx->GetHash().GetHex(); } static UniValue testmempoolaccept(const JSONRPCRequest& request) { RPCHelpMan{"testmempoolaccept", "\nReturns result of mempool acceptance tests indicating if raw transaction (serialized, hex-encoded) would be accepted by mempool.\n" "\nThis checks if the transaction violates the consensus or policy rules.\n" "\nSee sendrawtransaction call.\n", { {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings of raw transactions.\n" " Length must be one for now.", { {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""}, }, }, {"maxfeerate", RPCArg::Type::AMOUNT, /* default */ FormatMoney(DEFAULT_MAX_RAW_TX_FEE), "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT + "/kB\n"}, }, RPCResult{ "[ (array) The result of the mempool acceptance test for each raw transaction in the input array.\n" " Length is exactly one for now.\n" " {\n" " \"txid\" (string) The transaction hash in hex\n" " \"allowed\" (boolean) If the mempool allows this tx to be inserted\n" " \"reject-reason\" (string) Rejection string (only present when 'allowed' is false)\n" " }\n" "]\n" }, RPCExamples{ "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") + "\nTest acceptance of the transaction (signed hex)\n" + HelpExampleCli("testmempoolaccept", "[\"signedhex\"]") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]") }, }.Check(request); RPCTypeCheck(request.params, { UniValue::VARR, UniValueType(), // NUM or BOOL, checked later }); if (request.params[0].get_array().size() != 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Array must contain exactly one raw transaction for now"); } CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_array()[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } CTransactionRef tx(MakeTransactionRef(std::move(mtx))); const uint256& tx_hash = tx->GetHash(); CAmount max_raw_tx_fee = DEFAULT_MAX_RAW_TX_FEE; // TODO: temporary migration code for old clients. Remove in v0.20 if (request.params[1].isBool()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Second argument must be numeric (maxfeerate) and no longer supports a boolean. To allow a transaction with high fees, set maxfeerate to 0."); } else if (!request.params[1].isNull()) { size_t weight = GetTransactionWeight(*tx); CFeeRate fr(AmountFromValue(request.params[1])); // the +3/4 part rounds the value up, and is the same formula used when // calculating the fee for a transaction // (see GetVirtualTransactionSize) max_raw_tx_fee = fr.GetFee((weight+3)/4); } UniValue result(UniValue::VARR); UniValue result_0(UniValue::VOBJ); result_0.pushKV("txid", tx_hash.GetHex()); CValidationState state; bool missing_inputs; bool test_accept_res; { LOCK(cs_main); test_accept_res = AcceptToMemoryPool(mempool, state, std::move(tx), &missing_inputs, nullptr /* plTxnReplaced */, false /* bypass_limits */, max_raw_tx_fee, /* test_accept */ true); } result_0.pushKV("allowed", test_accept_res); if (!test_accept_res) { if (state.IsInvalid()) { result_0.pushKV("reject-reason", strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); } else if (missing_inputs) { result_0.pushKV("reject-reason", "missing-inputs"); } else { result_0.pushKV("reject-reason", state.GetRejectReason()); } } result.push_back(std::move(result_0)); return result; } static std::string WriteHDKeypath(std::vector<uint32_t>& keypath) { std::string keypath_str = "m"; for (uint32_t num : keypath) { keypath_str += "/"; bool hardened = false; if (num & 0x80000000) { hardened = true; num &= ~0x80000000; } keypath_str += std::to_string(num); if (hardened) { keypath_str += "'"; } } return keypath_str; } UniValue decodepsbt(const JSONRPCRequest& request) { RPCHelpMan{"decodepsbt", "\nReturn a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.\n", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The PSBT base64 string"}, }, RPCResult{ "{\n" " \"tx\" : { (json object) The decoded network-serialized unsigned transaction.\n" " ... The layout is the same as the output of decoderawtransaction.\n" " },\n" " \"unknown\" : { (json object) The unknown global fields\n" " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" " ...\n" " },\n" " \"inputs\" : [ (array of json objects)\n" " {\n" " \"non_witness_utxo\" : { (json object, optional) Decoded network transaction for non-witness UTXOs\n" " ...\n" " },\n" " \"witness_utxo\" : { (json object, optional) Transaction output for witness UTXOs\n" " \"amount\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"address\" : \"address\" (string) Bitcoin address if there is one\n" " }\n" " },\n" " \"partial_signatures\" : { (json object, optional)\n" " \"pubkey\" : \"signature\", (string) The public key and signature that corresponds to it.\n" " ,...\n" " }\n" " \"sighash\" : \"type\", (string, optional) The sighash type to be used\n" " \"redeem_script\" : { (json object, optional)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " }\n" " \"witness_script\" : { (json object, optional)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " }\n" " \"bip32_derivs\" : { (json object, optional)\n" " \"pubkey\" : { (json object, optional) The public key with the derivation path as the value.\n" " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n" " \"path\" : \"path\", (string) The path\n" " }\n" " ,...\n" " }\n" " \"final_scriptsig\" : { (json object, optional)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " }\n" " \"final_scriptwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n" " \"unknown\" : { (json object) The unknown global fields\n" " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" " ...\n" " },\n" " }\n" " ,...\n" " ]\n" " \"outputs\" : [ (array of json objects)\n" " {\n" " \"redeem_script\" : { (json object, optional)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " }\n" " \"witness_script\" : { (json object, optional)\n" " \"asm\" : \"asm\", (string) The asm\n" " \"hex\" : \"hex\", (string) The hex\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " }\n" " \"bip32_derivs\" : [ (array of json objects, optional)\n" " {\n" " \"pubkey\" : \"pubkey\", (string) The public key this path corresponds to\n" " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n" " \"path\" : \"path\", (string) The path\n" " }\n" " }\n" " ,...\n" " ],\n" " \"unknown\" : { (json object) The unknown global fields\n" " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" " ...\n" " },\n" " }\n" " ,...\n" " ]\n" " \"fee\" : fee (numeric, optional) The transaction fee paid if all UTXOs slots in the PSBT have been filled.\n" "}\n" }, RPCExamples{ HelpExampleCli("decodepsbt", "\"psbt\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR}); // Unserialize the transactions PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } UniValue result(UniValue::VOBJ); // Add the decoded tx UniValue tx_univ(UniValue::VOBJ); TxToUniv(CTransaction(*psbtx.tx), uint256(), tx_univ, false); result.pushKV("tx", tx_univ); // Unknown data UniValue unknowns(UniValue::VOBJ); for (auto entry : psbtx.unknown) { unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); } result.pushKV("unknown", unknowns); // inputs CAmount total_in = 0; bool have_all_utxos = true; UniValue inputs(UniValue::VARR); for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) { const PSBTInput& input = psbtx.inputs[i]; UniValue in(UniValue::VOBJ); // UTXOs if (!input.witness_utxo.IsNull()) { const CTxOut& txout = input.witness_utxo; UniValue out(UniValue::VOBJ); out.pushKV("amount", ValueFromAmount(txout.nValue)); total_in += txout.nValue; UniValue o(UniValue::VOBJ); ScriptToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); in.pushKV("witness_utxo", out); } else if (input.non_witness_utxo) { UniValue non_wit(UniValue::VOBJ); TxToUniv(*input.non_witness_utxo, uint256(), non_wit, false); in.pushKV("non_witness_utxo", non_wit); total_in += input.non_witness_utxo->vout[psbtx.tx->vin[i].prevout.n].nValue; } else { have_all_utxos = false; } // Partial sigs if (!input.partial_sigs.empty()) { UniValue partial_sigs(UniValue::VOBJ); for (const auto& sig : input.partial_sigs) { partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second)); } in.pushKV("partial_signatures", partial_sigs); } // Sighash if (input.sighash_type > 0) { in.pushKV("sighash", SighashToStr((unsigned char)input.sighash_type)); } // Redeem script and witness script if (!input.redeem_script.empty()) { UniValue r(UniValue::VOBJ); ScriptToUniv(input.redeem_script, r, false); in.pushKV("redeem_script", r); } if (!input.witness_script.empty()) { UniValue r(UniValue::VOBJ); ScriptToUniv(input.witness_script, r, false); in.pushKV("witness_script", r); } // keypaths if (!input.hd_keypaths.empty()) { UniValue keypaths(UniValue::VARR); for (auto entry : input.hd_keypaths) { UniValue keypath(UniValue::VOBJ); keypath.pushKV("pubkey", HexStr(entry.first)); keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint))); keypath.pushKV("path", WriteHDKeypath(entry.second.path)); keypaths.push_back(keypath); } in.pushKV("bip32_derivs", keypaths); } // Final scriptSig and scriptwitness if (!input.final_script_sig.empty()) { UniValue scriptsig(UniValue::VOBJ); scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true)); scriptsig.pushKV("hex", HexStr(input.final_script_sig)); in.pushKV("final_scriptSig", scriptsig); } if (!input.final_script_witness.IsNull()) { UniValue txinwitness(UniValue::VARR); for (const auto& item : input.final_script_witness.stack) { txinwitness.push_back(HexStr(item.begin(), item.end())); } in.pushKV("final_scriptwitness", txinwitness); } // Unknown data if (input.unknown.size() > 0) { UniValue unknowns(UniValue::VOBJ); for (auto entry : input.unknown) { unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); } in.pushKV("unknown", unknowns); } inputs.push_back(in); } result.pushKV("inputs", inputs); // outputs CAmount output_value = 0; UniValue outputs(UniValue::VARR); for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) { const PSBTOutput& output = psbtx.outputs[i]; UniValue out(UniValue::VOBJ); // Redeem script and witness script if (!output.redeem_script.empty()) { UniValue r(UniValue::VOBJ); ScriptToUniv(output.redeem_script, r, false); out.pushKV("redeem_script", r); } if (!output.witness_script.empty()) { UniValue r(UniValue::VOBJ); ScriptToUniv(output.witness_script, r, false); out.pushKV("witness_script", r); } // keypaths if (!output.hd_keypaths.empty()) { UniValue keypaths(UniValue::VARR); for (auto entry : output.hd_keypaths) { UniValue keypath(UniValue::VOBJ); keypath.pushKV("pubkey", HexStr(entry.first)); keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint))); keypath.pushKV("path", WriteHDKeypath(entry.second.path)); keypaths.push_back(keypath); } out.pushKV("bip32_derivs", keypaths); } // Unknown data if (output.unknown.size() > 0) { UniValue unknowns(UniValue::VOBJ); for (auto entry : output.unknown) { unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); } out.pushKV("unknown", unknowns); } outputs.push_back(out); // Fee calculation output_value += psbtx.tx->vout[i].nValue; } result.pushKV("outputs", outputs); if (have_all_utxos) { result.pushKV("fee", ValueFromAmount(total_in - output_value)); } return result; } UniValue combinepsbt(const JSONRPCRequest& request) { RPCHelpMan{"combinepsbt", "\nCombine multiple partially signed Bitcoin transactions into one transaction.\n" "Implements the Combiner role.\n", { {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of base64 strings of partially signed transactions", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A base64 string of a PSBT"}, }, }, }, RPCResult{ " \"psbt\" (string) The base64-encoded partially signed transaction\n" }, RPCExamples{ HelpExampleCli("combinepsbt", "[\"mybase64_1\", \"mybase64_2\", \"mybase64_3\"]") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VARR}, true); // Unserialize the transactions std::vector<PartiallySignedTransaction> psbtxs; UniValue txs = request.params[0].get_array(); if (txs.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txs' cannot be empty"); } for (unsigned int i = 0; i < txs.size(); ++i) { PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } psbtxs.push_back(psbtx); } PartiallySignedTransaction merged_psbt; const TransactionError error = CombinePSBTs(merged_psbt, psbtxs); if (error != TransactionError::OK) { throw JSONRPCTransactionError(error); } CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << merged_psbt; return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); } UniValue finalizepsbt(const JSONRPCRequest& request) { RPCHelpMan{"finalizepsbt", "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n" "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n" "created which has the final_scriptSig and final_scriptWitness fields filled for inputs that are complete.\n" "Implements the Finalizer and Extractor roles.\n", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}, {"extract", RPCArg::Type::BOOL, /* default */ "true", "If true and the transaction is complete,\n" " extract and return the complete transaction in normal network serialization instead of the PSBT."}, }, RPCResult{ "{\n" " \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction if not extracted\n" " \"hex\" : \"value\", (string) The hex-encoded network transaction if extracted\n" " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" " ]\n" "}\n" }, RPCExamples{ HelpExampleCli("finalizepsbt", "\"psbt\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true); // Unserialize the transactions PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } bool extract = request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool()); CMutableTransaction mtx; bool complete = FinalizeAndExtractPSBT(psbtx, mtx); UniValue result(UniValue::VOBJ); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); std::string result_str; if (complete && extract) { ssTx << mtx; result_str = HexStr(ssTx.str()); result.pushKV("hex", result_str); } else { ssTx << psbtx; result_str = EncodeBase64(ssTx.str()); result.pushKV("psbt", result_str); } result.pushKV("complete", complete); return result; } UniValue createpsbt(const JSONRPCRequest& request) { RPCHelpMan{"createpsbt", "\nCreates a transaction in the Partially Signed Transaction format.\n" "Implements the Creator role.\n", { {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of json objects", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"sequence", RPCArg::Type::NUM, /* default */ "depends on the value of the 'replaceable' and 'locktime' arguments", "The sequence number"}, }, }, }, }, {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "a json array with outputs (key-value pairs), where none of the keys are duplicated.\n" "That is, each address can only appear once and there can only be one 'data' object.\n" "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" " accepted as second parameter.", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT}, }, }, {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"}, }, }, }, }, {"locktime", RPCArg::Type::NUM, /* default */ "0", "Raw locktime. Non-0 value also locktime-activates inputs"}, {"replaceable", RPCArg::Type::BOOL, /* default */ "false", "Marks this transaction as BIP125 replaceable.\n" " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."}, }, RPCResult{ " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n" }, RPCExamples{ HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") }, }.Check(request); RPCTypeCheck(request.params, { UniValue::VARR, UniValueType(), // ARR or OBJ, checked later UniValue::VNUM, UniValue::VBOOL, }, true ); bool rbf = false; if (!request.params[3].isNull()) { rbf = request.params[3].isTrue(); } CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf); // Make a blank psbt PartiallySignedTransaction psbtx; psbtx.tx = rawTx; for (unsigned int i = 0; i < rawTx.vin.size(); ++i) { psbtx.inputs.push_back(PSBTInput()); } for (unsigned int i = 0; i < rawTx.vout.size(); ++i) { psbtx.outputs.push_back(PSBTOutput()); } // Serialize the PSBT CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); } UniValue converttopsbt(const JSONRPCRequest& request) { RPCHelpMan{"converttopsbt", "\nConverts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n" "createpsbt and walletcreatefundedpsbt should be used for new applications.\n", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of a raw transaction"}, {"permitsigdata", RPCArg::Type::BOOL, /* default */ "false", "If true, any signatures in the input will be discarded and conversion\n" " will continue. If false, RPC will fail if any signatures are present."}, {"iswitness", RPCArg::Type::BOOL, /* default */ "depends on heuristic tests", "Whether the transaction hex is a serialized witness transaction.\n" "If iswitness is not present, heuristic tests will be used in decoding.\n" "If true, only witness deserialization will be tried.\n" "If false, only non-witness deserialization will be tried.\n" "This boolean should reflect whether the transaction has inputs\n" "(e.g. fully valid, or on-chain transactions), if known by the caller." }, }, RPCResult{ " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n" }, RPCExamples{ "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + "\nConvert the transaction to a PSBT\n" + HelpExampleCli("converttopsbt", "\"rawtransaction\"") }, }.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL}, true); // parse hex string from parameter CMutableTransaction tx; bool permitsigdata = request.params[1].isNull() ? false : request.params[1].get_bool(); bool witness_specified = !request.params[2].isNull(); bool iswitness = witness_specified ? request.params[2].get_bool() : false; const bool try_witness = witness_specified ? iswitness : true; const bool try_no_witness = witness_specified ? !iswitness : true; if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } // Remove all scriptSigs and scriptWitnesses from inputs for (CTxIn& input : tx.vin) { if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && !permitsigdata) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses"); } input.scriptSig.clear(); input.scriptWitness.SetNull(); } // Make a blank psbt PartiallySignedTransaction psbtx; psbtx.tx = tx; for (unsigned int i = 0; i < tx.vin.size(); ++i) { psbtx.inputs.push_back(PSBTInput()); } for (unsigned int i = 0; i < tx.vout.size(); ++i) { psbtx.outputs.push_back(PSBTOutput()); } // Serialize the PSBT CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); } UniValue utxoupdatepsbt(const JSONRPCRequest& request) { RPCHelpMan{"utxoupdatepsbt", "\nUpdates all segwit inputs and outputs in a PSBT with data from output descriptors, the UTXO set or the mempool.\n", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}, {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "An array of either strings or objects", { {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"}, {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", { {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"}, {"range", RPCArg::Type::RANGE, "1000", "Up to what index HD chains should be explored (either end or [begin,end])"}, }}, }}, }, RPCResult { " \"psbt\" (string) The base64-encoded partially signed transaction with inputs updated\n" }, RPCExamples { HelpExampleCli("utxoupdatepsbt", "\"psbt\"") }}.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR}, true); // Unserialize the transactions PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } // Parse descriptors, if any. FlatSigningProvider provider; if (!request.params[1].isNull()) { auto descs = request.params[1].get_array(); for (size_t i = 0; i < descs.size(); ++i) { EvalDescriptorStringOrObject(descs[i], provider); } } // We don't actually need private keys further on; hide them as a precaution. HidingSigningProvider public_provider(&provider, /* nosign */ true, /* nobip32derivs */ false); // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK2(cs_main, mempool.cs); CCoinsViewCache &viewChain = ::ChainstateActive().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view for (const CTxIn& txin : psbtx.tx->vin) { view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail. } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } // Fill the inputs for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) { PSBTInput& input = psbtx.inputs.at(i); if (input.non_witness_utxo || !input.witness_utxo.IsNull()) { continue; } const Coin& coin = view.AccessCoin(psbtx.tx->vin[i].prevout); if (IsSegWitOutput(provider, coin.out.scriptPubKey)) { input.witness_utxo = coin.out; } // Update script/keypath information using descriptor data. // Note that SignPSBTInput does a lot more than just constructing ECDSA signatures // we don't actually care about those here, in fact. SignPSBTInput(public_provider, psbtx, i, /* sighash_type */ 1); } // Update script/keypath information using descriptor data. for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) { UpdatePSBTOutput(public_provider, psbtx, i); } CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); } UniValue joinpsbts(const JSONRPCRequest& request) { RPCHelpMan{"joinpsbts", "\nJoins multiple distinct PSBTs with different inputs and outputs into one PSBT with inputs and outputs from all of the PSBTs\n" "No input in any of the PSBTs can be in more than one of the PSBTs.\n", { {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of base64 strings of partially signed transactions", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"} }} }, RPCResult { " \"psbt\" (string) The base64-encoded partially signed transaction\n" }, RPCExamples { HelpExampleCli("joinpsbts", "\"psbt\"") }}.Check(request); RPCTypeCheck(request.params, {UniValue::VARR}, true); // Unserialize the transactions std::vector<PartiallySignedTransaction> psbtxs; UniValue txs = request.params[0].get_array(); if (txs.size() <= 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "At least two PSBTs are required to join PSBTs."); } int32_t best_version = 1; uint32_t best_locktime = 0xffffffff; for (unsigned int i = 0; i < txs.size(); ++i) { PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } psbtxs.push_back(psbtx); // Choose the highest version number if (psbtx.tx->nVersion > best_version) { best_version = psbtx.tx->nVersion; } // Choose the lowest lock time if (psbtx.tx->nLockTime < best_locktime) { best_locktime = psbtx.tx->nLockTime; } } // Create a blank psbt where everything will be added PartiallySignedTransaction merged_psbt; merged_psbt.tx = CMutableTransaction(); merged_psbt.tx->nVersion = best_version; merged_psbt.tx->nLockTime = best_locktime; // Merge for (auto& psbt : psbtxs) { for (unsigned int i = 0; i < psbt.tx->vin.size(); ++i) { if (!merged_psbt.AddInput(psbt.tx->vin[i], psbt.inputs[i])) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input %s:%d exists in multiple PSBTs", psbt.tx->vin[i].prevout.hash.ToString().c_str(), psbt.tx->vin[i].prevout.n)); } } for (unsigned int i = 0; i < psbt.tx->vout.size(); ++i) { merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]); } merged_psbt.unknown.insert(psbt.unknown.begin(), psbt.unknown.end()); } CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << merged_psbt; return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); } UniValue analyzepsbt(const JSONRPCRequest& request) { RPCHelpMan{"analyzepsbt", "\nAnalyzes and provides information about the current status of a PSBT and its inputs\n", { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"} }, RPCResult { "{\n" " \"inputs\" : [ (array of json objects)\n" " {\n" " \"has_utxo\" : true|false (boolean) Whether a UTXO is provided\n" " \"is_final\" : true|false (boolean) Whether the input is finalized\n" " \"missing\" : { (json object, optional) Things that are missing that are required to complete this input\n" " \"pubkeys\" : [ (array, optional)\n" " \"keyid\" (string) Public key ID, hash160 of the public key, of a public key whose BIP 32 derivation path is missing\n" " ]\n" " \"signatures\" : [ (array, optional)\n" " \"keyid\" (string) Public key ID, hash160 of the public key, of a public key whose signature is missing\n" " ]\n" " \"redeemscript\" : \"hash\" (string, optional) Hash160 of the redeemScript that is missing\n" " \"witnessscript\" : \"hash\" (string, optional) SHA256 of the witnessScript that is missing\n" " }\n" " \"next\" : \"role\" (string, optional) Role of the next person that this input needs to go to\n" " }\n" " ,...\n" " ]\n" " \"estimated_vsize\" : vsize (numeric, optional) Estimated vsize of the final signed transaction\n" " \"estimated_feerate\" : feerate (numeric, optional) Estimated feerate of the final signed transaction in " + CURRENCY_UNIT + "/kB. Shown only if all UTXO slots in the PSBT have been filled.\n" " \"fee\" : fee (numeric, optional) The transaction fee paid. Shown only if all UTXO slots in the PSBT have been filled.\n" " \"next\" : \"role\" (string) Role of the next person that this psbt needs to go to\n" "}\n" }, RPCExamples { HelpExampleCli("analyzepsbt", "\"psbt\"") }}.Check(request); RPCTypeCheck(request.params, {UniValue::VSTR}); // Unserialize the transaction PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } PSBTAnalysis psbta = AnalyzePSBT(psbtx); UniValue result(UniValue::VOBJ); UniValue inputs_result(UniValue::VARR); for (const auto& input : psbta.inputs) { UniValue input_univ(UniValue::VOBJ); UniValue missing(UniValue::VOBJ); input_univ.pushKV("has_utxo", input.has_utxo); input_univ.pushKV("is_final", input.is_final); input_univ.pushKV("next", PSBTRoleName(input.next)); if (!input.missing_pubkeys.empty()) { UniValue missing_pubkeys_univ(UniValue::VARR); for (const CKeyID& pubkey : input.missing_pubkeys) { missing_pubkeys_univ.push_back(HexStr(pubkey)); } missing.pushKV("pubkeys", missing_pubkeys_univ); } if (!input.missing_redeem_script.IsNull()) { missing.pushKV("redeemscript", HexStr(input.missing_redeem_script)); } if (!input.missing_witness_script.IsNull()) { missing.pushKV("witnessscript", HexStr(input.missing_witness_script)); } if (!input.missing_sigs.empty()) { UniValue missing_sigs_univ(UniValue::VARR); for (const CKeyID& pubkey : input.missing_sigs) { missing_sigs_univ.push_back(HexStr(pubkey)); } missing.pushKV("signatures", missing_sigs_univ); } if (!missing.getKeys().empty()) { input_univ.pushKV("missing", missing); } inputs_result.push_back(input_univ); } result.pushKV("inputs", inputs_result); if (psbta.estimated_vsize != nullopt) { result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize); } if (psbta.estimated_feerate != nullopt) { result.pushKV("estimated_feerate", ValueFromAmount(psbta.estimated_feerate->GetFeePerK())); } if (psbta.fee != nullopt) { result.pushKV("fee", ValueFromAmount(*psbta.fee)); } result.pushKV("next", PSBTRoleName(psbta.next)); return result; } // clang-format off static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose","blockhash"} }, { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} }, { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring","iswitness"} }, { "rawtransactions", "decodescript", &decodescript, {"hexstring"} }, { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees|maxfeerate"} }, { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} }, { "rawtransactions", "signrawtransactionwithkey", &signrawtransactionwithkey, {"hexstring","privkeys","prevtxs","sighashtype"} }, { "rawtransactions", "testmempoolaccept", &testmempoolaccept, {"rawtxs","allowhighfees|maxfeerate"} }, { "rawtransactions", "decodepsbt", &decodepsbt, {"psbt"} }, { "rawtransactions", "combinepsbt", &combinepsbt, {"txs"} }, { "rawtransactions", "finalizepsbt", &finalizepsbt, {"psbt", "extract"} }, { "rawtransactions", "createpsbt", &createpsbt, {"inputs","outputs","locktime","replaceable"} }, { "rawtransactions", "converttopsbt", &converttopsbt, {"hexstring","permitsigdata","iswitness"} }, { "rawtransactions", "utxoupdatepsbt", &utxoupdatepsbt, {"psbt", "descriptors"} }, { "rawtransactions", "joinpsbts", &joinpsbts, {"txs"} }, { "rawtransactions", "analyzepsbt", &analyzepsbt, {"psbt"} }, { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} }, { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} }, }; // clang-format on void RegisterRawTransactionRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 009614 move.l D2, (A0)+ [base+ 3C, base+ 4C, base+ 4E, base+ 5C, base+ 5E, base+ EC, base+ EE, base+ FC, base+ FE, base+16C, base+16E, base+17C, base+17E, base+20C, base+20E, base+21C, base+21E, base+28C, base+28E, base+29C, base+29E, base+2AC, base+2AE, base+2BC, base+2BE, base+32C, base+32E, base+33C, base+33E, base+3CC, base+3CE, base+3DC, base+3DE, base+42E] 009616 addi.w #$10, D3 009690 move.l D2, (A0)+ [base+ 3C, base+ 4C, base+ 4E, base+ 5C, base+ 5E, base+ EC, base+ EE, base+ FC, base+ FE, base+16C, base+16E, base+17C, base+17E, base+20C, base+20E, base+21C, base+21E, base+28C, base+28E, base+29C, base+29E, base+2AC, base+2AE, base+2BC, base+2BE, base+32C, base+32E, base+33C, base+33E, base+3CC, base+3CE, base+3DC, base+3DE, base+42E] 009692 addi.w #$10, D3 [base+ 40, base+ 50, base+ 52, base+ 60, base+ 62, base+ E0, base+ E2, base+ F0, base+ F2, base+100, base+102, base+170, base+172, base+180, base+182, base+210, base+212, base+220, base+222, base+290, base+292, base+2A0, base+2A2, base+2B0, base+2B2, base+330, base+332, base+340, base+342, base+3C0, base+3C2, base+3D0, base+3D2, base+432] 00977C move.l D2, (A0)+ [base+ 3C, base+ 3E, base+ 4C, base+ 4E, base+ 5C, base+ 5E, base+ 8C, base+ 8E, base+ BC, base+ BE, base+11C, base+11E, base+1BC, base+1BE, base+1DC, base+1DE, base+33C, base+33E, base+37C, base+37E, base+39C, base+39E, base+3BC, base+3BE, base+3FC, base+3FE, base+42C, base+42E] 00977E addi.w #$10, D3 00A61C move.l D1, (A0)+ 00A61E move.l D1, (A0)+ 00A64E move.l D2, (A0)+ [base+ 3C, base+ 4C, base+ 4E, base+ 5C, base+ 5E, base+ EC, base+ EE, base+ FC, base+ FE, base+16C, base+16E, base+17C, base+17E, base+20C, base+20E, base+21C, base+21E, base+28C, base+28E, base+29C, base+29E, base+2AC, base+2AE, base+2BC, base+2BE, base+32C, base+32E, base+33C, base+33E, base+3CC, base+3CE, base+3DC, base+3DE, base+42E] 00A650 addi.w #$10, D6 [base+ 40, base+ 50, base+ 52, base+ 60, base+ 62, base+ E0, base+ E2, base+ F0, base+ F2, base+100, base+102, base+170, base+172, base+180, base+182, base+210, base+212, base+220, base+222, base+290, base+292, base+2A0, base+2A2, base+2B0, base+2B2, base+330, base+332, base+340, base+342, base+3C0, base+3C2, base+3D0, base+3D2, base+432] 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11 // <propagate_const> // propagate_const::operator element_type*(); #include <experimental/propagate_const> #include "test_macros.h" #include "propagate_const_helpers.h" #include <type_traits> using std::experimental::propagate_const; typedef propagate_const<X> P; int main(int, char**) { static_assert(!std::is_convertible<P, int *>::value, ""); return 0; }
/* * Copyright (c) 2017-2018, The Alloy Developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of Alloy. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #include "TransactionExtra.h" #include "Common/MemoryInputStream.h" #include "Common/StreamTools.h" #include "Common/StringTools.h" #include "CryptoNoteTools.h" #include "Serialization/BinaryOutputStreamSerializer.h" #include "Serialization/BinaryInputStreamSerializer.h" using namespace Crypto; using namespace Common; namespace CryptoNote { bool parseTransactionExtra(const std::vector<uint8_t> &transactionExtra, std::vector<TransactionExtraField> &transactionExtraFields) { transactionExtraFields.clear(); if (transactionExtra.empty()) return true; try { MemoryInputStream iss(transactionExtra.data(), transactionExtra.size()); BinaryInputStreamSerializer ar(iss); int c = 0; while (!iss.endOfStream()) { c = read<uint8_t>(iss); switch (c) { case TX_EXTRA_TAG_PADDING: { size_t size = 1; for (; !iss.endOfStream() && size <= TX_EXTRA_PADDING_MAX_COUNT; ++size) { if (read<uint8_t>(iss) != 0) { return false; // all bytes should be zero } } if (size > TX_EXTRA_PADDING_MAX_COUNT) { return false; } transactionExtraFields.push_back(TransactionExtraPadding{ size }); break; } case TX_EXTRA_TAG_PUBKEY: { TransactionExtraPublicKey extraPk; ar(extraPk.publicKey, "public_key"); transactionExtraFields.push_back(extraPk); break; } case TX_EXTRA_NONCE: { TransactionExtraNonce extraNonce; uint8_t size = read<uint8_t>(iss); if (size > 0) { extraNonce.nonce.resize(size); read(iss, extraNonce.nonce.data(), extraNonce.nonce.size()); } transactionExtraFields.push_back(extraNonce); break; } case TX_EXTRA_MERGE_MINING_TAG: { TransactionExtraMergeMiningTag mmTag; ar(mmTag, "mm_tag"); transactionExtraFields.push_back(mmTag); break; } } } } catch (std::exception &) { return false; } return true; } struct ExtraSerializerVisitor : public boost::static_visitor<bool> { std::vector<uint8_t>& extra; ExtraSerializerVisitor(std::vector<uint8_t>& tx_extra) : extra(tx_extra) {} bool operator()(const TransactionExtraPadding& t) { if (t.size > TX_EXTRA_PADDING_MAX_COUNT) { return false; } extra.insert(extra.end(), t.size, 0); return true; } bool operator()(const TransactionExtraPublicKey& t) { return addTransactionPublicKeyToExtra(extra, t.publicKey); } bool operator()(const TransactionExtraNonce& t) { return addExtraNonceToTransactionExtra(extra, t.nonce); } bool operator()(const TransactionExtraMergeMiningTag& t) { return appendMergeMiningTagToExtra(extra, t); } }; bool writeTransactionExtra(std::vector<uint8_t>& tx_extra, const std::vector<TransactionExtraField>& tx_extra_fields) { ExtraSerializerVisitor visitor(tx_extra); for (const auto& tag : tx_extra_fields) { if (!boost::apply_visitor(visitor, tag)) { return false; } } return true; } PublicKey getTransactionPublicKeyFromExtra(const std::vector<uint8_t>& tx_extra) { std::vector<TransactionExtraField> tx_extra_fields; parseTransactionExtra(tx_extra, tx_extra_fields); TransactionExtraPublicKey pub_key_field; if (!findTransactionExtraFieldByType(tx_extra_fields, pub_key_field)) return boost::value_initialized<PublicKey>(); return pub_key_field.publicKey; } bool addTransactionPublicKeyToExtra(std::vector<uint8_t>& tx_extra, const PublicKey& tx_pub_key) { tx_extra.resize(tx_extra.size() + 1 + sizeof(PublicKey)); tx_extra[tx_extra.size() - 1 - sizeof(PublicKey)] = TX_EXTRA_TAG_PUBKEY; *reinterpret_cast<PublicKey*>(&tx_extra[tx_extra.size() - sizeof(PublicKey)]) = tx_pub_key; return true; } bool addExtraNonceToTransactionExtra(std::vector<uint8_t>& tx_extra, const BinaryArray& extra_nonce) { if (extra_nonce.size() > TX_EXTRA_NONCE_MAX_COUNT) { return false; } size_t start_pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size()); //write tag tx_extra[start_pos] = TX_EXTRA_NONCE; //write len ++start_pos; tx_extra[start_pos] = static_cast<uint8_t>(extra_nonce.size()); //write data ++start_pos; memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size()); return true; } bool appendMergeMiningTagToExtra(std::vector<uint8_t>& tx_extra, const TransactionExtraMergeMiningTag& mm_tag) { BinaryArray blob; if (!toBinaryArray(mm_tag, blob)) { return false; } tx_extra.push_back(TX_EXTRA_MERGE_MINING_TAG); std::copy(reinterpret_cast<const uint8_t*>(blob.data()), reinterpret_cast<const uint8_t*>(blob.data() + blob.size()), std::back_inserter(tx_extra)); return true; } bool getMergeMiningTagFromExtra(const std::vector<uint8_t>& tx_extra, TransactionExtraMergeMiningTag& mm_tag) { std::vector<TransactionExtraField> tx_extra_fields; parseTransactionExtra(tx_extra, tx_extra_fields); return findTransactionExtraFieldByType(tx_extra_fields, mm_tag); } void setPaymentIdToTransactionExtraNonce(std::vector<uint8_t>& extra_nonce, const Hash& payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID); const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } bool getPaymentIdFromTransactionExtraNonce(const std::vector<uint8_t>& extra_nonce, Hash& payment_id) { if (sizeof(Hash) + 1 != extra_nonce.size()) return false; if (TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast<const Hash*>(extra_nonce.data() + 1); return true; } bool parsePaymentId(const std::string& paymentIdString, Hash& paymentId) { return Common::podFromHex(paymentIdString, paymentId); } bool createTxExtraWithPaymentId(const std::string& paymentIdString, std::vector<uint8_t>& extra) { Hash paymentIdBin; if (!parsePaymentId(paymentIdString, paymentIdBin)) { return false; } std::vector<uint8_t> extraNonce; CryptoNote::setPaymentIdToTransactionExtraNonce(extraNonce, paymentIdBin); if (!CryptoNote::addExtraNonceToTransactionExtra(extra, extraNonce)) { return false; } return true; } bool getPaymentIdFromTxExtra(const std::vector<uint8_t>& extra, Hash& paymentId) { std::vector<TransactionExtraField> tx_extra_fields; if (!parseTransactionExtra(extra, tx_extra_fields)) { return false; } TransactionExtraNonce extra_nonce; if (findTransactionExtraFieldByType(tx_extra_fields, extra_nonce)) { if (!getPaymentIdFromTransactionExtraNonce(extra_nonce.nonce, paymentId)) { return false; } } else { return false; } return true; } }
db DEX_STARMIE ; pokedex id db 60 ; base hp db 75 ; base attack db 85 ; base defense db 115 ; base speed db 100 ; base special db WATER ; species type 1 db PSYCHIC ; species type 2 db 60 ; catch rate db 207 ; base exp yield INCBIN "pic/ymon/starmie.pic",0,1 ; 66, sprite dimensions dw StarmiePicFront dw StarmiePicBack ; attacks known at lvl 0 db TACKLE db WATER_GUN db HARDEN db CONFUSION db 5 ; growth rate ; learnset tmlearn 6 tmlearn 9,10,11,12,13,14,15 tmlearn 20,24 tmlearn 25,29,30,31,32 tmlearn 33,34,39,40 tmlearn 44,45,46 tmlearn 49,50,53,55 db BANK(StarmiePicFront)
/* * Test for temporarily blocked interrupts */ lc r100, 0x10000000 // test result output pointer lc r101, halt lc r102, failure lc r103, 0x20000000 // timer: number of pulses (0xFFFFFFFF - infinite) lc r104, 0x20000004 // timer: delay between pulses (in cycles) lc iv0, timer_handler lc cr, 0x101 // enable interrupt 0 in temporarily blocked state lc r32, 0 // interrupt handler call counter lc r33, 1000 // loop counter lc r34, loop1 lc r35, loop2 sw r104, 100 sw r103, 1 loop1: sub r33, r33, 1 cjmpug r34, r33, 0 // loop1 lc r33, 1000 mov cr, 1 // unblock interrupt 0 loop2: sub r33, r33, 1 cjmpug r35, r33, 0 // loop2 // r32 should be 1 by this point cjmpne r102, r32, 1 // failure sw r100, 1 jmp r101 // halt failure: sw r100, 2 halt: hlt jmp r101 // halt timer_handler: add r32, r32, 1 iret
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock("0x14dc23f54de47df797172d66531e7a115b782e65f69dda7bf5a4e98fac0ae086"); static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // starting difficulty is 1 / 2^12 CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "DamnCoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; int64 nMinimumInputValue = CENT / 100; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { if (nVersion > CTransaction::CURRENT_VERSION) return false; BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, true, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n", hash.ToString().substr(0,10).c_str(), mapTx.size()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+10) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = 5 * COIN; //Amt of coins per block // if(nHeight < 17280) // no block reward within the first 3 days // nSubsidy = 0; if(nHeight > 10519200) // no block reward after 5 years nSubsidy = 0; return nSubsidy + nFees; } static const int64 nTargetTimespan = 0.35 * 24 * 60 * 60; // DamnCoin: 0.35 days static const int64 nTargetSpacing = 15; // DamnCoin: 15 seconds static const int64 nInterval = nTargetTimespan / nTargetSpacing; // Thanks: Balthazar for suggesting the following fix // https://bitcointalk.org/index.php?topic=182430.msg1904506#msg1904506 static const int64 nReTargetHistoryFact = 4; // look at 4 times the retarget // interval into the block history // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special difficulty rule for testnet: if (fTestNet) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; if (pindexLast->nHeight > COINFIX1_BLOCK) { blockstogoback = nReTargetHistoryFact * nInterval; } // Go back by what we want to be nReTargetHistoryFact*nInterval blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = 0; if (pindexLast->nHeight > COINFIX1_BLOCK) // obtain average actual timespan nActualTimespan = (pindexLast->GetBlockTime() - pindexFirst->GetBlockTime())/nReTargetHistoryFact; else nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal DamnCoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC. int64 nBIP30SwitchTime = 1349049600; bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime); // BIP16 didn't become active until October 1 2012 int64 nBIP16SwitchTime = 1349049600; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); if (fEnforceBIP30) { CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); // if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: // strMiscWarning = _("Warning: this version is obsolete, upgrade required"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (!CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "DamnCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc0; pchMessageStart[2] = 0xb8; pchMessageStart[3] = 0xdb; hashGenesisBlock = uint256("0xa50faf35e1dddf4a076a907fbcef6d9d1595390cdb1c818a35dae53b67ad0aa8"); } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis block: /* block.nTime = 1399574511 block.nNonce = 2086299649 block.GetHash = 14dc23f54de47df797172d66531e7a115b782e65f69dda7bf5a4e98fac0ae086 CBlock(hash=14dc23f54de47df79717, PoW=00000aeb1f05fbf0b2fa, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=ef7e256a2c, nTime=1399574511, nBits=1e0ffff0, nNonce=2086299649, vtx=1) CTransaction(hash=ef7e256a2c, ver=1, vin.size=1, vout.size=1, nLockTime=0) CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d010414466972737420646179206f662050726f6a656374) CTxOut(error) vMerkleTree: ef7e256a2c */ // Genesis block const char* pszTimestamp = "First day of Project"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 0; txNew.vout[0].scriptPubKey = CScript() << 0x0 << OP_CHECKSIG; // a privkey for that 'vanity' pubkey would be interesting ;) CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1514372784; block.nBits = 0x1e0ffff0; block.nNonce = 2086299649; if (fTestNet) { block.nTime = 1514372784; block.nNonce = 386402991; } //// debug print printf("%s\n", block.GetHash().ToString().c_str()); printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0xef7e256a2cf2d38576225af2775a1e8160928a0c78526ab3615615d1ff16870e")); // If genesis block hash does not match, then generate new genesis hash. if (true && block.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) break; if ((block.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); printf("block.GetHash = %s\n", block.GetHash().ToString().c_str()); } block.print(); assert(block.GetHash() == hashGenesisBlock); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file\n", nLoaded); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI if it applies to me if(AppliesToMe()) uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xfc, 0xd9, 0xb7, 0xdd }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%d invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Don't bother if send buffer is too full to respond anyway if (pfrom->vSend.size() >= SendBufferSize()) break; // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size // Litecoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes) bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetPoWHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); loop { unsigned int nHashesDone = 0; //unsigned int nNonceFound; uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (pblock->nNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
; A121907: Expansion of g.f.: (1 + x + x^2)/(1 - 2*x - 2*x^2). ; 1,3,9,24,66,180,492,1344,3672,10032,27408,74880,204576,558912,1526976,4171776,11397504,31138560,85072128,232421376,634987008,1734816768,4739607552,12948848640,35376912384,96651522048,264056868864,721416781824,1970947301376,5384728166400,14711350935552,40192158203904,109807018278912,299998352965632,819610742489088,2239218190909440,6117657866797056,16713752115412992,45662819964420096,124753144159666176,340831928248172544,931170144815677440,2544004146127699968,6950348581886754816,18988705456028909568,51878108075831328768,141733627063720476672,387223470279103610880,1057914194685648175104,2890275329929503571968,7896379049230303494144,21573308758319614132224,58939375615099835252736,161025368746838898769920,439929488723877468045312,1201909714941432733630464,3283678407330620403351552,8971176244544106273964032,24509709303749453354631168,66961771096587119257190400,182942960800673145223643136,499809463794520528961667072,1365504849190387348370620416,3730628625969815754664574976,10192266950320406206070390784,27845791152580443921469931520,76076116205801700255080644608,207843814716764288353101152256,567839861845131977216363593728,1551367353123792531138929491968,4238414429937849016710586171392,11579563566123283095699031326720,31635955992122264224819234996224,86431039116491094641036532645888,236133990217226717731711535284224,645130058667435624745496135860224,1762528097769324684954415342288896,4815316312873520619399822956298240,13155688821285690608708476597174272,35942010268318422456216599106945024,98195398179208226129850151408238592,268274816895053297172133501030367232,732940430148523046603967304877211648 add $0,1 seq $0,2605 ; a(n) = 2*(a(n-1) + a(n-2)), a(0) = 0, a(1) = 1. mul $0,6 div $0,4