text
stringlengths 5
1.04M
|
|---|
#include "EditorLayer.h"
#include <imgui/imgui.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "QAQ/Scene/SceneSerializer.h"
#include "QAQ/Utils/PlatformUtils.h"
#include "ImGuizmo.h"
#include "QAQ/Math/Math.h"
namespace QAQ
{
EditorLayer::EditorLayer()
: Layer("EditorLayer"), m_CameraController(1280.0f / 720.0f), m_SquareColor({0.2f, 0.3f, 0.8f, 1.0f})
{
}
void EditorLayer::OnAttach()
{
QAQ_PROFILE_FUNCTION();
m_CheckerboardTexture = Texture2D::Create("assets/textures/Checkerboard.png");
FramebufferSpecification fbSpec;
fbSpec.Attachments = {FramebufferTextureFormat::RGBA8, FramebufferTextureFormat::RED_INTEGER, FramebufferTextureFormat::Depth};
fbSpec.Width = 1280;
fbSpec.Height = 720;
m_Framebuffer = Framebuffer::Create(fbSpec);
m_ActiveScene = CreateRef<Scene>();
auto commandLineArgs = Application::Get().GetCommandLineArgs();
if (commandLineArgs.Count > 1)
{
auto sceneFilePath = commandLineArgs[1];
SceneSerializer serializer(m_ActiveScene);
serializer.Deserialize(sceneFilePath);
}
m_EditorCamera = EditorCamera(30.0f, 1.778f, 0.1f, 1000.0f);
#if 0
// Entity
auto square = m_ActiveScene->CreateEntity("Green Square");
square.AddComponent<SpriteRendererComponent>(glm::vec4{0.0f, 1.0f, 0.0f, 1.0f});
auto redSquare = m_ActiveScene->CreateEntity("Red Square");
redSquare.AddComponent<SpriteRendererComponent>(glm::vec4{ 1.0f, 0.0f, 0.0f, 1.0f });
m_SquareEntity = square;
m_CameraEntity = m_ActiveScene->CreateEntity("Camera A");
m_CameraEntity.AddComponent<CameraComponent>();
m_SecondCamera = m_ActiveScene->CreateEntity("Camera B");
auto& cc = m_SecondCamera.AddComponent<CameraComponent>();
cc.Primary = false;
class CameraController : public ScriptableEntity
{
public:
virtual void OnCreate() override
{
auto& translation = GetComponent<TransformComponent>().Translation;
translation.x = rand() % 10 - 5.0f;
}
virtual void OnDestroy() override
{
}
virtual void OnUpdate(Timestep ts) override
{
auto& translation = GetComponent<TransformComponent>().Translation;
float speed = 5.0f;
if (Input::IsKeyPressed(Key::A))
translation.x -= speed * ts;
if (Input::IsKeyPressed(Key::D))
translation.x += speed * ts;
if (Input::IsKeyPressed(Key::W))
translation.y += speed * ts;
if (Input::IsKeyPressed(Key::S))
translation.y -= speed * ts;
}
};
m_CameraEntity.AddComponent<NativeScriptComponent>().Bind<CameraController>();
m_SecondCamera.AddComponent<NativeScriptComponent>().Bind<CameraController>();
#endif
m_SceneHierarchyPanel.SetContext(m_ActiveScene);
}
void EditorLayer::OnDetach()
{
QAQ_PROFILE_FUNCTION();
}
void EditorLayer::OnUpdate(Timestep ts)
{
QAQ_PROFILE_FUNCTION();
// Resize
if (FramebufferSpecification spec = m_Framebuffer->GetSpecification();
m_ViewportSize.x > 0.0f && m_ViewportSize.y > 0.0f && // zero sized framebuffer is invalid
(spec.Width != m_ViewportSize.x || spec.Height != m_ViewportSize.y))
{
m_Framebuffer->Resize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
m_CameraController.OnResize(m_ViewportSize.x, m_ViewportSize.y);
m_EditorCamera.SetViewportSize(m_ViewportSize.x, m_ViewportSize.y);
m_ActiveScene->OnViewportResize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
}
// Update
if (m_ViewportFocused)
m_CameraController.OnUpdate(ts);
m_EditorCamera.OnUpdate(ts);
// Render
Renderer2D::ResetStats();
m_Framebuffer->Bind();
RenderCommand::SetClearColor({0.1f, 0.1f, 0.1f, 1});
RenderCommand::Clear();
// Clear our entity ID attachment to -1
m_Framebuffer->ClearAttachment(1, -1);
// Update scene
m_ActiveScene->OnUpdateEditor(ts, m_EditorCamera);
auto [mx, my] = ImGui::GetMousePos();
mx -= m_ViewportBounds[0].x;
my -= m_ViewportBounds[0].y;
glm::vec2 viewportSize = m_ViewportBounds[1] - m_ViewportBounds[0];
my = viewportSize.y - my;
int mouseX = (int)mx;
int mouseY = (int)my;
if (mouseX >= 0 && mouseY >= 0 && mouseX < (int)viewportSize.x && mouseY < (int)viewportSize.y)
{
int pixelData = m_Framebuffer->ReadPixel(1, mouseX, mouseY);
m_HoveredEntity = pixelData == -1 ? Entity() : Entity((entt::entity)pixelData, m_ActiveScene.get());
}
m_Framebuffer->Unbind();
}
void EditorLayer::OnImGuiRender()
{
QAQ_PROFILE_FUNCTION();
// Note: Switch this to true to enable dockspace
static bool dockspaceOpen = true;
static bool opt_fullscreen_persistant = true;
bool opt_fullscreen = opt_fullscreen_persistant;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
// We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
// because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)
{
ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
// When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
// Important: note that we proceed even if Begin() returns false (aka window is collapsed).
// This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
// all active windows docked into it will lose their parent and become undocked.
// We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
// any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &dockspaceOpen, window_flags);
ImGui::PopStyleVar();
if (opt_fullscreen)
ImGui::PopStyleVar(2);
// DockSpace
ImGuiIO &io = ImGui::GetIO();
ImGuiStyle &style = ImGui::GetStyle();
float minWinSizeX = style.WindowMinSize.x;
style.WindowMinSize.x = 370.0f;
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
style.WindowMinSize.x = minWinSizeX;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
// Disabling fullscreen would allow the window to be moved to the front of other windows,
// which we can't undo at the moment without finer window depth/z control.
//ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant);1
if (ImGui::MenuItem("New", "Ctrl+N"))
NewScene();
if (ImGui::MenuItem("Open...", "Ctrl+O"))
OpenScene();
if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S"))
SaveSceneAs();
if (ImGui::MenuItem("Exit"))
Application::Get().Close();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
m_SceneHierarchyPanel.OnImGuiRender();
ImGui::Begin("Stats");
std::string name = "None";
if (m_HoveredEntity)
name = m_HoveredEntity.GetComponent<TagComponent>().Tag;
ImGui::Text("Hovered Entity: %s", name.c_str());
auto stats = Renderer2D::GetStats();
ImGui::Text("Renderer2D Stats:");
ImGui::Text("Draw Calls: %d", stats.DrawCalls);
ImGui::Text("Quads: %d", stats.QuadCount);
ImGui::Text("Vertices: %d", stats.GetTotalVertexCount());
ImGui::Text("Indices: %d", stats.GetTotalIndexCount());
ImGui::End();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{0, 0});
ImGui::Begin("Viewport");
auto viewportMinRegion = ImGui::GetWindowContentRegionMin();
auto viewportMaxRegion = ImGui::GetWindowContentRegionMax();
auto viewportOffset = ImGui::GetWindowPos();
m_ViewportBounds[0] = {viewportMinRegion.x + viewportOffset.x, viewportMinRegion.y + viewportOffset.y};
m_ViewportBounds[1] = {viewportMaxRegion.x + viewportOffset.x, viewportMaxRegion.y + viewportOffset.y};
m_ViewportFocused = ImGui::IsWindowFocused();
m_ViewportHovered = ImGui::IsWindowHovered();
Application::Get().GetImGuiLayer()->BlockEvents(!m_ViewportFocused && !m_ViewportHovered);
ImVec2 viewportPanelSize = ImGui::GetContentRegionAvail();
m_ViewportSize = {viewportPanelSize.x, viewportPanelSize.y};
uint64_t textureID = m_Framebuffer->GetColorAttachmentRendererID();
ImGui::Image(reinterpret_cast<void *>(textureID), ImVec2{m_ViewportSize.x, m_ViewportSize.y}, ImVec2{0, 1}, ImVec2{1, 0});
// Gizmos
Entity selectedEntity = m_SceneHierarchyPanel.GetSelectedEntity();
if (selectedEntity && m_GizmoType != -1)
{
ImGuizmo::SetOrthographic(false);
ImGuizmo::SetDrawlist();
ImGuizmo::SetRect(m_ViewportBounds[0].x, m_ViewportBounds[0].y, m_ViewportBounds[1].x - m_ViewportBounds[0].x, m_ViewportBounds[1].y - m_ViewportBounds[0].y);
// Camera
// Runtime camera from entity
// auto cameraEntity = m_ActiveScene->GetPrimaryCameraEntity();
// const auto& camera = cameraEntity.GetComponent<CameraComponent>().Camera;
// const glm::mat4& cameraProjection = camera.GetProjection();
// glm::mat4 cameraView = glm::inverse(cameraEntity.GetComponent<TransformComponent>().GetTransform());
// Editor camera
const glm::mat4 &cameraProjection = m_EditorCamera.GetProjection();
glm::mat4 cameraView = m_EditorCamera.GetViewMatrix();
// Entity transform
auto &tc = selectedEntity.GetComponent<TransformComponent>();
glm::mat4 transform = tc.GetTransform();
// Snapping
bool snap = Input::IsKeyPressed(Key::LeftControl);
float snapValue = 0.5f; // Snap to 0.5m for translation/scale
// Snap to 45 degrees for rotation
if (m_GizmoType == ImGuizmo::OPERATION::ROTATE)
snapValue = 45.0f;
float snapValues[3] = {snapValue, snapValue, snapValue};
ImGuizmo::Manipulate(glm::value_ptr(cameraView), glm::value_ptr(cameraProjection),
(ImGuizmo::OPERATION)m_GizmoType, ImGuizmo::LOCAL, glm::value_ptr(transform),
nullptr, snap ? snapValues : nullptr);
if (ImGuizmo::IsUsing())
{
glm::vec3 translation, rotation, scale;
Math::DecomposeTransform(transform, translation, rotation, scale);
glm::vec3 deltaRotation = rotation - tc.Rotation;
tc.Translation = translation;
tc.Rotation += deltaRotation;
tc.Scale = scale;
}
}
ImGui::End();
ImGui::PopStyleVar();
ImGui::End();
}
void EditorLayer::OnEvent(Event &e)
{
m_CameraController.OnEvent(e);
m_EditorCamera.OnEvent(e);
EventDispatcher dispatcher(e);
dispatcher.Dispatch<KeyPressedEvent>(QAQ_BIND_EVENT_FN(EditorLayer::OnKeyPressed));
dispatcher.Dispatch<MouseButtonPressedEvent>(QAQ_BIND_EVENT_FN(EditorLayer::OnMouseButtonPressed));
}
bool EditorLayer::OnKeyPressed(KeyPressedEvent &e)
{
// Shortcuts
if (e.GetRepeatCount() > 0)
return false;
bool control = Input::IsKeyPressed(Key::LeftControl) || Input::IsKeyPressed(Key::RightControl);
bool shift = Input::IsKeyPressed(Key::LeftShift) || Input::IsKeyPressed(Key::RightShift);
switch (e.GetKeyCode())
{
case Key::N:
{
if (control)
NewScene();
break;
}
case Key::O:
{
if (control)
OpenScene();
break;
}
case Key::S:
{
if (control && shift)
SaveSceneAs();
break;
}
// Gizmos
case Key::Q:
if (!ImGuizmo::IsUsing())
m_GizmoType = -1;
break;
case Key::W:
if (!ImGuizmo::IsUsing())
m_GizmoType = ImGuizmo::OPERATION::TRANSLATE;
break;
case Key::E:
if (!ImGuizmo::IsUsing())
m_GizmoType = ImGuizmo::OPERATION::ROTATE;
break;
case Key::R:
if (!ImGuizmo::IsUsing())
m_GizmoType = ImGuizmo::OPERATION::SCALE;
break;
}
}
bool EditorLayer::OnMouseButtonPressed(MouseButtonPressedEvent &e)
{
if (e.GetMouseButton() == Mouse::ButtonLeft)
{
if (m_ViewportHovered && !ImGuizmo::IsOver() && !Input::IsKeyPressed(Key::LeftAlt))
m_SceneHierarchyPanel.SetSelectedEntity(m_HoveredEntity);
}
return false;
}
void EditorLayer::NewScene()
{
m_ActiveScene = CreateRef<Scene>();
m_ActiveScene->OnViewportResize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
m_SceneHierarchyPanel.SetContext(m_ActiveScene);
}
void EditorLayer::OpenScene()
{
std::string filepath = FileDialogs::OpenFile("QAQ Scene (*.scene)\0*.scene\0");
if (!filepath.empty())
{
m_ActiveScene = CreateRef<Scene>();
m_ActiveScene->OnViewportResize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
m_SceneHierarchyPanel.SetContext(m_ActiveScene);
SceneSerializer serializer(m_ActiveScene);
serializer.Deserialize(filepath);
}
}
void EditorLayer::SaveSceneAs()
{
std::string filepath = FileDialogs::SaveFile("QAQ Scene (*.scene)\0*.scene\0");
if (!filepath.empty())
{
SceneSerializer serializer(m_ActiveScene);
serializer.Serialize(filepath);
}
}
}
|
/*
QUESTION - given a string of english alphabet lowercase letters, find the number of vowels
example -
string word = "sachinduhan";
print '4'
why? - 'a','i', 'u', 'a';
string word = "nslksssjl";
print '0';
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int ans = 0;
string name = "sachinduhan";
for (int i = 0; i < name.length(); i++)
{
if (name[i] == 'a' || name[i] == 'e' || name[i] == 'i' || name[i] == 'o' || name[i] == 'u')
ans++;
}
cout << ans << endl;
return 0;
}
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// REQUIRES: c++experimental
// UNSUPPORTED: c++98, c++03
// <experimental/memory_resource>
// memory_resource * null_memory_resource()
#include <experimental/memory_resource>
#include <new>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
#include "count_new.hpp"
namespace ex = std::experimental::pmr;
struct assert_on_compare : public ex::memory_resource
{
protected:
virtual void * do_allocate(size_t, size_t)
{ assert(false); }
virtual void do_deallocate(void *, size_t, size_t)
{ assert(false); }
virtual bool do_is_equal(ex::memory_resource const &) const noexcept
{ assert(false); }
};
void test_return()
{
{
static_assert(std::is_same<
decltype(ex::null_memory_resource()), ex::memory_resource*
>::value, "");
}
// Test that the returned value is not null
{
assert(ex::null_memory_resource());
}
// Test the same value is returned by repeated calls.
{
assert(ex::null_memory_resource() == ex::null_memory_resource());
}
}
void test_equality()
{
// Same object
{
ex::memory_resource & r1 = *ex::null_memory_resource();
ex::memory_resource & r2 = *ex::null_memory_resource();
// check both calls returned the same object
assert(&r1 == &r2);
// check for proper equality semantics
assert(r1 == r2);
assert(r2 == r1);
assert(!(r1 != r2));
assert(!(r2 != r1));
// check the is_equal method
assert(r1.is_equal(r2));
assert(r2.is_equal(r1));
}
// Different types
{
ex::memory_resource & r1 = *ex::null_memory_resource();
assert_on_compare c;
ex::memory_resource & r2 = c;
assert(r1 != r2);
assert(!(r1 == r2));
assert(!r1.is_equal(r2));
}
}
void test_allocate()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
DisableAllocationGuard g; // null_memory_resource shouldn't allocate.
try {
ex::null_memory_resource()->allocate(1);
assert(false);
} catch (std::bad_alloc const &) {
// do nothing
} catch (...) {
assert(false);
}
#endif
}
void test_deallocate()
{
globalMemCounter.reset();
int x = 42;
ex::null_memory_resource()->deallocate(nullptr, 0);
ex::null_memory_resource()->deallocate(&x, 0);
assert(globalMemCounter.checkDeleteCalledEq(0));
assert(globalMemCounter.checkDeleteArrayCalledEq(0));
}
int main(int, char**)
{
test_return();
test_equality();
test_allocate();
test_deallocate();
return 0;
}
|
#include "test/integration/filters/tee_filter.h"
#include "envoy/registry/registry.h"
#include "source/common/common/logger.h"
#include "source/common/http/header_map_impl.h"
namespace Envoy {
// A test filter that essentially tees the data flow through it.
class StreamTeeFilter : public Http::PassThroughFilter, public StreamTee {
public:
// Http::PassThroughFilter
Http::FilterDataStatus decodeData(Buffer::Instance& buffer, bool end_stream) override {
ENVOY_LOG_MISC(trace, "StreamTee decodeData {}", buffer.length());
absl::MutexLock l{&mutex_};
request_body_.add(buffer);
decode_end_stream_ = end_stream;
if (on_decode_data_) {
return on_decode_data_(*this, decoder_callbacks_);
}
return Http::FilterDataStatus::Continue;
}
Http::FilterTrailersStatus decodeTrailers(Http::RequestTrailerMap& request_trailers) override {
absl::MutexLock l{&mutex_};
request_trailers_ = Http::createHeaderMap<Http::RequestTrailerMapImpl>(request_trailers);
decode_end_stream_ = true;
return Http::FilterTrailersStatus::Continue;
}
Http::FilterDataStatus encodeData(Buffer::Instance& buffer, bool end_stream) override {
ENVOY_LOG_MISC(trace, "StreamTee encodeData {}", buffer.length());
absl::MutexLock l{&mutex_};
response_body_.add(buffer);
encode_end_stream_ = end_stream;
if (on_encode_data_) {
return on_encode_data_(*this, encoder_callbacks_);
}
return Http::FilterDataStatus::Continue;
}
Http::FilterTrailersStatus encodeTrailers(Http::ResponseTrailerMap& response_trailers) override {
absl::MutexLock l{&mutex_};
response_trailers_ = Http::createHeaderMap<Http::ResponseTrailerMapImpl>(response_trailers);
encode_end_stream_ = true;
return Http::FilterTrailersStatus::Continue;
}
};
Http::FilterFactoryCb StreamTeeFilterConfig::createFilter(const std::string&,
Server::Configuration::FactoryContext&) {
return [this](Http::FilterChainFactoryCallbacks& callbacks) -> void {
auto filter = std::make_shared<StreamTeeFilter>();
// TODO(kbaichoo): support multiple connections.
uint32_t next_stream_id = consumeNextClientStreamId();
ASSERT(!stream_id_to_stream_tee_.contains(next_stream_id), "Client Stream ID already exists.");
stream_id_to_stream_tee_.insert({next_stream_id, filter});
callbacks.addStreamFilter(std::move(filter));
};
}
bool StreamTeeFilterConfig::inspectStreamTee(uint32_t stream_id,
std::function<void(const StreamTee&)> inspector) {
if (!stream_id_to_stream_tee_.contains(stream_id)) {
ENVOY_LOG_MISC(warn, "No stream with the given ID.");
return false;
}
const StreamTeeSharedPtr& stream_tee = stream_id_to_stream_tee_.find(stream_id)->second;
inspector(*stream_tee);
return true;
}
bool StreamTeeFilterConfig::setEncodeDataCallback(
uint32_t stream_id,
std::function<Http::FilterDataStatus(StreamTee&,
Http::StreamEncoderFilterCallbacks* encoder_cbs)>
cb) {
if (!stream_id_to_stream_tee_.contains(stream_id)) {
ENVOY_LOG_MISC(warn, "No stream with the given ID.");
return false;
}
StreamTeeSharedPtr& stream_tee = stream_id_to_stream_tee_.find(stream_id)->second;
absl::MutexLock l{&stream_tee->mutex_};
stream_tee->on_encode_data_ = cb;
return true;
}
bool StreamTeeFilterConfig::setDecodeDataCallback(
uint32_t stream_id,
std::function<Http::FilterDataStatus(StreamTee&,
Http::StreamDecoderFilterCallbacks* decoder_cbs)>
cb) {
if (!stream_id_to_stream_tee_.contains(stream_id)) {
ENVOY_LOG_MISC(warn, "No stream with the given ID.");
return false;
}
StreamTeeSharedPtr& stream_tee = stream_id_to_stream_tee_.find(stream_id)->second;
absl::MutexLock l{&stream_tee->mutex_};
stream_tee->on_decode_data_ = cb;
return true;
}
} // namespace Envoy
|
// -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#include "fern/language/interpreter/dataset_source.h"
#include "fern/language/operation/core/attribute_argument.h"
#include "fern/language/io/drivers.h"
namespace fern {
namespace language {
DatasetSource::DatasetSource(
DataName const& data_name)
: _data_name(data_name),
_dataset(open_dataset(_data_name.database_pathname().generic_string(),
OpenMode::READ)),
_expression_type(_dataset->expression_type(_data_name.data_pathname()))
{
}
ExpressionType const& DatasetSource::expression_type() const
{
return _expression_type;
}
std::shared_ptr<Argument> DatasetSource::read() const
{
#ifndef NDEBUG
set_data_has_been_read();
#endif
return std::shared_ptr<Argument>(std::make_shared<AttributeArgument>(
_dataset->read_attribute(_data_name.data_pathname())));
}
} // namespace language
} // namespace fern
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Sylko Olzscher
*
*/
#ifndef CYNG_TRAITS_TAG_HPP
#define CYNG_TRAITS_TAG_HPP
#include <cyng/intrinsics.h>
#include <cstddef>
#include <tuple>
#include <functional>
#include <cyng/intrinsics/traits.hpp>
namespace cyng
{
namespace traits
{
/**
* Declare a tag list for all supported types.
* Note that void is not a valid tuple element.
*
* Consider using Boost.Multiprecision
*/
using tag_t = std::tuple<
null,
bool,
char,
float,
double,
long double,
const char*,
std::uint8_t,
std::uint16_t,
std::uint32_t,
std::uint64_t,
std::int8_t,
std::int16_t,
std::int32_t,
std::int64_t,
std::string,
std::chrono::system_clock::time_point,
std::chrono::nanoseconds,
std::chrono::microseconds,
std::chrono::milliseconds,
std::chrono::seconds,
std::chrono::minutes,
std::chrono::hours,
chrono::dbl_time_point,
version,
revision,
code,
label,
logging::severity,
buffer_t,
mac48,
mac64,
color_8,
color_16,
crypto::digest_md5,
crypto::digest_sha1,
crypto::digest_sha256,
crypto::digest_sha512,
object, // embedded object - don't do this
tuple_t,
vector_t,
set_t,
attr_map_t, // std::map<std::size_t, object>;
attr_t, // std::pair<std::size_t, object>;
param_map_t, // std::map<std::string, object>;
param_t, // std::pair<std::string, object>;
lockable,
boost::system::error_code,
boost::uuids::uuid,
boost::filesystem::path,
boost::asio::ip::tcp::endpoint,
boost::asio::ip::udp::endpoint,
boost::asio::ip::icmp::endpoint,
boost::asio::ip::address,
#if defined(CYNG_ODBC_INSTALLED)
SQL_TIMESTAMP_STRUCT,
#else
dummy_SQL_TIMESTAMP_STRUCT,
#endif
eod
>;
/**
* Test if type is element of a tuple
*
* Example:
* @code
* using T = std::tuple<int, double, char>;
* std::cout << std::boolalpha;
* std::cout << tuple_contains_type<int, T>::value << std::endl;
* @endcode
*/
template <typename T, typename Tuple>
struct has_type;
template <typename T>
struct has_type<T, std::tuple<>>
: std::false_type
{};
template <typename T, typename U, typename... Ts>
struct has_type<T, std::tuple<U, Ts...>>
: has_type<T, std::tuple<Ts...>>
{};
template <typename T, typename... Ts>
struct has_type<T, std::tuple<T, Ts...>>
: std::true_type
{};
/**
* Calculate the index of a specified type in the tag tuple:
*
* Example:
* @code
* typedef std::tuple<int, char*, int, long> foo_t;
* std::cout << "index<int, foo_t> = " << index<int, foo_t>::value << std::endl;
* @endcode
*/
template <class T, class Tuple>
struct index;
template <class T, class... Types>
struct index<T, std::tuple<T, Types...>>
{
static constexpr std::size_t value = 0;
};
template <class T, class U, class... Types>
struct index<T, std::tuple<U, Types...>>
{
static constexpr std::size_t value = 1 + index<T, std::tuple<Types...>>::value;
};
} // traits
/**
* @return true if data type T is in the type list tag_t, i.e. it is a built-in type
*/
template <typename T>
constexpr bool built_in_type()
{
return traits::has_type<T, traits::tag_t>::value;
}
/**
* @return true if tag is in the range of the built-in types
*/
inline bool built_in_tag(std::size_t tag)
{
return tag < std::tuple_size<traits::tag_t>::value;
}
/**
* @return the index of the specified type in the tag tuple
*/
template <typename T>
constexpr typename std::enable_if<traits::has_type<T, traits::tag_t>::value, std::size_t>::type
type_tag_traits()
{
// using R = typename std::conditional<built_in_type<T>()
// , std::integral_constant<std::size_t, traits::index<T, traits::tag_t>::value>
// , std::integral_constant<std::size_t, std::tuple_size<traits::tag_t>::value>
// >::type;
// return R::value;
return traits::index<T, traits::tag_t>::value;
}
template <typename T>
constexpr typename std::enable_if<!traits::has_type<T, traits::tag_t>::value, std::size_t>::type
type_tag_traits()
{
//
// one element after the last entry
//
// return std::tuple_size<traits::tag_t>::value + 1;
//
// specialize type_tag<> for your custom data types
//
return cyng::traits::type_tag<T>::tag::value;
}
enum /*class*/ type_code : std::size_t
{
TC_NULL = type_tag_traits<null>(),
TC_BOOL = type_tag_traits<bool>(),
TC_CHAR = type_tag_traits<char>(),
TC_FLOAT = type_tag_traits<float>(),
TC_DOUBLE = type_tag_traits<double>(),
TC_FLOAT80 = type_tag_traits<long double>(), // different sizes on different compilers
// const char*,
TC_UINT8 = type_tag_traits<std::uint8_t>(),
TC_UINT16 = type_tag_traits<std::uint16_t>(),
TC_UINT32 = type_tag_traits<std::uint32_t>(),
TC_UINT64 = type_tag_traits<std::uint64_t>(),
TC_INT8 = type_tag_traits<std::int8_t>(),
TC_INT16 = type_tag_traits<std::int16_t>(),
TC_INT32 = type_tag_traits<std::int32_t>(),
TC_INT64 = type_tag_traits<std::int64_t>(),
TC_STRING = type_tag_traits<std::string>(),
TC_TIME_POINT = type_tag_traits<std::chrono::system_clock::time_point>(),
TC_NANO_SECOND = type_tag_traits<std::chrono::nanoseconds>(),
TC_MICRO_SECOND = type_tag_traits<std::chrono::microseconds>(),
TC_MILLI_SECOND = type_tag_traits<std::chrono::milliseconds>(),
TC_SECOND = type_tag_traits<std::chrono::seconds>(),
TC_MINUTE = type_tag_traits<std::chrono::minutes>(),
TC_HOUR = type_tag_traits<std::chrono::hours>(),
TC_DBL_TP = type_tag_traits<chrono::dbl_time_point>(),
TC_VERSION = type_tag_traits<version>(),
TC_REVISION = type_tag_traits<revision>(),
TC_CODE = type_tag_traits<code>(),
TC_LABEL = type_tag_traits<label>(),
TC_SEVERITY = type_tag_traits<logging::severity>(),
TC_BUFFER = type_tag_traits<buffer_t>(),
TC_MAC48 = type_tag_traits<mac48>(),
TC_MAC64 = type_tag_traits<mac64>(),
TC_COLOR_8 = type_tag_traits<color_8>(),
TC_COLOR_16 = type_tag_traits<color_16>(),
TC_DIGEST_MD5 = type_tag_traits<crypto::digest_md5>(),
TC_DIGEST_SHA1 = type_tag_traits<crypto::digest_sha1>(),
TC_DIGEST_SHA256 = type_tag_traits<crypto::digest_sha256>(),
TC_DIGEST_SHA512 = type_tag_traits<crypto::digest_sha512>(),
TC_OBJECT = type_tag_traits<object>(),
TC_TUPLE = type_tag_traits<tuple_t>(),
TC_VECTOR = type_tag_traits<vector_t>(),
TC_SET = type_tag_traits<set_t>(),
TC_ATTR_MAP = type_tag_traits<attr_map_t>(), // std::map<std::size_t, object>;
TC_ATTR = type_tag_traits<attr_t>(), // std::pair<std::size_t, object>;
TC_PARAM_MAP = type_tag_traits<param_map_t>(), // std::map<std::string, object>;
TC_PARAM = type_tag_traits<param_t>(), // std::pair<std::string, object>;
TC_EC = type_tag_traits<boost::system::error_code>(),
TC_UUID = type_tag_traits<boost::uuids::uuid>(),
TC_FS_PATH = type_tag_traits<boost::filesystem::path>(),
TC_IP_TCP_ENDPOINT = type_tag_traits<boost::asio::ip::tcp::endpoint>(),
TC_IP_UDP_ENDPOINT = type_tag_traits<boost::asio::ip::udp::endpoint>(),
TC_IP_ICMP_ENDPOINT = type_tag_traits<boost::asio::ip::icmp::endpoint>(),
TC_IP_ADDRESS = type_tag_traits<boost::asio::ip::address>(),
#if defined(CYNG_ODBC_INSTALLED)
TC_SQL_TIMESTAMP = type_tag_traits<SQL_TIMESTAMP_STRUCT>(),
#else
TC_SQL_TIMESTAMP = type_tag_traits<dummy_SQL_TIMESTAMP_STRUCT>(),
#endif
TC_EOD = type_tag_traits<eod>()
};
namespace traits
{
/**
* Calculate the data type from it's type code.
* Overwrite this template for custom types.
*/
template < std::size_t N >
struct reverse_type
{
using type = typename std::tuple_element<N, traits::tag_t>::type;
};
}
}
#endif // CYNG_TRAITS_TAG_HPP
|
//
// Construct the Mu2e G4 world and serve information about that world.
//
// Original author Rob Kutschke
//
// Heirarchy is:
// 0 World (air)
// 1 Earthen Overburden
// 2 Concrete walls of the hall
// 3 Air inside the hall
// 4 Effective volume representing the DS coils+cryostats.
// 4 DS Vaccum
//
// 4 Effective volume representing the PS coils+cryostats.
// 4 PS Vacuum
//
// The Earth overburden is modeled in two parts: a box that extends
// to the surface of the earth plus a cap above grade. The cap is shaped
// as a G4Paraboloid.
//
// C++ includes
#include <iostream>
#include <string>
#include <vector>
// Framework includes
#include "messagefacility/MessageLogger/MessageLogger.h"
#include "cetlib_except/exception.h"
#include "art/Framework/Services/Registry/ServiceDefinitionMacros.h"
// Mu2e includes
#include "Offline/ConfigTools/inc/checkForStale.hh"
#include "Offline/Mu2eG4Helper/inc/Mu2eG4Helper.hh"
#include "Offline/Mu2eG4/inc/SensitiveDetectorName.hh"
#include "Offline/Mu2eG4/inc/Mu2eWorld.hh"
#include "Offline/Mu2eG4/inc/constructWorldVolume.hh"
#include "Offline/Mu2eG4/inc/constructHall.hh"
#include "Offline/Mu2eG4/inc/constructProtonBeamDump.hh"
#include "Offline/Mu2eG4/inc/constructProtonAbsorber.hh"
#include "Offline/Mu2eG4/inc/constructCRV.hh"
#include "Offline/Mu2eG4/inc/constructExternalShielding.hh"
#include "Offline/Mu2eG4/inc/constructSaddles.hh"
#include "Offline/Mu2eG4/inc/constructServicesGeom.hh"
#include "Offline/Mu2eG4/inc/constructTSdA.hh"
#include "Offline/Mu2eG4/inc/constructMBS.hh"
#include "Offline/Mu2eG4/inc/constructVirtualDetectors.hh"
#include "Offline/Mu2eG4/inc/constructVirtualDetectorSDs.hh"
#include "Offline/Mu2eG4/inc/constructVisualizationRegions.hh"
#include "Offline/Mu2eG4/inc/constructDS.hh"
#include "Offline/Mu2eG4/inc/constructMSTM.hh"
#include "Offline/Mu2eG4/inc/constructSTM.hh"
#include "Offline/Mu2eG4/inc/constructTS.hh"
#include "Offline/Mu2eG4/inc/constructPS.hh"
#include "Offline/Mu2eG4/inc/constructPSEnclosure.hh"
#include "Offline/Mu2eG4/inc/MaterialFinder.hh"
#include "Offline/Mu2eG4/inc/CaloCrystalSD.hh"
#include "Offline/Mu2eG4/inc/CaloReadoutSD.hh"
#include "Offline/Mu2eG4/inc/CaloReadoutCardSD.hh"
#include "Offline/Mu2eG4/inc/CaloCrateSD.hh"
#include "Offline/Mu2eG4/inc/ExtMonFNALPixelSD.hh"
#include "Offline/Mu2eG4/inc/TrackerWireSD.hh"
#include "Offline/Mu2eG4/inc/Mu2eG4SensitiveDetector.hh"
#include "Offline/Mu2eG4/inc/CRVSD.hh"
#include "Offline/Mu2eG4/inc/StrawSD.hh"
#include "Offline/Mu2eG4/inc/TrackerPlaneSupportSD.hh"
#include "Offline/Mu2eG4/inc/findMaterialOrThrow.hh"
#include "Offline/Mu2eG4/inc/nestTubs.hh"
#include "Offline/Mu2eG4/inc/nestTorus.hh"
#include "Offline/Mu2eG4/inc/nestBox.hh"
#include "Offline/Mu2eG4/inc/nestCons.hh"
#include "Offline/Mu2eG4/inc/finishNesting.hh"
#include "Offline/GeometryService/inc/GeometryService.hh"
#include "Offline/GeometryService/inc/GeomHandle.hh"
#include "Offline/GeometryService/inc/WorldG4.hh"
#include "Offline/GeometryService/inc/DetectorSystem.hh"
#include "Offline/BFieldGeom/inc/BFieldManager.hh"
#include "Offline/CalorimeterGeom/inc/Calorimeter.hh"
#include "Offline/CalorimeterGeom/inc/DiskCalorimeter.hh"
#include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh"
#include "Offline/StoppingTargetGeom/inc/StoppingTarget.hh"
#include "Offline/BeamlineGeom/inc/Beamline.hh"
#include "Offline/BeamlineGeom/inc/TransportSolenoid.hh"
#include "Offline/GeometryService/inc/VirtualDetector.hh"
#include "Offline/Mu2eG4/inc/constructTracker.hh"
#include "Offline/Mu2eG4/inc/constructStoppingTarget.hh"
#include "Offline/Mu2eG4/inc/constructDummyStoppingTarget.hh"
#include "Offline/Mu2eG4/inc/constructDiskCalorimeter.hh"
#include "Offline/Mu2eG4/inc/SensitiveDetectorHelper.hh"
#include "Offline/TrackerGeom/inc/Tracker.hh"
#include "Offline/ExtinctionMonitorFNAL/Geometry/inc/ExtMonFNAL.hh"
#include "Offline/Mu2eG4/inc/constructPTM.hh"
// G4 includes
#include "Geant4/G4Threading.hh"
#include "Geant4/G4SDManager.hh"
#include "Geant4/G4GeometryManager.hh"
#include "Geant4/G4PhysicalVolumeStore.hh"
#include "Geant4/G4LogicalVolumeStore.hh"
#include "Geant4/G4Material.hh"
#include "Geant4/G4Box.hh"
#include "Geant4/G4Paraboloid.hh"
#include "Geant4/G4Colour.hh"
#include "Geant4/G4Tubs.hh"
#include "Geant4/G4IntersectionSolid.hh"
#include "Geant4/G4SubtractionSolid.hh"
#include "Geant4/G4LogicalVolume.hh"
#include "Geant4/G4TwoVector.hh"
#include "Geant4/G4ThreeVector.hh"
#include "Geant4/globals.hh"
#include "Geant4/G4UniformMagField.hh"
#include "Geant4/G4FieldManager.hh"
#include "Geant4/G4Mag_UsualEqRhs.hh"
#include "Geant4/G4Mag_SpinEqRhs.hh"
#include "Geant4/G4ExactHelixStepper.hh"
#include "Geant4/G4ChordFinder.hh"
#include "Geant4/G4TransportationManager.hh"
#include "Geant4/G4PropagatorInField.hh"
#include "Geant4/G4MagIntegratorDriver.hh"
#include "Geant4/G4UserLimits.hh"
#include "Geant4/G4ClassicalRK4.hh"
#include "Geant4/G4ImplicitEuler.hh"
#include "Geant4/G4ExplicitEuler.hh"
#include "Geant4/G4SimpleRunge.hh"
#include "Geant4/G4SimpleHeum.hh"
#include "Geant4/G4HelixImplicitEuler.hh"
#include "Geant4/G4HelixSimpleRunge.hh"
#if G4VERSION>4103
#include "Geant4/G4DormandPrince745.hh"
#include "Geant4/G4BogackiShampine23.hh"
#endif
#include "Geant4/G4GDMLParser.hh"
#include "Geant4/G4ProductionCuts.hh"
#include "Geant4/G4Region.hh"
#include "Offline/Mu2eG4/inc/Mu2eG4GlobalMagneticField.hh"
#include "boost/regex.hpp"
using namespace std;
namespace mu2e {
Mu2eWorld::Mu2eWorld(const Mu2eG4Config::Top& conf,
SensitiveDetectorHelper *sdHelper/*no ownership passing*/)
: Mu2eUniverse(conf.debug())
, sdHelper_(sdHelper)
, conf_(conf)
, activeWr_Wl_SD_(true)
, writeGDML_(conf.debug().writeGDML())
, gdmlFileName_(conf.debug().GDMLFileName())
, g4stepperName_(conf.physics().stepper())
, g4epsilonMin_(conf.physics().epsilonMin())
, g4epsilonMax_(conf.physics().epsilonMax())
, g4DeltaOneStep_(conf.physics().deltaOneStep()*CLHEP::mm)
, g4DeltaIntersection_(conf.physics().deltaIntersection()*CLHEP::mm)
, g4DeltaChord_(conf.physics().deltaChord()*CLHEP::mm)
, g4StepMinimum_(conf.physics().stepMinimum()*CLHEP::mm)
, g4MaxIntSteps_(conf.physics().maxIntSteps())
, bfieldMaxStep_(conf.physics().bfieldMaxStep()*CLHEP::mm)
, strawGasMaxStep_(conf.physics().strawGasMaxStep()*CLHEP::mm)
, limitStepInAllVolumes_(conf.physics().limitStepInAllVolumes())
, useEmOption4InTracker_(conf.physics().useEmOption4InTracker())
{}
// This is the callback called by G4 via G4VPhysicalVolume* WorldMaker::Construct()
G4VPhysicalVolume * Mu2eWorld::construct(){
// Construct all of the Mu2e world, hall, detectors, beamline ...
return constructWorld();
}
// This is the callback called by G4 via void WorldMaker::ConstructSDandField()
void Mu2eWorld::constructSDandField(){
sdHelper_->instantiateLVSDs(_config);
instantiateSensitiveDetectors();
constructBFieldAndManagers();
}
// Construct all of the Mu2e world, hall, detectors, beamline ...
G4VPhysicalVolume * Mu2eWorld::constructWorld(){
// If you play with the order of these calls, you may break things.
GeomHandle<WorldG4> worldGeom;
G4ThreeVector tmpTrackercenter = GeomHandle<DetectorSystem>()->getOrigin();
if (activeWr_Wl_SD_) {
TrackerWireSD::setMu2eDetCenterInWorld( tmpTrackercenter );
}
VolumeInfo worldVInfo = constructWorldVolume(_config);
if ( _verbosityLevel > 0) {
G4cout << __func__ << " worldVInfo.centerInParent : " << worldVInfo.centerInParent << G4endl;
G4cout << __func__ << " worldVInfo.centerInWorld : " << worldVInfo.centerInWorld << G4endl;
}
VolumeInfo hallInfo = constructHall(worldVInfo, _config);
if ( _verbosityLevel > 0) {
G4cout << __func__ << " hallInfo.centerInParent : " << hallInfo.centerInParent << G4endl;
G4cout << __func__ << " hallInfo.centerInWorld : " << hallInfo.centerInWorld << G4endl;
G4cout << __func__ << " hallInfo.centerInMu2e() : " << hallInfo.centerInMu2e() << G4endl;
}
constructProtonBeamDump(hallInfo, _config);
constructDS(hallInfo, _config);
//Here's a test case for a another way of making SDs active.
//Instead of being a void function, it returns a G4LogicalVolume*,
//which I made a member function of this class. Then, I access this member function
//in constructSDandField() call to instantiateSensitiveDetectors in order to set the SensitiveDetectors
psVacuumLogical_ = constructPS(hallInfo, _config);
constructPSEnclosure(hallInfo, _config);
constructTS(hallInfo, _config);
VolumeInfo trackerInfo = constructTracker();
VolumeInfo targetInfo = constructTarget();
constructProtonAbsorber(_config);
VolumeInfo calorimeterInfo = constructCal();
// This is just placeholder for now - and might be misnamed.
constructMagnetYoke();
if ( _config.getBool("hasExternalShielding",false) ) {
constructExternalShielding(hallInfo, _config);
}
// This is for saddles holding up cryostats
constructSaddles(hallInfo, _config);
// This is for pipes, cable runs, Electronics racks, etc.
constructServicesGeom(hallInfo, _config);
if ( _config.getBool("hasTSdA",false) ) {
constructTSdA(_config);
}
if ( _config.getBool("hasMBS",false) ) {
constructMBS(_config);
}
if ( _config.getBool("mstm.build", false) ) {
constructMSTM(hallInfo, _config);
}
if ( _config.getBool("hasSTM",false) ) {
constructSTM(_config);
}
if (_config.getBool("hasPTM",false) ){
constructPTM(hallInfo, _config);
}
// _geom is member data of Mu2eG4Universe, from which this inherits
// it is a ref to a const GeometryService object
if ( const_cast<GeometryService&>(_geom).hasElement<CosmicRayShield>() ) {
GeomHandle<CosmicRayShield> CosmicRayShieldGeomHandle;
constructCRV(hallInfo,_config);
}
constructVirtualDetectors(_config); // beware of the placement order of this function
constructVisualizationRegions(worldVInfo, _config);
if ( _verbosityLevel > 0) {
mf::LogInfo log("GEOM");
log << "Mu2e Origin: " << worldGeom->mu2eOriginInWorld() << "\n";
}
// creating regions to be able to asign special cut and EM options
fhicl::ParameterSet minRangeRegionCutsPSet;
if (conf_.physics().minRangeRegionCuts.get_if_present(minRangeRegionCutsPSet)) {
const std::vector<std::string> regionNames{minRangeRegionCutsPSet.get_names()};
for(const auto& regionName : regionNames) {
G4Region* region = new G4Region(regionName); // G4RegionStore takes ownership
VolumeInfo const & volInfo = _helper->locateVolInfo(regionName);
volInfo.logical->SetRegion(region);
region->AddRootLogicalVolume(volInfo.logical);
G4ProductionCuts* regionProductionCuts = new G4ProductionCuts();
G4double productionCut = minRangeRegionCutsPSet.get<double>(regionName);
regionProductionCuts->SetProductionCut(productionCut);
// the above sets the same cut for gamma, e- and e+, proton/ions
G4double protonProductionCut = conf_.physics().protonProductionCut();
regionProductionCuts->SetProductionCut(protonProductionCut,"proton");
region->SetProductionCuts(regionProductionCuts);
if ( _verbosityLevel > 0 ) {
G4cout << __func__ << " Setting gamma, e- and e+ production cut for "
<< regionName << " to " << productionCut << " mm and for proton to "
<< protonProductionCut << " mm" << G4endl;
G4cout << __func__ << " Resulting cuts for gamma, e-, e+, proton: ";
for (auto const& rcut : regionProductionCuts->GetProductionCuts() ) {
G4cout << " " << rcut;
}
G4cout << G4endl;
}
}
}
// special case for the tracker when we need a region to set a
// different EM option even when no production cuts are set explicitly
if ( useEmOption4InTracker_
//&& !pset_.has_key("physics.minRangeRegionCuts.TrackerMother")) {
&& !minRangeRegionCutsPSet.has_key("TrackerMother")) {
G4Region* region = new G4Region("TrackerMother");
trackerInfo.logical->SetRegion(region);
region->AddRootLogicalVolume(trackerInfo.logical);
}
constructStepLimiters();
// Write out mu2e geometry into a gdml file.
if (writeGDML_) {
G4GDMLParser parser;
parser.Write(gdmlFileName_, worldVInfo.logical);
}
return worldVInfo.physical;
}//Mu2eWorld::constructWorld()
// Choose the selected tracker and build it.
VolumeInfo Mu2eWorld::constructTracker(){
// The tracker is built inside this volume.
std::string theDS3("DS3Vacuum");
if ( _config.getBool("inGaragePosition",false) ) theDS3 = "garageFakeDS3Vacuum";
VolumeInfo const & detSolDownstreamVacInfo = _helper->locateVolInfo(theDS3);
// Construct one of the trackers.
VolumeInfo trackerInfo;
if ( _config.getBool("hasTracker",false) ) {
if ( _config.getInt("TrackerVersion",3) != 5 ){
throw cet::exception("GEOM")
<< "Current code only supports TrackerVersion = 5\n"
<< "Requested version: "
<< _config.getInt("TrackerVersion",3);
}
trackerInfo = constructTrackerv5( detSolDownstreamVacInfo, _config);
}
if ( _verbosityLevel > 0) {
G4cout << __func__ << "detSolDownstreamVacInfo.centerInMu2e().x() =" << detSolDownstreamVacInfo.centerInMu2e().x() << G4endl;
G4cout << __func__ << "detSolDownstreamVacInfo.centerInMu2e().y() =" << detSolDownstreamVacInfo.centerInMu2e().y() << G4endl;
G4cout << __func__ << "detSolDownstreamVacInfo.centerInMu2e().z() =" << detSolDownstreamVacInfo.centerInMu2e().z() << G4endl;
}
return trackerInfo;
}//Mu2eWorld::constructTracker
// Either build the stopping target or a placeholder.
// This should be call constrcutStoppingTarget but the name is already taken.
VolumeInfo Mu2eWorld::constructTarget(){
// The target is built inside this volume.
std::string theDS3("DS3Vacuum");
std::string theDS2("DS2Vacuum");
if ( _config.getBool("inGaragePosition",false) && _config.getBool("garage.extractOPA_IPA_ST")) {
theDS3 = "garageFakeDS3Vacuum";
theDS2 = "garageFakeDS2Vacuum";
}
VolumeInfo const & detSolUpstreamVacInfo = ( _config.getBool("isDumbbell",false) ) ? _helper->locateVolInfo(theDS3) : _helper->locateVolInfo(theDS2);//DS3Vacuum to move the targets
if ( _verbosityLevel > 0) {
G4cout << __func__ << "detSolUpstreamVacInfo.centerInWorld.z()=" << detSolUpstreamVacInfo.centerInWorld.z() << G4endl;
G4cout << __func__ << "detSolUpstreamVacInfo.centerInMu2e().z() =" << detSolUpstreamVacInfo.centerInMu2e().z() << G4endl;
}
// Buid the stopping target
VolumeInfo targetInfo = ( _config.getBool("hasTarget",false) ) ?
constructStoppingTarget( detSolUpstreamVacInfo,
_config )
:
constructDummyStoppingTarget( detSolUpstreamVacInfo,
_config );
return targetInfo;
} // end Mu2eWorld::constructTarget
// Construct the magnetic field managers and attach them to
// the relevant volumes or to the world
void Mu2eWorld::constructBFieldAndManagers(){
GeomHandle<WorldG4> worldGeom;
// Get some information needed further
VolumeInfo const & ds2VacuumVacInfo = _helper->locateVolInfo("DS2Vacuum");
VolumeInfo const & ds3VacuumVacInfo = _helper->locateVolInfo("DS3Vacuum");
G4LogicalVolume* ds2Vacuum = ds2VacuumVacInfo.logical;
G4LogicalVolume* ds3Vacuum = ds3VacuumVacInfo.logical;
double ds2HL = static_cast<G4Tubs*>(ds2VacuumVacInfo.solid)->GetZHalfLength();
G4ThreeVector ds2Z0 = ds2VacuumVacInfo.centerInWorld;
G4ThreeVector beamZ0( ds2Z0.x(), ds2Z0.y(), ds2Z0.z()+ds2HL );
// Decide on the G4 Stepper
GeomHandle<BFieldConfig> bfConfig;
bool needDSUniform = (bfConfig->dsFieldForm() == BFieldConfig::dsModelSplit || bfConfig->dsFieldForm() == BFieldConfig::dsModelUniform );
bool needDSGradient = false;
// Create field manager for the uniform DS field.
if (needDSUniform) {
_dsUniform = FieldMgr::forUniformField( bfConfig->getDSUniformValue()*CLHEP::tesla, worldGeom->mu2eOriginInWorld() );
// Create field manager for the gradient field in DS3
if(bfConfig->dsFieldForm() == BFieldConfig::dsModelSplit) {
needDSGradient = true;
_dsGradient = FieldMgr::forGradientField( bfConfig->getDSUniformValue().z()*CLHEP::tesla,
bfConfig->getDSGradientValue().z()*CLHEP::tesla/CLHEP::m,
beamZ0 );
}
}
// Create global field managers; don't use FieldMgr here to avoid problem with ownership
G4MagneticField * _field = new Mu2eG4GlobalMagneticField(worldGeom->mu2eOriginInWorld());
G4Mag_EqRhs * _rhs = new G4Mag_UsualEqRhs(_field);
G4MagIntegratorStepper * _stepper;
if ( _g4VerbosityLevel > 0 ) G4cout << __func__ << " Setting up " << g4stepperName_ << " stepper" << G4endl;
if ( g4stepperName_ == "G4ClassicalRK4" ) {
_stepper = new G4ClassicalRK4(_rhs);
} else if ( g4stepperName_ == "G4ClassicalRK4WSpin" ) {
delete _rhs; // FIXME: avoid the delete
_rhs = new G4Mag_SpinEqRhs(_field);
_stepper = new G4ClassicalRK4(_rhs, 12);
if ( _g4VerbosityLevel > 0) {
G4cout << __func__ << " Replaced G4Mag_UsualEqRhs with G4ClassicalRK4WSpin "
<< "and used G4ClassicalRK4 with Spin" << G4endl;
}
#if G4VERSION>4103
} else if ( g4stepperName_ == "G4DormandPrince745WSpin" ) {
delete _rhs; // FIXME: avoid the delete
_rhs = new G4Mag_SpinEqRhs(_field);
_stepper = new G4DormandPrince745(_rhs, 12);
if ( _g4VerbosityLevel > 0) {
G4cout << __func__ << " Replaced G4Mag_UsualEqRhs with G4DormandPrince745WSpin "
<< "and used G4DormandPrince745 with Spin" << G4endl;
}
#endif
} else if ( g4stepperName_ == "G4ImplicitEuler" ) {
_stepper = new G4ImplicitEuler(_rhs);
} else if ( g4stepperName_ == "G4ExplicitEuler" ) {
_stepper = new G4ExplicitEuler(_rhs);
} else if ( g4stepperName_ == "G4SimpleHeum" ) {
_stepper = new G4SimpleHeum(_rhs);
} else if ( g4stepperName_ == "G4HelixImplicitEuler" ) {
_stepper = new G4HelixImplicitEuler(_rhs);
} else if ( g4stepperName_ == "G4HelixSimpleRunge" ) {
_stepper = new G4HelixSimpleRunge(_rhs);
#if G4VERSION>4103
} else if ( g4stepperName_ == "G4DormandPrince745" ) {
_stepper = new G4DormandPrince745(_rhs);
} else if ( g4stepperName_ == "G4BogackiShampine23" ) {
_stepper = new G4BogackiShampine23(_rhs);
#endif
} else if ( g4stepperName_ == "G4SimpleRunge" ) {
_stepper = new G4SimpleRunge(_rhs);
} else {
throw cet::exception("GEOM")
<< "Unrecognized stepper : "
<< g4stepperName_
<< "\n";
}
G4ChordFinder * _chordFinder = new G4ChordFinder(_field,g4StepMinimum_,_stepper);
G4FieldManager * _manager = new G4FieldManager(_field,_chordFinder,true);
// G4TransportationManager takes ownership of _manager
G4TransportationManager* transporationMgr =
G4TransportationManager::GetTransportationManager();
transporationMgr->SetFieldManager(_manager);
// Define uniform field region in the detector solenoid, if neccessary
if (bfConfig->dsFieldForm() == BFieldConfig::dsModelUniform ){
ds2Vacuum->SetFieldManager( _dsUniform->manager(), true);
if ( _verbosityLevel > 0 ) G4cout << __func__ << " Use uniform field in DS2" << G4endl;
}
if (bfConfig->dsFieldForm() == BFieldConfig::dsModelUniform || bfConfig->dsFieldForm() == BFieldConfig::dsModelSplit){
if( needDSGradient ) {
ds3Vacuum->SetFieldManager( _dsGradient->manager(), true);
if ( _verbosityLevel > 0 ) G4cout << __func__ << " Use gradient field in DS3" << G4endl;
} else {
ds3Vacuum->SetFieldManager( _dsUniform->manager(), true);
if ( _verbosityLevel > 0 ) G4cout << __func__ << " Use uniform field in DS3" << G4endl;
}
// if( _config.getBool("hasMBS",false) ) {
// VolumeInfo const & MBSMotherInfo = _helper->locateVolInfo("MBSMother");
// G4LogicalVolume* mbsMother = MBSMotherInfo.logical;
// mbsMother->SetFieldManager(0,true);
// }
}
// Adjust properties of the integrators to control accuracy vs time.
if ( _dsUniform.get() != 0 ){
G4double deltaIntersection = 0.00001*CLHEP::mm;
_dsUniform->manager()->SetDeltaIntersection(deltaIntersection);
}
if ( _dsGradient.get() != 0 ){
G4double deltaIntersection = 0.00001*CLHEP::mm;
_dsGradient->manager()->SetDeltaIntersection(deltaIntersection);
}
_manager->SetMinimumEpsilonStep(g4epsilonMin_);
_manager->SetMaximumEpsilonStep(g4epsilonMax_);
_manager->SetDeltaOneStep(g4DeltaOneStep_);
_manager->SetDeltaIntersection(g4DeltaIntersection_);
_chordFinder->SetDeltaChord(g4DeltaChord_);
G4PropagatorInField* _propInField = transporationMgr->GetPropagatorInField();
_propInField->SetMaxLoopCount(g4MaxIntSteps_);
if ( _g4VerbosityLevel > 0 ) {
G4cout << __func__ << " Stepper precision parameters: " << G4endl;
G4cout << __func__ << " g4epsilonMin " << _manager->GetMinimumEpsilonStep() << G4endl;
G4cout << __func__ << " g4epsilonMax " << _manager->GetMaximumEpsilonStep() << G4endl;
G4cout << __func__ << " g4DeltaOneStep " << _manager->GetDeltaOneStep() << G4endl;
G4cout << __func__ << " g4DeltaIntersection " << _manager->GetDeltaIntersection() << G4endl;
G4cout << __func__ << " g4DeltaChord " << _chordFinder->GetDeltaChord() << G4endl;
G4cout << __func__ << " g4StepMinimum "
// << dynamic_cast<G4MagInt_Driver*>(_chordFinder->GetIntegrationDriver())->GetHmin() << G4endl;
// the above assumes G4ChordFinder is instantiated in the way it is done above with the 3 parameters
// does not work in 10.5+; fixme
<< g4StepMinimum_ << G4endl;
G4cout << __func__ << " g4MaxIntStep " << _propInField->GetMaxLoopCount() << G4endl;
}
} // end Mu2eWorld::constructBFieldAndManagers
// A helper function for Mu2eWorld::constructStepLimiters().
// Find all logical volumes matching a wildcarded name and add steplimiters to them.
void Mu2eWorld::stepLimiterHelper ( std::string const& regexp, G4UserLimits* stepLimit ) {
boost::regex expression(regexp.c_str());
std::vector<mu2e::VolumeInfo const*> vols =
art::ServiceHandle<mu2e::Mu2eG4Helper>()->locateVolInfo(expression);
for ( auto v : vols ){
v->logical->SetUserLimits( stepLimit );
if(_g4VerbosityLevel > 0) {
G4cout << __func__ << " Activated step limit for volume "<<v->logical->GetName() << G4endl;
}
}
}
// helper function
void Mu2eWorld::setStepLimitToAllSuchVolumes(const G4String& vn,
G4UserLimits* const stepLimit,
const G4LogicalVolumeStore* const lvs,
int verbosityLevel) {
int vtbcc = 0;
for ( auto lvi=lvs->begin(); lvi!=lvs->end(); ++lvi) {
if ((*lvi)->GetName() == vn) {
(*lvi)->SetUserLimits( stepLimit );
if(verbosityLevel > 0) {
G4cout << __func__<< " Activated step limit for volume " << vn << G4endl;
}
++vtbcc;
}
}
if (vtbcc>1 && verbosityLevel > -1) {
G4cout << __func__<< " WARNING: found " << vn << " " << vtbcc << " times" << G4endl;
}
}
// Adding a step limiter is a two step process.
// 1) In the physics list constructor add a G4StepLimiter to the list of discrete
// physics processes attached to each particle species of interest.
//
// 2) In this code, create a G4UserLimits object and attach it to the logical
// volumes of interest.
// The net result is specifying a step limiter for pairs of (logical volume, particle species).
//
void Mu2eWorld::constructStepLimiters(){
// G4LogicalVolume* hallAir = _helper->locateVolInfo("HallAir").logical;
G4LogicalVolume* ds1Vacuum = _helper->locateVolInfo("DS1Vacuum").logical;
G4LogicalVolume* ds2Vacuum = _helper->locateVolInfo("DS2Vacuum").logical;
G4LogicalVolume* ds3Vacuum = _helper->locateVolInfo("DS3Vacuum").logical;
G4LogicalVolume* dsCVacuum = _helper->locateVolInfo("DSCryoVacuumRegion").logical;
G4LogicalVolume* tracker = _helper->locateVolInfo("TrackerMother").logical;
G4LogicalVolume* trackerPanel = _helper->locateVolInfo("StrawPanelEnvelope").logical;
G4LogicalVolume* caloMother = _helper->locateVolInfo("CalorimeterMother").logical;
G4LogicalVolume* stoppingTarget = _helper->locateVolInfo("StoppingTargetMother").logical;
G4LogicalVolume* productionTarget = _helper->locateVolInfo("ProductionTargetMother").logical;
vector<G4LogicalVolume*> psVacua;
psVacua.push_back( _helper->locateVolInfo("PSVacuum").logical );
psVacua.push_back( _helper->locateVolInfo("psVacuumVesselVacuum").logical );
vector<G4LogicalVolume*> tsVacua; // could use stepLimiterHelper; see below
tsVacua.push_back( _helper->locateVolInfo("TS1Vacuum").logical );
tsVacua.push_back( _helper->locateVolInfo("TS2Vacuum").logical );
tsVacua.push_back( _helper->locateVolInfo("TS3Vacuum").logical );
tsVacua.push_back( _helper->locateVolInfo("TS4Vacuum").logical );
tsVacua.push_back( _helper->locateVolInfo("TS5Vacuum").logical );
tsVacua.push_back( _helper->locateVolInfo("TS1CryoInsVac").logical );
tsVacua.push_back( _helper->locateVolInfo("TS2CryoInsVac").logical );
tsVacua.push_back( _helper->locateVolInfo("TS3CryoInsVac").logical );
tsVacua.push_back( _helper->locateVolInfo("TS4CryoInsVac").logical );
tsVacua.push_back( _helper->locateVolInfo("TS5CryoInsVac").logical );
vector<G4LogicalVolume*> mbsLVS;
mbsLVS.push_back( _helper->locateVolInfo("MBSMother").logical );
// We may make separate G4UserLimits objects per logical volume but we choose not to.
// At some it might be interesting to make several step limiters, each with different
// limits. For now that is not necessary.
AntiLeakRegistry& reg = art::ServiceHandle<Mu2eG4Helper>()->antiLeakRegistry();
G4UserLimits* stepLimit = reg.add( G4UserLimits(bfieldMaxStep_) );
if(_g4VerbosityLevel > 0) {
G4cout << __func__ << " Using step limit = "<<bfieldMaxStep_/CLHEP::mm<<" mm"<<G4endl;
}
// Add the step limiters to the interesting volumes.
// Keep them separated so that we can add different step limits should we decide to.
// hallAir->SetUserLimits( stepLimit ); // not a vacuum per se; CPU costly
// calorimeter does not use the nest functions; fixme
// so we need to use the geant4's functions
// in addition, some of its logical volumes are duplicated; fixme
G4LogicalVolumeStore* lvs = G4LogicalVolumeStore::GetInstance();
setStepLimitToAllSuchVolumes("caloBackPlateFEELog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloCrystalFrameInLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloFEBLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloFEEBoxInLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloFrontPlateLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloFullBackPlateLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("caloHoleBackLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("calofullCrystalDiskLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("ccrateBoxInLog", stepLimit,lvs,_g4VerbosityLevel);
setStepLimitToAllSuchVolumes("ccrateFullBoxLog", stepLimit,lvs,_g4VerbosityLevel);
ds1Vacuum->SetUserLimits( stepLimit );
ds2Vacuum->SetUserLimits( stepLimit );
ds3Vacuum->SetUserLimits( stepLimit );
dsCVacuum->SetUserLimits( stepLimit );
tracker->SetUserLimits( stepLimit );
trackerPanel->SetUserLimits( stepLimit );
caloMother->SetUserLimits( stepLimit );
stoppingTarget->SetUserLimits( stepLimit );
productionTarget->SetUserLimits( stepLimit );
for ( auto lv : psVacua ){
lv->SetUserLimits( stepLimit);
}
for ( auto lv : tsVacua ){
lv->SetUserLimits( stepLimit);
}
for ( auto lv : mbsLVS ){
lv->SetUserLimits( stepLimit );
}
// Now do all of the tracker related envelope volumes, using regex's with wildcards.
stepLimiterHelper("^TrackerPlaneEnvelope_.*$", stepLimit );
stepLimiterHelper("^TrackerSupportServiceEnvelope_.*$", stepLimit );
stepLimiterHelper("^TrackerSupportServiceSectionEnvelope_.*$", stepLimit );
// special case for straws to get the energy deposits right
if (strawGasMaxStep_>0.0) {
G4UserLimits* strawGasStepLimit = reg.add( G4UserLimits(strawGasMaxStep_) );
if(_g4VerbosityLevel > 0) {
G4cout << __func__<< " Using strawGas step limit = "
<<strawGasMaxStep_/CLHEP::mm<<" mm"<<G4endl;
}
stepLimiterHelper("^TrackerStrawGas_.*$", strawGasStepLimit);
}
// and the calorimeter elements
stepLimiterHelper("^caloDisk_.*$", stepLimit );
stepLimiterHelper("^caloFEB_.*$", stepLimit );
// calorimeter does not use Mu2e nest functions for those; see above; fixme
// stepLimiterHelper("^caloFEBLog*$", stepLimit );
// stepLimiterHelper("^ccrateFullBoxLog*$", stepLimit );
// stepLimiterHelper("^ccrateBoxInLog*$", stepLimit );
// stepLimiterHelper("^ccrateBoardLog*$", stepLimit );
// stepLimiterHelper("^caloFrontPlateLog*$", stepLimit );
// stepLimiterHelper("^caloCrystalFrameInLog*$", stepLimit );
// stepLimiterHelper("^caloHoleBackLog*$", stepLimit );
// stepLimiterHelper("^caloFEEBoxInLog*$", stepLimit );
// stepLimiterHelper("^caloBackPlateFEELog*$", stepLimit );
// stepLimiterHelper("^caloFullBackPlateLog*$", stepLimit );
// An option to limit the step size in these non-vaccum volumes to
// visually validate geometry of the filter channel
//
// ==== BEGIN COMMENT-OUT: to allow construction of new building dirt volumes w/o overlaps (knoepfel)
//
// G4LogicalVolume* emfcMagnetAperture = _helper->locateVolInfo("ExtMonFNALfilterMagnetAperture").logical;
// if(emfcMagnetAperture) {
// const double maxStepLength = _config.getDouble("extMonFNAL.maxG4StepLength", 0)*CLHEP::millimeter;
// if(maxStepLength > 0) {
// G4cout<< __func__<<"Adding step limiter for ExtMonFNALFilterMagnet: maxStepLength = "<<maxStepLength<<G4endl;
// G4UserLimits* emfcStepLimit = reg.add(G4UserLimits(maxStepLength));
// emfcMagnetAperture->SetUserLimits(emfcStepLimit);
// _helper->locateVolInfo("ExtMonFNALfilterMagnetIron").logical->SetUserLimits(emfcStepLimit);
// }
// }
//
// ==== END COMMENT-OUT
// Activate step limiter everywhere for spectial studies
if(limitStepInAllVolumes_) {
stepLimiterHelper("^.*$", stepLimit);
}
} // end Mu2eWorld::constructStepLimiters(){
// Construct calorimeter if needed.
VolumeInfo Mu2eWorld::constructCal(){
// The calorimeter is built inside this volume.
std::string theDS3("DS3Vacuum");
if ( _config.getBool("inGaragePosition",false) ) theDS3 = "garageFakeDS3Vacuum";
VolumeInfo const & detSolDownstreamVacInfo = _helper->locateVolInfo(theDS3);
// Construct one of the calorimeters.
VolumeInfo calorimeterInfo;
if ( _config.getBool("hasDiskCalorimeter",false) ) {
calorimeterInfo = constructDiskCalorimeter( detSolDownstreamVacInfo,_config );
}
return calorimeterInfo;
}//Mu2eWorld::constructCal
// A place holder for now.
void Mu2eWorld::constructMagnetYoke(){
}//Mu2eWorld::constructMagnetYoke
// instantiateSensitiveDetectors
void Mu2eWorld::instantiateSensitiveDetectors(){
//art::ServiceHandle<GeometryService> geom;//I don't see this being used!
G4SDManager* SDman = G4SDManager::GetSDMpointer();
//get the LVStore singleton
G4LogicalVolumeStore* store = G4LogicalVolumeStore::GetInstance();
// G4 takes ownership and will delete the detectors at the job end
/************************** Tracker **************************/
//done
if(sdHelper_->enabled(StepInstanceName::tracker)) {
StrawSD* strawSD =
new StrawSD( SensitiveDetectorName::TrackerGas(), _config );
SDman->AddNewDetector(strawSD);
//loop over all of the LV names and find the ones we need
//set the SensitiveDetectors for these
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from ConstructTrackerTDR and constructTrackerv3
if (LVname.find("TrackerStrawGas_") != std::string::npos) {
(*pos)->SetSensitiveDetector(strawSD);
}
}//for
}//if tracker
/************************** TrackerDS **************************/
//done
if(sdHelper_->enabled(StepInstanceName::trackerDS)) {
TrackerPlaneSupportSD* ttdsSD =
new TrackerPlaneSupportSD( SensitiveDetectorName::TrackerPlaneSupport(), _config );
SDman->AddNewDetector(ttdsSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from constructTrackerv3
if (LVname.find("TrackerPlaneSupport_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttdsSD);
}
//from constructTrackerv3Detailed
if (LVname.find("TrackerSupportElecCu") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttdsSD);
}
}//for
}//if trackerDS
/************************** VirtualDetector **************************/
//done
if(sdHelper_->enabled(StepInstanceName::virtualdetector)) {
Mu2eG4SensitiveDetector* vdSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::VirtualDetector(), _config );
SDman->AddNewDetector(vdSD);
constructVirtualDetectorSDs(_config, vdSD);
}//if virtualdetector
/************************** trackerSWires **************************/
//done
if (sdHelper_->enabled(StepInstanceName::trackerSWires)) {
TrackerWireSD *ttwsSD =
new TrackerWireSD(SensitiveDetectorName::TrackerSWires(), _config);
SDman->AddNewDetector(ttwsSD);
//trackerSWires need to be fixed if virtual detector is fixed
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from ConstructTrackerTDR
if (LVname.find("TrackerStrawWire_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwsSD);
}
//from ConstructTrackerTDR
if (LVname.find("TrackerWireCore_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwsSD);
}
//from ConstructTrackerTDR
if (LVname.find("TrackerWirePlate_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwsSD);
}
}//for
}//if trackerSWires
/************************** trackerWalls **************************/
//done
if (sdHelper_->enabled(StepInstanceName::trackerWalls)) {
TrackerWireSD *ttwlSD =
new TrackerWireSD( SensitiveDetectorName::TrackerWalls(), _config );
SDman->AddNewDetector(ttwlSD);
//trackerWalls need to be fixed if virtual detector is fixed
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from ConstructTrackerTDR and constructTrackerv3
if (LVname.find("TrackerStrawWall_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwlSD);
}
//from ConstructTrackerTDR
if (LVname.find("TrackerStrawWallOuterMetal_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwlSD);
}
//from ConstructTrackerTDR
if (LVname.find("TrackerStrawWallInnerMetal1_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwlSD);
}
//from ConstructTrackerTDR
if (LVname.find("TrackerStrawWallInnerMetal2_") != std::string::npos) {
(*pos)->SetSensitiveDetector(ttwlSD);
}
}//for
}//if trackerWalls
/************************** CALORIMETER **************************/
// _geom is member data of Mu2eG4Universe, from which this inherits (GeoService const&)
//done
if ( const_cast<GeometryService&>(_geom).hasElement<Calorimeter>() ) {
if(sdHelper_->enabled(StepInstanceName::calorimeter)) {
CaloCrystalSD* ccSD =
new CaloCrystalSD( SensitiveDetectorName::CaloCrystal(), _config );
SDman->AddNewDetector(ccSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("CrystalLog") != std::string::npos) {
(*pos)->SetSensitiveDetector(ccSD);
}
}//for
}//if calorimeter
if(sdHelper_->enabled(StepInstanceName::calorimeterRO)) {
CaloReadoutSD* crSD =
new CaloReadoutSD( SensitiveDetectorName::CaloReadout(), _config );
SDman->AddNewDetector(crSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("CrystalROLog") != std::string::npos) {
(*pos)->SetSensitiveDetector(crSD);
}
}//for
}//if calorimeterRO
if(sdHelper_->enabled(StepInstanceName::calorimeterROCard)) {
CaloReadoutCardSD* crCardSD =
new CaloReadoutCardSD( SensitiveDetectorName::CaloReadoutCard(), _config );
SDman->AddNewDetector(crCardSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("caloFEECardROLog") != std::string::npos) {
(*pos)->SetSensitiveDetector(crCardSD);
}
}//for
}//if calorimeterROCard
if(sdHelper_->enabled(StepInstanceName::calorimeterCrate)) {
CaloCrateSD* cCrateSD =
new CaloCrateSD( SensitiveDetectorName::CaloCrate(), _config );
SDman->AddNewDetector(cCrateSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ccrateActiveStripLog") != std::string::npos) {
(*pos)->SetSensitiveDetector(cCrateSD);
}
}//for
}//if calorimeterCrate
}//if calorimeter
/************************** ExtMonFNALPixelSD **************************/
if( sdHelper_->extMonPixelsEnabled() ) {
GeomHandle<mu2e::ExtMonFNAL::ExtMon> extmon;
//SDman->AddNewDetector(new ExtMonFNALPixelSD(_config, *extmon));
ExtMonFNALPixelSD* emSD = new ExtMonFNALPixelSD(_config, *extmon);
SDman->AddNewDetector(emSD);
//from constructExtMonFNALModules
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("EMFModule") != std::string::npos) {
(*pos)->SetSensitiveDetector(emSD);
}
}//for
}
/************************** StoppingTarget **************************/
//done
if(sdHelper_->enabled(StepInstanceName::stoppingtarget)) {
Mu2eG4SensitiveDetector* stSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::StoppingTarget(), _config );
SDman->AddNewDetector(stSD);
//loop over all of the LV names to find ones we need
//set the SensitiveDetectors for these
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("Foil_") != std::string::npos) {
(*pos)->SetSensitiveDetector(stSD);
}
if (LVname.find("FoilSupportStructure_") != std::string::npos) {
(*pos)->SetSensitiveDetector(stSD);
}
}//for
}//if stoppingtarget
//done
/************************** ProductionTarget **************************/
if(sdHelper_->enabled(StepInstanceName::ProductionTargetCoreSection)) {
Mu2eG4SensitiveDetector* prodtargcoreSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetCoreSection(), _config );
SDman->AddNewDetector(prodtargcoreSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetCoreSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargcoreSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetStartingCoreSection)) {
Mu2eG4SensitiveDetector* prodtargstartingcoreSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetStartingCoreSection(), _config );
SDman->AddNewDetector(prodtargstartingcoreSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetStartingCoreSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargstartingcoreSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetFinStartingSection)) {
Mu2eG4SensitiveDetector* prodtargfinstartingSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetFinStartingSection(), _config );
SDman->AddNewDetector(prodtargfinstartingSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetFinStartingSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargfinstartingSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetNegativeEndRing)) {
Mu2eG4SensitiveDetector* prodtargnegativeendringSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetNegativeEndRing(), _config );
SDman->AddNewDetector(prodtargnegativeendringSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetNegativeEndRing") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargnegativeendringSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetPositiveEndRing)) {
Mu2eG4SensitiveDetector* prodtargpositiveendringSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetPositiveEndRing(), _config );
SDman->AddNewDetector(prodtargpositiveendringSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetPositiveEndRing") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargpositiveendringSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetFinSection)) {
Mu2eG4SensitiveDetector* prodtargfinsectionSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetFinSection(), _config );
SDman->AddNewDetector(prodtargfinsectionSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetFinSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargfinsectionSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetFinTopSection)) {
Mu2eG4SensitiveDetector* prodtargfintopsectionSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetFinTopSection(), _config );
SDman->AddNewDetector(prodtargfintopsectionSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetFinTopSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargfintopsectionSD);
}
}
}
if(sdHelper_->enabled(StepInstanceName::ProductionTargetFinTopStartingSection)) {
Mu2eG4SensitiveDetector* prodtargfintopstartingsectionSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProductionTargetFinTopStartingSection(), _config );
SDman->AddNewDetector(prodtargfintopstartingsectionSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if (LVname.find("ProductionTargetFinTopStartingSection") != std::string::npos) {
(*pos)->SetSensitiveDetector(prodtargfintopstartingsectionSD);
}
}
}
/************************** CRV **************************/
if(sdHelper_->enabled(StepInstanceName::CRV)) {
CRVSD* sbSD =
new CRVSD( SensitiveDetectorName::CRSScintillatorBar(), _config );
SDman->AddNewDetector(sbSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//we need names like CRV_R1, but not CRSCMB_CRV_R1 and not CRV_Support_TS
if ((LVname.find("CRV_") != std::string::npos)
&& (LVname.find("CRV_Support") == std::string::npos)
&& (LVname.find("CRSCMB_CRV") == std::string::npos)) {
(*pos)->SetSensitiveDetector(sbSD);
}
}//for
}//if CRV
/************************** ProtonAbsorber **************************/
if(sdHelper_->enabled(StepInstanceName::protonabsorber)) {
Mu2eG4SensitiveDetector* paSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::ProtonAbsorber(), _config );
SDman->AddNewDetector(paSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from constructProtonAbsorber, will pick up protonabs{1,2,3,4}
if (LVname.find("protonabs") != std::string::npos) {
(*pos)->SetSensitiveDetector(paSD);
}
//from HelicalProtonAbsorber
if (LVname.find("helical_pabs_log") != std::string::npos) {
(*pos)->SetSensitiveDetector(paSD);
}
}//for
}//if protonabsorber
/************************** PSVacuum **************************/
//done
if(sdHelper_->enabled(StepInstanceName::PSVacuum)) {
Mu2eG4SensitiveDetector* psVacuumSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::PSVacuum(), _config );
SDman->AddNewDetector(psVacuumSD);
if( _config.getBool("PS.Vacuum.Sensitive", false) ) {
psVacuumLogical_->SetSensitiveDetector(psVacuumSD);
}
}
/************************** STMDet **************************/
//done
if(sdHelper_->enabled(StepInstanceName::STMDet)) {
Mu2eG4SensitiveDetector* STMDetSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::STMDet(), _config );
SDman->AddNewDetector(STMDetSD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
if ( LVname == "stmDet1" || LVname == "stmDet2" ){
(*pos)->SetSensitiveDetector(STMDetSD);
}
}//for
}//if STMDet
/************************** panelEBKey **************************/
if(sdHelper_->enabled(StepInstanceName::panelEBKey)) {
Mu2eG4SensitiveDetector* EBKeySD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::panelEBKey(), _config );
SDman->AddNewDetector(EBKeySD);
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++) {
G4String LVname = (*pos)->GetName();
//we need the PanelEBKey, but NOT the PanelEBKeyShield
if ((LVname.find("PanelEBKey") != std::string::npos) &&
(LVname.find("PanelEBKeyShield") == std::string::npos)) {
(*pos)->SetSensitiveDetector(EBKeySD);
}
}//for
}//if panelEBKey
/************************** DSCableRun **************************/
//if ( cableRunSensitive && sdHelper.enabled(StepInstanceName::DSCableRun) )
if(sdHelper_->enabled(StepInstanceName::DSCableRun)) {
Mu2eG4SensitiveDetector* cableRunSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::DSCableRun(), _config );
SDman->AddNewDetector(cableRunSD);
//NOTE: THIS 'if' test seems redundant to me, but I am just copying the format from constructDS.cc
if ( _config.getBool("ds.CableRun.sensitive",false) ) {
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++) {
G4String LVname = (*pos)->GetName();
//will pick up names like CalCableRun, CalCableRunUpGap1, CalCableRunUpGap2, calCableRunFall
//but not CalCableRunLogInCalFeb, CalCableRunInCalFeb
if ( (LVname.find("alCableRun") != std::string::npos) &&
(LVname.find("CalCableRunLog") == std::string::npos) &&
(LVname.find("CalCableRunIn") == std::string::npos) )
{
(*pos)->SetSensitiveDetector(cableRunSD);
}
//will pick up names like TrkCableRun1, TrkCableRun2, TrkCableRunGap1, TrkCableRunGap1a, TrkCableRunGap2, TrkCableRunGap2a
//but not TrkCableRun1LogInCalFeb, TrkCableRun2LogInCalFeb, TrkCableRun1InCalFeb, TrkCableRun2InCalFeb
if ( (LVname.find("TrkCableRun") != std::string::npos) &&
(LVname.find("TrkCableRun1Log") == std::string::npos) &&
(LVname.find("TrkCableRun2Log") == std::string::npos) &&
(LVname.find("TrkCableRun1In") == std::string::npos) &&
(LVname.find("TrkCableRun2In") == std::string::npos) )
{
(*pos)->SetSensitiveDetector(cableRunSD);
}
}//for
}//if ds.CableRun.sensitive
}//if DSCableRun
/********************* Production target monitor *********************/
if(sdHelper_->enabled(StepInstanceName::PTM)) {
Mu2eG4SensitiveDetector* ptMonSD =
new Mu2eG4SensitiveDetector( SensitiveDetectorName::PTM(), _config );
SDman->AddNewDetector(ptMonSD);
//loop over all of the LV names and find the ones we need
//set the SensitiveDetectors for these
for(G4LogicalVolumeStore::iterator pos=store->begin(); pos!=store->end(); pos++){
G4String LVname = (*pos)->GetName();
//from constructPTM
if (LVname.find("PTMWire") != std::string::npos) {
(*pos)->SetSensitiveDetector(ptMonSD);
}
}//for
}//if pTargetMon
}//instantiateSensitiveDetectors
} // end namespace mu2e
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include "chainparams.h"
#include "keystore.h"
#include "net.h"
#include "net_processing.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"
#include "test/test_blockdee.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
CService ip(uint32_t i)
{
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(DoS_banning)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100); // Should get banned
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode2, *connman);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet...
BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr2));
}
BOOST_AUTO_TEST_CASE(DoS_banscore)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 10);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
int64_t nStartTime = GetTime();
SetMockTime(nStartTime); // Overrides future calls to GetTime()
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode, *connman);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
Misbehaving(dummyNode.GetId(), 100);
SendMessages(&dummyNode, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60*24+1);
BOOST_CHECK(!connman->IsBanned(addr));
}
CTransactionRef RandomOrphan()
{
std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(GetRandHash());
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
return it->second.tx;
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
CKey key;
key.MakeNewKey(true);
CBasicKeyStore keystore;
keystore.AddKey(key);
// 50 orphan transactions:
for (int i = 0; i < 50; i++)
{
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = GetRandHash();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetHash();
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
SignSignature(keystore, *txPrev, tx, 0);
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
tx.vin.resize(2777);
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetHash();
}
SignSignature(keystore, *txPrev, tx, 0);
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++)
{
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
}
BOOST_AUTO_TEST_SUITE_END()
|
#ifndef PYTHONIC_INCLUDE_NUMPY_INT32_HPP
#define PYTHONIC_INCLUDE_NUMPY_INT32_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/utils/meta.hpp"
#include "pythonic/utils/numpy_traits.hpp"
#include "pythonic/types/numpy_op_helper.hpp"
namespace pythonic
{
namespace numpy
{
namespace details
{
int32_t int32();
template <class V>
int32_t int32(V v);
}
#define NUMPY_NARY_FUNC_NAME int32
#define NUMPY_NARY_FUNC_SYM details::int32
#include "pythonic/include/types/numpy_nary_expr.hpp"
}
}
#endif
|
/* NOTE - eventually this file will be automatically updated using a Perl script that understand
* the naming of test case files, functions, and namespaces.
*/
#include <time.h> /* for time() */
#include <stdlib.h> /* for srand() */
#include "std_testcase.h"
#include "testcases.h"
int main(int argc, char * argv[]) {
/* seed randomness */
srand( (unsigned)time(NULL) );
globalArgc = argc;
globalArgv = argv;
#ifndef OMITGOOD
/* Calling C good functions */
/* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_16_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_16_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_06_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_06_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_02_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_02_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_18_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_18_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_08_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_08_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_05_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_05_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_17_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_17_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_04_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_04_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_03_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_03_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_10_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_10_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_07_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_07_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_15_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_15_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_01_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_01_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_11_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_11_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_14_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_14_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_09_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_09_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_12_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_12_good();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_13_good();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_13_good();
/* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ good functions */
/* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITGOOD */
#ifndef OMITBAD
/* Calling C bad functions */
/* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_16_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_16_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_06_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_06_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_02_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_02_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_18_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_18_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_08_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_08_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_05_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_05_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_17_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_17_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_04_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_04_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_03_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_03_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_10_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_10_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_07_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_07_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_15_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_15_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_01_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_01_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_11_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_11_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_14_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_14_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_09_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_09_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_12_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_12_bad();
printLine("Calling CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_13_bad();");
CWE780_Use_of_RSA_Algorithm_Without_OAEP__w32_13_bad();
/* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ bad functions */
/* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITBAD */
return 0;
}
|
/*
* MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
* NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information.
* Released into the public domain.
*/
#include <Arduino.h>
#include "MFRC522.h"
/////////////////////////////////////////////////////////////////////////////////////
// Functions for setting up the Arduino
/////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
MFRC522::MFRC522(): MFRC522(SS, UINT8_MAX) { // SS is defined in pins_arduino.h, UINT8_MAX means there is no connection from Arduino to MFRC522's reset and power down input
} // End constructor
/**
* Constructor.
* Prepares the output pins.
*/
MFRC522::MFRC522( byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low). If there is no connection from the CPU to NRSTPD, set this to UINT8_MAX. In this case, only soft reset will be used in PCD_Init().
): MFRC522(SS, resetPowerDownPin) { // SS is defined in pins_arduino.h
} // End constructor
/**
* Constructor.
* Prepares the output pins.
*/
MFRC522::MFRC522( byte chipSelectPin, ///< Arduino pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low)
byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low). If there is no connection from the CPU to NRSTPD, set this to UINT8_MAX. In this case, only soft reset will be used in PCD_Init().
) {
_chipSelectPin = chipSelectPin;
_resetPowerDownPin = resetPowerDownPin;
} // End constructor
/////////////////////////////////////////////////////////////////////////////////////
// Basic interface functions for communicating with the MFRC522
/////////////////////////////////////////////////////////////////////////////////////
/**
* Writes a byte to the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void MFRC522::PCD_WriteRegister( PCD_Register reg, ///< The register to write to. One of the PCD_Register enums.
byte value ///< The value to write.
) {
SPI.beginTransaction(SPISettings(MFRC522_SPICLOCK, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
digitalWrite(_chipSelectPin, LOW); // Select slave
SPI.transfer(reg); // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
SPI.transfer(value);
digitalWrite(_chipSelectPin, HIGH); // Release slave again
SPI.endTransaction(); // Stop using the SPI bus
} // End PCD_WriteRegister()
/**
* Writes a number of bytes to the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void MFRC522::PCD_WriteRegister( PCD_Register reg, ///< The register to write to. One of the PCD_Register enums.
byte count, ///< The number of bytes to write to the register
byte *values ///< The values to write. Byte array.
) {
SPI.beginTransaction(SPISettings(MFRC522_SPICLOCK, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
digitalWrite(_chipSelectPin, LOW); // Select slave
SPI.transfer(reg); // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
for (byte index = 0; index < count; index++) {
SPI.transfer(values[index]);
}
digitalWrite(_chipSelectPin, HIGH); // Release slave again
SPI.endTransaction(); // Stop using the SPI bus
} // End PCD_WriteRegister()
/**
* Reads a byte from the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
byte MFRC522::PCD_ReadRegister( PCD_Register reg ///< The register to read from. One of the PCD_Register enums.
) {
byte value;
SPI.beginTransaction(SPISettings(MFRC522_SPICLOCK, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
digitalWrite(_chipSelectPin, LOW); // Select slave
SPI.transfer(0x80 | reg); // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
value = SPI.transfer(0); // Read the value back. Send 0 to stop reading.
digitalWrite(_chipSelectPin, HIGH); // Release slave again
SPI.endTransaction(); // Stop using the SPI bus
return value;
} // End PCD_ReadRegister()
/**
* Reads a number of bytes from the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void MFRC522::PCD_ReadRegister( PCD_Register reg, ///< The register to read from. One of the PCD_Register enums.
byte count, ///< The number of bytes to read
byte *values, ///< Byte array to store the values in.
byte rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated.
) {
if (count == 0) {
return;
}
//Serial.print(F("Reading ")); Serial.print(count); Serial.println(F(" bytes from register."));
byte address = 0x80 | reg; // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
byte index = 0; // Index in values array.
SPI.beginTransaction(SPISettings(MFRC522_SPICLOCK, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
digitalWrite(_chipSelectPin, LOW); // Select slave
count--; // One read is performed outside of the loop
SPI.transfer(address); // Tell MFRC522 which address we want to read
if (rxAlign) { // Only update bit positions rxAlign..7 in values[0]
// Create bit mask for bit positions rxAlign..7
byte mask = (0xFF << rxAlign) & 0xFF;
// Read value and tell that we want to read the same address again.
byte value = SPI.transfer(address);
// Apply mask to both current value of values[0] and the new data in value.
values[0] = (values[0] & ~mask) | (value & mask);
index++;
}
while (index < count) {
values[index] = SPI.transfer(address); // Read value and tell that we want to read the same address again.
index++;
}
values[index] = SPI.transfer(0); // Read the final byte. Send 0 to stop reading.
digitalWrite(_chipSelectPin, HIGH); // Release slave again
SPI.endTransaction(); // Stop using the SPI bus
} // End PCD_ReadRegister()
/**
* Sets the bits given in mask in register reg.
*/
void MFRC522::PCD_SetRegisterBitMask( PCD_Register reg, ///< The register to update. One of the PCD_Register enums.
byte mask ///< The bits to set.
) {
byte tmp;
tmp = PCD_ReadRegister(reg);
PCD_WriteRegister(reg, tmp | mask); // set bit mask
} // End PCD_SetRegisterBitMask()
/**
* Clears the bits given in mask from register reg.
*/
void MFRC522::PCD_ClearRegisterBitMask( PCD_Register reg, ///< The register to update. One of the PCD_Register enums.
byte mask ///< The bits to clear.
) {
byte tmp;
tmp = PCD_ReadRegister(reg);
PCD_WriteRegister(reg, tmp & (~mask)); // clear bit mask
} // End PCD_ClearRegisterBitMask()
/**
* Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PCD_CalculateCRC( byte *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation.
byte length, ///< In: The number of bytes to transfer.
byte *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first.
) {
PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command.
PCD_WriteRegister(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit
PCD_WriteRegister(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
PCD_WriteRegister(FIFODataReg, length, data); // Write data to the FIFO
PCD_WriteRegister(CommandReg, PCD_CalcCRC); // Start the calculation
// Wait for the CRC calculation to complete. Check for the register to
// indicate that the CRC calculation is complete in a loop. If the
// calculation is not indicated as complete in ~90ms, then time out
// the operation.
const uint32_t deadline = millis() + 89;
do {
// DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
byte n = PCD_ReadRegister(DivIrqReg);
if (n & 0x04) { // CRCIRq bit set - calculation done
PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
// Transfer the result from the registers to the result buffer
result[0] = PCD_ReadRegister(CRCResultRegL);
result[1] = PCD_ReadRegister(CRCResultRegH);
return STATUS_OK;
}
yield();
}
while (static_cast<uint32_t> (millis()) < deadline);
// 89ms passed and nothing happened. Communication with the MFRC522 might be down.
return STATUS_TIMEOUT;
} // End PCD_CalculateCRC()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for manipulating the MFRC522
/////////////////////////////////////////////////////////////////////////////////////
/**
* Initializes the MFRC522 chip.
*/
void MFRC522::PCD_Init() {
bool hardReset = false;
// Set the chipSelectPin as digital output, do not select the slave yet
pinMode(_chipSelectPin, OUTPUT);
digitalWrite(_chipSelectPin, HIGH);
// If a valid pin number has been set, pull device out of power down / reset state.
if (_resetPowerDownPin != UNUSED_PIN) {
// First set the resetPowerDownPin as digital input, to check the MFRC522 power down mode.
pinMode(_resetPowerDownPin, INPUT);
if (digitalRead(_resetPowerDownPin) == LOW) { // The MFRC522 chip is in power down mode.
pinMode(_resetPowerDownPin, OUTPUT); // Now set the resetPowerDownPin as digital output.
digitalWrite(_resetPowerDownPin, LOW); // Make sure we have a clean LOW state.
delayMicroseconds(2); // 8.8.1 Reset timing requirements says about 100ns. Let us be generous: 2μsl
digitalWrite(_resetPowerDownPin, HIGH); // Exit power down mode. This triggers a hard reset.
// Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs. Let us be generous: 50ms.
delay(50);
hardReset = true;
}
}
if (!hardReset) { // Perform a soft reset if we haven't triggered a hard reset above.
PCD_Reset();
}
// Reset baud rates
PCD_WriteRegister(TxModeReg, 0x00);
PCD_WriteRegister(RxModeReg, 0x00);
// Reset ModWidthReg
PCD_WriteRegister(ModWidthReg, 0x26);
// When communicating with a PICC we need a timeout if something goes wrong.
// f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
// TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
PCD_WriteRegister(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
PCD_WriteRegister(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.
PCD_WriteRegister(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
PCD_WriteRegister(TReloadRegL, 0xE8);
PCD_WriteRegister(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
PCD_WriteRegister(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)
PCD_AntennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)
} // End PCD_Init()
/**
* Initializes the MFRC522 chip.
*/
void MFRC522::PCD_Init( byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low)
) {
PCD_Init(SS, resetPowerDownPin); // SS is defined in pins_arduino.h
} // End PCD_Init()
/**
* Initializes the MFRC522 chip.
*/
void MFRC522::PCD_Init( byte chipSelectPin, ///< Arduino pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low)
byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low)
) {
_chipSelectPin = chipSelectPin;
_resetPowerDownPin = resetPowerDownPin;
// Set the chipSelectPin as digital output, do not select the slave yet
PCD_Init();
} // End PCD_Init()
/**
* Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
*/
void MFRC522::PCD_Reset() {
PCD_WriteRegister(CommandReg, PCD_SoftReset); // Issue the SoftReset command.
// The datasheet does not mention how long the SoftRest command takes to complete.
// But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
// Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs. Let us be generous: 50ms.
uint8_t count = 0;
do {
// Wait for the PowerDown bit in CommandReg to be cleared (max 3x50ms)
delay(50);
} while ((PCD_ReadRegister(CommandReg) & (1 << 4)) && (++count) < 3);
} // End PCD_Reset()
/**
* Turns the antenna on by enabling pins TX1 and TX2.
* After a reset these pins are disabled.
*/
void MFRC522::PCD_AntennaOn() {
byte value = PCD_ReadRegister(TxControlReg);
if ((value & 0x03) != 0x03) {
PCD_WriteRegister(TxControlReg, value | 0x03);
}
} // End PCD_AntennaOn()
/**
* Turns the antenna off by disabling pins TX1 and TX2.
*/
void MFRC522::PCD_AntennaOff() {
PCD_ClearRegisterBitMask(TxControlReg, 0x03);
} // End PCD_AntennaOff()
/**
* Get the current MFRC522 Receiver Gain (RxGain[2:0]) value.
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
* NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
*
* @return Value of the RxGain, scrubbed to the 3 bits used.
*/
byte MFRC522::PCD_GetAntennaGain() {
return PCD_ReadRegister(RFCfgReg) & (0x07<<4);
} // End PCD_GetAntennaGain()
/**
* Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask.
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
* NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
*/
void MFRC522::PCD_SetAntennaGain(byte mask) {
if (PCD_GetAntennaGain() != mask) { // only bother if there is a change
PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4)); // clear needed to allow 000 pattern
PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits
}
} // End PCD_SetAntennaGain()
/**
* Performs a self-test of the MFRC522
* See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
*
* @return Whether or not the test passed. Or false if no firmware reference is available.
*/
bool MFRC522::PCD_PerformSelfTest() {
// This follows directly the steps outlined in 16.1.1
// 1. Perform a soft reset.
PCD_Reset();
// 2. Clear the internal buffer by writing 25 bytes of 00h
byte ZEROES[25] = {0x00};
PCD_WriteRegister(FIFOLevelReg, 0x80); // flush the FIFO buffer
PCD_WriteRegister(FIFODataReg, 25, ZEROES); // write 25 bytes of 00h to FIFO
PCD_WriteRegister(CommandReg, PCD_Mem); // transfer to internal buffer
// 3. Enable self-test
PCD_WriteRegister(AutoTestReg, 0x09);
// 4. Write 00h to FIFO buffer
PCD_WriteRegister(FIFODataReg, 0x00);
// 5. Start self-test by issuing the CalcCRC command
PCD_WriteRegister(CommandReg, PCD_CalcCRC);
// 6. Wait for self-test to complete
byte n;
for (uint8_t i = 0; i < 0xFF; i++) {
// The datasheet does not specify exact completion condition except
// that FIFO buffer should contain 64 bytes.
// While selftest is initiated by CalcCRC command
// it behaves differently from normal CRC computation,
// so one can't reliably use DivIrqReg to check for completion.
// It is reported that some devices does not trigger CRCIRq flag
// during selftest.
n = PCD_ReadRegister(FIFOLevelReg);
if (n >= 64) {
break;
}
}
PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
// 7. Read out resulting 64 bytes from the FIFO buffer.
byte result[64];
PCD_ReadRegister(FIFODataReg, 64, result, 0);
// Auto self-test done
// Reset AutoTestReg register to be 0 again. Required for normal operation.
PCD_WriteRegister(AutoTestReg, 0x00);
// Determine firmware version (see section 9.3.4.8 in spec)
byte version = PCD_ReadRegister(VersionReg);
// Pick the appropriate reference values
const byte *reference;
switch (version) {
case 0x88: // Fudan Semiconductor FM17522 clone
reference = FM17522_firmware_reference;
break;
case 0x90: // Version 0.0
reference = MFRC522_firmware_referenceV0_0;
break;
case 0x91: // Version 1.0
reference = MFRC522_firmware_referenceV1_0;
break;
case 0x92: // Version 2.0
reference = MFRC522_firmware_referenceV2_0;
break;
default: // Unknown version
return false; // abort test
}
// Verify that the results match up to our expectations
for (uint8_t i = 0; i < 64; i++) {
if (result[i] != pgm_read_byte(&(reference[i]))) {
return false;
}
}
// Test passed; all is good.
return true;
} // End PCD_PerformSelfTest()
/////////////////////////////////////////////////////////////////////////////////////
// Power control
/////////////////////////////////////////////////////////////////////////////////////
//IMPORTANT NOTE!!!!
//Calling any other function that uses CommandReg will disable soft power down mode !!!
//For more details about power control, refer to the datasheet - page 33 (8.6)
void MFRC522::PCD_SoftPowerDown(){//Note : Only soft power down mode is available throught software
byte val = PCD_ReadRegister(CommandReg); // Read state of the command register
val |= (1<<4);// set PowerDown bit ( bit 4 ) to 1
PCD_WriteRegister(CommandReg, val);//write new value to the command register
}
void MFRC522::PCD_SoftPowerUp(){
byte val = PCD_ReadRegister(CommandReg); // Read state of the command register
val &= ~(1<<4);// set PowerDown bit ( bit 4 ) to 0
PCD_WriteRegister(CommandReg, val);//write new value to the command register
// wait until PowerDown bit is cleared (this indicates end of wake up procedure)
const uint32_t timeout = (uint32_t)millis() + 500;// create timer for timeout (just in case)
while(millis()<=timeout){ // set timeout to 500 ms
val = PCD_ReadRegister(CommandReg);// Read state of the command register
if(!(val & (1<<4))){ // if powerdown bit is 0
break;// wake up procedure is finished
}
yield();
}
}
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with PICCs
/////////////////////////////////////////////////////////////////////////////////////
/**
* Executes the Transceive command.
* CRC validation can only be done if backData and backLen are specified.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PCD_TransceiveData( byte *sendData, ///< Pointer to the data to transfer to the FIFO.
byte sendLen, ///< Number of bytes to transfer to the FIFO.
byte *backData, ///< nullptr or pointer to buffer if data should be read back after executing the command.
byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default nullptr.
byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
) {
byte waitIRq = 0x30; // RxIRq and IdleIRq
return PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC);
} // End PCD_TransceiveData()
/**
* Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO.
* CRC validation can only be done if backData and backLen are specified.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PCD_CommunicateWithPICC( byte command, ///< The command to execute. One of the PCD_Command enums.
byte waitIRq, ///< The bits in the ComIrqReg register that signals successful completion of the command.
byte *sendData, ///< Pointer to the data to transfer to the FIFO.
byte sendLen, ///< Number of bytes to transfer to the FIFO.
byte *backData, ///< nullptr or pointer to buffer if data should be read back after executing the command.
byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits.
byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
) {
// Prepare values for BitFramingReg
byte txLastBits = validBits ? *validBits : 0;
byte bitFraming = (rxAlign << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command.
PCD_WriteRegister(ComIrqReg, 0x7F); // Clear all seven interrupt request bits
PCD_WriteRegister(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
PCD_WriteRegister(FIFODataReg, sendLen, sendData); // Write sendData to the FIFO
PCD_WriteRegister(BitFramingReg, bitFraming); // Bit adjustments
PCD_WriteRegister(CommandReg, command); // Execute the command
if (command == PCD_Transceive) {
PCD_SetRegisterBitMask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts
}
// In PCD_Init() we set the TAuto flag in TModeReg. This means the timer
// automatically starts when the PCD stops transmitting.
//
// Wait here for the command to complete. The bits specified in the
// `waitIRq` parameter define what bits constitute a completed command.
// When they are set in the ComIrqReg register, then the command is
// considered complete. If the command is not indicated as complete in
// ~36ms, then consider the command as timed out.
const uint32_t deadline = millis() + 36;
bool completed = false;
do {
byte n = PCD_ReadRegister(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
if (n & waitIRq) { // One of the interrupts that signal success has been set.
completed = true;
break;
}
if (n & 0x01) { // Timer interrupt - nothing received in 25ms
return STATUS_TIMEOUT;
}
yield();
}
while (static_cast<uint32_t> (millis()) < deadline);
// 36ms and nothing happened. Communication with the MFRC522 might be down.
if (!completed) {
return STATUS_TIMEOUT;
}
// Stop now if any errors except collisions were detected.
byte errorRegValue = PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
if (errorRegValue & 0x13) { // BufferOvfl ParityErr ProtocolErr
return STATUS_ERROR;
}
byte _validBits = 0;
// If the caller wants data back, get it from the MFRC522.
if (backData && backLen) {
byte n = PCD_ReadRegister(FIFOLevelReg); // Number of bytes in the FIFO
if (n > *backLen) {
return STATUS_NO_ROOM;
}
*backLen = n; // Number of bytes returned
PCD_ReadRegister(FIFODataReg, n, backData, rxAlign); // Get received data from FIFO
_validBits = PCD_ReadRegister(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid.
if (validBits) {
*validBits = _validBits;
}
}
// Tell about collisions
if (errorRegValue & 0x08) { // CollErr
return STATUS_COLLISION;
}
// Perform CRC_A validation if requested.
if (backData && backLen && checkCRC) {
// In this case a MIFARE Classic NAK is not OK.
if (*backLen == 1 && _validBits == 4) {
return STATUS_MIFARE_NACK;
}
// We need at least the CRC_A value and all 8 bits of the last byte must be received.
if (*backLen < 2 || _validBits != 0) {
return STATUS_CRC_WRONG;
}
// Verify CRC_A - do our own calculation and store the control in controlBuffer.
byte controlBuffer[2];
MFRC522::StatusCode status = PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]);
if (status != STATUS_OK) {
return status;
}
if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) {
return STATUS_CRC_WRONG;
}
}
return STATUS_OK;
} // End PCD_CommunicateWithPICC()
/**
* Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PICC_RequestA( byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
) {
return PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize);
} // End PICC_RequestA()
/**
* Transmits a Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PICC_WakeupA( byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
) {
return PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize);
} // End PICC_WakeupA()
/**
* Transmits REQA or WUPA commands.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PICC_REQA_or_WUPA( byte command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA
byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
) {
byte validBits;
MFRC522::StatusCode status;
if (bufferATQA == nullptr || *bufferSize < 2) { // The ATQA response is 2 bytes long.
return STATUS_NO_ROOM;
}
PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
validBits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0]
status = PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits);
if (status != STATUS_OK) {
return status;
}
if (*bufferSize != 2 || validBits != 0) { // ATQA must be exactly 16 bits.
return STATUS_ERROR;
}
return STATUS_OK;
} // End PICC_REQA_or_WUPA()
/**
* Transmits SELECT/ANTICOLLISION commands to select a single PICC.
* Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA().
* On success:
* - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.)
* - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
*
* A PICC UID consists of 4, 7 or 10 bytes.
* Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
* UID size Number of UID bytes Cascade levels Example of PICC
* ======== =================== ============== ===============
* single 4 1 MIFARE Classic
* double 7 2 MIFARE Ultralight
* triple 10 3 Not currently in use?
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PICC_Select( Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
byte validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
) {
bool uidComplete;
bool selectDone;
bool useCascadeTag;
byte cascadeLevel = 1;
MFRC522::StatusCode result;
byte count;
byte checkBit;
byte index;
byte uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level.
int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level.
byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A
byte bufferUsed; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO.
byte rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received.
byte txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte.
byte *responseBuffer;
byte responseLength;
// Description of buffer structure:
// Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3
// Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits.
// Byte 2: UID-data or CT See explanation below. CT means Cascade Tag.
// Byte 3: UID-data
// Byte 4: UID-data
// Byte 5: UID-data
// Byte 6: BCC Block Check Character - XOR of bytes 2-5
// Byte 7: CRC_A
// Byte 8: CRC_A
// The BCC and CRC_A are only transmitted if we know all the UID bits of the current Cascade Level.
//
// Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels)
// UID size Cascade level Byte2 Byte3 Byte4 Byte5
// ======== ============= ===== ===== ===== =====
// 4 bytes 1 uid0 uid1 uid2 uid3
// 7 bytes 1 CT uid0 uid1 uid2
// 2 uid3 uid4 uid5 uid6
// 10 bytes 1 CT uid0 uid1 uid2
// 2 CT uid3 uid4 uid5
// 3 uid6 uid7 uid8 uid9
// Sanity checks
if (validBits > 80) {
return STATUS_INVALID;
}
// Prepare MFRC522
PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
// Repeat Cascade Level loop until we have a complete UID.
uidComplete = false;
while (!uidComplete) {
// Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2.
switch (cascadeLevel) {
case 1:
buffer[0] = PICC_CMD_SEL_CL1;
uidIndex = 0;
useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes
break;
case 2:
buffer[0] = PICC_CMD_SEL_CL2;
uidIndex = 3;
useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes
break;
case 3:
buffer[0] = PICC_CMD_SEL_CL3;
uidIndex = 6;
useCascadeTag = false; // Never used in CL3.
break;
default:
return STATUS_INTERNAL_ERROR;
break;
}
// How many UID bits are known in this Cascade Level?
currentLevelKnownBits = validBits - (8 * uidIndex);
if (currentLevelKnownBits < 0) {
currentLevelKnownBits = 0;
}
// Copy the known bits from uid->uidByte[] to buffer[]
index = 2; // destination index in buffer[]
if (useCascadeTag) {
buffer[index++] = PICC_CMD_CT;
}
byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level.
if (bytesToCopy) {
byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag
if (bytesToCopy > maxBytes) {
bytesToCopy = maxBytes;
}
for (count = 0; count < bytesToCopy; count++) {
buffer[index++] = uid->uidByte[uidIndex + count];
}
}
// Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits
if (useCascadeTag) {
currentLevelKnownBits += 8;
}
// Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations.
selectDone = false;
while (!selectDone) {
// Find out how many bits and bytes to send and receive.
if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT.
//Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes
// Calculate BCC - Block Check Character
buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5];
// Calculate CRC_A
result = PCD_CalculateCRC(buffer, 7, &buffer[7]);
if (result != STATUS_OK) {
return result;
}
txLastBits = 0; // 0 => All 8 bits are valid.
bufferUsed = 9;
// Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx)
responseBuffer = &buffer[6];
responseLength = 3;
}
else { // This is an ANTICOLLISION.
//Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
txLastBits = currentLevelKnownBits % 8;
count = currentLevelKnownBits / 8; // Number of whole bytes in the UID part.
index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs
buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits
bufferUsed = index + (txLastBits ? 1 : 0);
// Store response in the unused part of buffer
responseBuffer = &buffer[index];
responseLength = sizeof(buffer) - index;
}
// Set bit adjustments
rxAlign = txLastBits; // Having a separate variable is overkill. But it makes the next line easier to read.
PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
// Transmit the buffer and receive the response.
result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign);
if (result == STATUS_COLLISION) { // More than one PICC in the field => collision.
byte valueOfCollReg = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0]
if (valueOfCollReg & 0x20) { // CollPosNotValid
return STATUS_COLLISION; // Without a valid collision position we cannot continue
}
byte collisionPos = valueOfCollReg & 0x1F; // Values 0-31, 0 means bit 32.
if (collisionPos == 0) {
collisionPos = 32;
}
if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen
return STATUS_INTERNAL_ERROR;
}
// Choose the PICC with the bit set.
currentLevelKnownBits = collisionPos;
count = currentLevelKnownBits % 8; // The bit to modify
checkBit = (currentLevelKnownBits - 1) % 8;
index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0.
buffer[index] |= (1 << checkBit);
}
else if (result != STATUS_OK) {
return result;
}
else { // STATUS_OK
if (currentLevelKnownBits >= 32) { // This was a SELECT.
selectDone = true; // No more anticollision
// We continue below outside the while.
}
else { // This was an ANTICOLLISION.
// We now have all 32 bits of the UID in this Cascade Level
currentLevelKnownBits = 32;
// Run loop again to do the SELECT.
}
}
} // End of while (!selectDone)
// We do not check the CBB - it was constructed by us above.
// Copy the found UID bytes from buffer[] to uid->uidByte[]
index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[]
bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4;
for (count = 0; count < bytesToCopy; count++) {
uid->uidByte[uidIndex + count] = buffer[index++];
}
// Check response SAK (Select Acknowledge)
if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A).
return STATUS_ERROR;
}
// Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore.
result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]);
if (result != STATUS_OK) {
return result;
}
if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) {
return STATUS_CRC_WRONG;
}
if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes
cascadeLevel++;
}
else {
uidComplete = true;
uid->sak = responseBuffer[0];
}
} // End of while (!uidComplete)
// Set correct uid->size
uid->size = 3 * cascadeLevel + 1;
return STATUS_OK;
} // End PICC_Select()
/**
* Instructs a PICC in state ACTIVE(*) to go to state HALT.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PICC_HaltA() {
MFRC522::StatusCode result;
byte buffer[4];
// Build command buffer
buffer[0] = PICC_CMD_HLTA;
buffer[1] = 0;
// Calculate CRC_A
result = PCD_CalculateCRC(buffer, 2, &buffer[2]);
if (result != STATUS_OK) {
return result;
}
// Send the command.
// The standard says:
// If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the
// HLTA command, this response shall be interpreted as 'not acknowledge'.
// We interpret that this way: Only STATUS_TIMEOUT is a success.
result = PCD_TransceiveData(buffer, sizeof(buffer), nullptr, 0);
if (result == STATUS_TIMEOUT) {
return STATUS_OK;
}
if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-)
return STATUS_ERROR;
}
return result;
} // End PICC_HaltA()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with MIFARE PICCs
/////////////////////////////////////////////////////////////////////////////////////
/**
* Executes the MFRC522 MFAuthent command.
* This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card.
* The authentication is described in the MFRC522 datasheet section 10.3.1.9 and http://www.nxp.com/documents/data_sheet/MF1S503x.pdf section 10.1.
* For use with MIFARE Classic PICCs.
* The PICC must be selected - ie in state ACTIVE(*) - before calling this function.
* Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start.
*
* All keys are set to FFFFFFFFFFFFh at chip delivery.
*
* @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key.
*/
MFRC522::StatusCode MFRC522::PCD_Authenticate(byte command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B
byte blockAddr, ///< The block number. See numbering in the comments in the .h file.
MIFARE_Key *key, ///< Pointer to the Crypteo1 key to use (6 bytes)
Uid *uid ///< Pointer to Uid struct. The first 4 bytes of the UID is used.
) {
byte waitIRq = 0x10; // IdleIRq
// Build command buffer
byte sendData[12];
sendData[0] = command;
sendData[1] = blockAddr;
for (byte i = 0; i < MF_KEY_SIZE; i++) { // 6 key bytes
sendData[2+i] = key->keyByte[i];
}
// Use the last uid bytes as specified in http://cache.nxp.com/documents/application_note/AN10927.pdf
// section 3.2.5 "MIFARE Classic Authentication".
// The only missed case is the MF1Sxxxx shortcut activation,
// but it requires cascade tag (CT) byte, that is not part of uid.
for (byte i = 0; i < 4; i++) { // The last 4 bytes of the UID
sendData[8+i] = uid->uidByte[i+uid->size-4];
}
// Start the authentication.
return PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData));
} // End PCD_Authenticate()
/**
* Used to exit the PCD from its authenticated state.
* Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start.
*/
void MFRC522::PCD_StopCrypto1() {
// Clear MFCrypto1On bit
PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0]
} // End PCD_StopCrypto1()
/**
* Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC.
*
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
*
* For MIFARE Ultralight only addresses 00h to 0Fh are decoded.
* The MF0ICU1 returns a NAK for higher addresses.
* The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument.
* For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned.
* A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned.
*
* The buffer must be at least 18 bytes because a CRC_A is also returned.
* Checks the CRC_A before returning STATUS_OK.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Read( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from.
byte *buffer, ///< The buffer to store the data in
byte *bufferSize ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK.
) {
MFRC522::StatusCode result;
// Sanity check
if (buffer == nullptr || *bufferSize < 18) {
return STATUS_NO_ROOM;
}
// Build command buffer
buffer[0] = PICC_CMD_MF_READ;
buffer[1] = blockAddr;
// Calculate CRC_A
result = PCD_CalculateCRC(buffer, 2, &buffer[2]);
if (result != STATUS_OK) {
return result;
}
// Transmit the buffer and receive the response, validate CRC_A.
return PCD_TransceiveData(buffer, 4, buffer, bufferSize, nullptr, 0, true);
} // End MIFARE_Read()
/**
* Writes 16 bytes to the active PICC.
*
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
*
* For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE".
* Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3)
* are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0.
* *
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Write( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to.
byte *buffer, ///< The 16 bytes to write to the PICC
byte bufferSize ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written.
) {
MFRC522::StatusCode result;
// Sanity check
if (buffer == nullptr || bufferSize < 16) {
return STATUS_INVALID;
}
// Mifare Classic protocol requires two communications to perform a write.
// Step 1: Tell the PICC we want to write to block blockAddr.
byte cmdBuffer[2];
cmdBuffer[0] = PICC_CMD_MF_WRITE;
cmdBuffer[1] = blockAddr;
result = PCD_MIFARE_Transceive(cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
if (result != STATUS_OK) {
return result;
}
// Step 2: Transfer the data
result = PCD_MIFARE_Transceive(buffer, bufferSize); // Adds CRC_A and checks that the response is MF_ACK.
if (result != STATUS_OK) {
return result;
}
return STATUS_OK;
} // End MIFARE_Write()
/**
* Writes a 4 byte page to the active MIFARE Ultralight PICC.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Ultralight_Write( byte page, ///< The page (2-15) to write to.
byte *buffer, ///< The 4 bytes to write to the PICC
byte bufferSize ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written.
) {
MFRC522::StatusCode result;
// Sanity check
if (buffer == nullptr || bufferSize < 4) {
return STATUS_INVALID;
}
// Build commmand buffer
byte cmdBuffer[6];
cmdBuffer[0] = PICC_CMD_UL_WRITE;
cmdBuffer[1] = page;
memcpy(&cmdBuffer[2], buffer, 4);
// Perform the write
result = PCD_MIFARE_Transceive(cmdBuffer, 6); // Adds CRC_A and checks that the response is MF_ACK.
if (result != STATUS_OK) {
return result;
}
return STATUS_OK;
} // End MIFARE_Ultralight_Write()
/**
* MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Decrement( byte blockAddr, ///< The block (0-0xff) number.
int32_t delta ///< This number is subtracted from the value of block blockAddr.
) {
return MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta);
} // End MIFARE_Decrement()
/**
* MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Increment( byte blockAddr, ///< The block (0-0xff) number.
int32_t delta ///< This number is added to the value of block blockAddr.
) {
return MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta);
} // End MIFARE_Increment()
/**
* MIFARE Restore copies the value of the addressed block into a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Restore( byte blockAddr ///< The block (0-0xff) number.
) {
// The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2.
// Doing only a single step does not work, so I chose to transfer 0L in step two.
return MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L);
} // End MIFARE_Restore()
/**
* Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_TwoStepHelper( byte command, ///< The command to use
byte blockAddr, ///< The block (0-0xff) number.
int32_t data ///< The data to transfer in step 2
) {
MFRC522::StatusCode result;
byte cmdBuffer[2]; // We only need room for 2 bytes.
// Step 1: Tell the PICC the command and block address
cmdBuffer[0] = command;
cmdBuffer[1] = blockAddr;
result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
if (result != STATUS_OK) {
return result;
}
// Step 2: Transfer the data
result = PCD_MIFARE_Transceive( (byte *)&data, 4, true); // Adds CRC_A and accept timeout as success.
if (result != STATUS_OK) {
return result;
}
return STATUS_OK;
} // End MIFARE_TwoStepHelper()
/**
* MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_Transfer( byte blockAddr ///< The block (0-0xff) number.
) {
MFRC522::StatusCode result;
byte cmdBuffer[2]; // We only need room for 2 bytes.
// Tell the PICC we want to transfer the result into block blockAddr.
cmdBuffer[0] = PICC_CMD_MF_TRANSFER;
cmdBuffer[1] = blockAddr;
result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
if (result != STATUS_OK) {
return result;
}
return STATUS_OK;
} // End MIFARE_Transfer()
/**
* Helper routine to read the current value from a Value Block.
*
* Only for MIFARE Classic and only for blocks in "value block" mode, that
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
* the block must be authenticated before calling this function.
*
* @param[in] blockAddr The block (0x00-0xff) number.
* @param[out] value Current value of the Value Block.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_GetValue(byte blockAddr, int32_t *value) {
MFRC522::StatusCode status;
byte buffer[18];
byte size = sizeof(buffer);
// Read the block
status = MIFARE_Read(blockAddr, buffer, &size);
if (status == STATUS_OK) {
// Extract the value
*value = (int32_t(buffer[3])<<24) | (int32_t(buffer[2])<<16) | (int32_t(buffer[1])<<8) | int32_t(buffer[0]);
}
return status;
} // End MIFARE_GetValue()
/**
* Helper routine to write a specific value into a Value Block.
*
* Only for MIFARE Classic and only for blocks in "value block" mode, that
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
* the block must be authenticated before calling this function.
*
* @param[in] blockAddr The block (0x00-0xff) number.
* @param[in] value New value of the Value Block.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::MIFARE_SetValue(byte blockAddr, int32_t value) {
byte buffer[18];
// Translate the int32_t into 4 bytes; repeated 2x in value block
buffer[0] = buffer[ 8] = (value & 0xFF);
buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8;
buffer[2] = buffer[10] = (value & 0xFF0000) >> 16;
buffer[3] = buffer[11] = (value & 0xFF000000) >> 24;
// Inverse 4 bytes also found in value block
buffer[4] = ~buffer[0];
buffer[5] = ~buffer[1];
buffer[6] = ~buffer[2];
buffer[7] = ~buffer[3];
// Address 2x with inverse address 2x
buffer[12] = buffer[14] = blockAddr;
buffer[13] = buffer[15] = ~blockAddr;
// Write the whole data block
return MIFARE_Write(blockAddr, buffer, 16);
} // End MIFARE_SetValue()
/**
* Authenticate with a NTAG216.
*
* Only for NTAG216. First implemented by Gargantuanman.
*
* @param[in] passWord password.
* @param[in] pACK result success???.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PCD_NTAG216_AUTH(byte* passWord, byte pACK[]) //Authenticate with 32bit password
{
// TODO: Fix cmdBuffer length and rxlength. They really should match.
// (Better still, rxlength should not even be necessary.)
MFRC522::StatusCode result;
byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
cmdBuffer[0] = 0x1B; //Comando de autentificacion
for (byte i = 0; i<4; i++)
cmdBuffer[i+1] = passWord[i];
result = PCD_CalculateCRC(cmdBuffer, 5, &cmdBuffer[5]);
if (result!=STATUS_OK) {
return result;
}
// Transceive the data, store the reply in cmdBuffer[]
byte waitIRq = 0x30; // RxIRq and IdleIRq
// byte cmdBufferSize = sizeof(cmdBuffer);
byte validBits = 0;
byte rxlength = 5;
result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, 7, cmdBuffer, &rxlength, &validBits);
pACK[0] = cmdBuffer[0];
pACK[1] = cmdBuffer[1];
if (result!=STATUS_OK) {
return result;
}
return STATUS_OK;
} // End PCD_NTAG216_AUTH()
/////////////////////////////////////////////////////////////////////////////////////
// Support functions
/////////////////////////////////////////////////////////////////////////////////////
/**
* Wrapper for MIFARE protocol communication.
* Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522::PCD_MIFARE_Transceive( byte *sendData, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A.
byte sendLen, ///< Number of bytes in sendData.
bool acceptTimeout ///< True => A timeout is also success
) {
MFRC522::StatusCode result;
byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
// Sanity check
if (sendData == nullptr || sendLen > 16) {
return STATUS_INVALID;
}
// Copy sendData[] to cmdBuffer[] and add CRC_A
memcpy(cmdBuffer, sendData, sendLen);
result = PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]);
if (result != STATUS_OK) {
return result;
}
sendLen += 2;
// Transceive the data, store the reply in cmdBuffer[]
byte waitIRq = 0x30; // RxIRq and IdleIRq
byte cmdBufferSize = sizeof(cmdBuffer);
byte validBits = 0;
result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits);
if (acceptTimeout && result == STATUS_TIMEOUT) {
return STATUS_OK;
}
if (result != STATUS_OK) {
return result;
}
// The PICC must reply with a 4 bit ACK
if (cmdBufferSize != 1 || validBits != 4) {
return STATUS_ERROR;
}
if (cmdBuffer[0] != MF_ACK) {
return STATUS_MIFARE_NACK;
}
return STATUS_OK;
} // End PCD_MIFARE_Transceive()
/**
* Returns a __FlashStringHelper pointer to a status code name.
*
* @return const __FlashStringHelper *
*/
const __FlashStringHelper *MFRC522::GetStatusCodeName(MFRC522::StatusCode code ///< One of the StatusCode enums.
) {
switch (code) {
case STATUS_OK: return F("Success.");
case STATUS_ERROR: return F("Error in communication.");
case STATUS_COLLISION: return F("Collision detected.");
case STATUS_TIMEOUT: return F("Timeout in communication.");
case STATUS_NO_ROOM: return F("A buffer is not big enough.");
case STATUS_INTERNAL_ERROR: return F("Internal error in the code. Should not happen.");
case STATUS_INVALID: return F("Invalid argument.");
case STATUS_CRC_WRONG: return F("The CRC_A does not match.");
case STATUS_MIFARE_NACK: return F("A MIFARE PICC responded with NAK.");
default: return F("Unknown error");
}
} // End GetStatusCodeName()
/**
* Translates the SAK (Select Acknowledge) to a PICC type.
*
* @return PICC_Type
*/
MFRC522::PICC_Type MFRC522::PICC_GetType(byte sak ///< The SAK byte returned from PICC_Select().
) {
// http://www.nxp.com/documents/application_note/AN10833.pdf
// 3.2 Coding of Select Acknowledge (SAK)
// ignore 8-bit (iso14443 starts with LSBit = bit 1)
// fixes wrong type for manufacturer Infineon (http://nfc-tools.org/index.php?title=ISO14443A)
sak &= 0x7F;
switch (sak) {
case 0x04: return PICC_TYPE_NOT_COMPLETE; // UID not complete
case 0x09: return PICC_TYPE_MIFARE_MINI;
case 0x08: return PICC_TYPE_MIFARE_1K;
case 0x18: return PICC_TYPE_MIFARE_4K;
case 0x00: return PICC_TYPE_MIFARE_UL;
case 0x10:
case 0x11: return PICC_TYPE_MIFARE_PLUS;
case 0x01: return PICC_TYPE_TNP3XXX;
case 0x20: return PICC_TYPE_ISO_14443_4;
case 0x40: return PICC_TYPE_ISO_18092;
default: return PICC_TYPE_UNKNOWN;
}
} // End PICC_GetType()
/**
* Returns a __FlashStringHelper pointer to the PICC type name.
*
* @return const __FlashStringHelper *
*/
const __FlashStringHelper *MFRC522::PICC_GetTypeName(PICC_Type piccType ///< One of the PICC_Type enums.
) {
switch (piccType) {
case PICC_TYPE_ISO_14443_4: return F("PICC compliant with ISO/IEC 14443-4");
case PICC_TYPE_ISO_18092: return F("PICC compliant with ISO/IEC 18092 (NFC)");
case PICC_TYPE_MIFARE_MINI: return F("MIFARE Mini, 320 bytes");
case PICC_TYPE_MIFARE_1K: return F("MIFARE 1KB");
case PICC_TYPE_MIFARE_4K: return F("MIFARE 4KB");
case PICC_TYPE_MIFARE_UL: return F("MIFARE Ultralight or Ultralight C");
case PICC_TYPE_MIFARE_PLUS: return F("MIFARE Plus");
case PICC_TYPE_MIFARE_DESFIRE: return F("MIFARE DESFire");
case PICC_TYPE_TNP3XXX: return F("MIFARE TNP3XXX");
case PICC_TYPE_NOT_COMPLETE: return F("SAK indicates UID is not complete.");
case PICC_TYPE_UNKNOWN:
default: return F("Unknown type");
}
} // End PICC_GetTypeName()
/**
* Dumps debug info about the connected PCD to Serial.
* Shows all known firmware versions
*/
void MFRC522::PCD_DumpVersionToSerial() {
// Get the MFRC522 firmware version
byte v = PCD_ReadRegister(VersionReg);
Serial.print(F("Firmware Version: 0x"));
Serial.print(v, HEX);
// Lookup which version
switch(v) {
case 0x88: Serial.println(F(" = (clone)")); break;
case 0x90: Serial.println(F(" = v0.0")); break;
case 0x91: Serial.println(F(" = v1.0")); break;
case 0x92: Serial.println(F(" = v2.0")); break;
case 0x12: Serial.println(F(" = counterfeit chip")); break;
default: Serial.println(F(" = (unknown)"));
}
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF))
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
} // End PCD_DumpVersionToSerial()
/**
* Dumps debug info about the selected PICC to Serial.
* On success the PICC is halted after dumping the data.
* For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried.
*/
void MFRC522::PICC_DumpToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select().
) {
MIFARE_Key key;
// Dump UID, SAK and Type
PICC_DumpDetailsToSerial(uid);
// Dump contents
PICC_Type piccType = PICC_GetType(uid->sak);
switch (piccType) {
case PICC_TYPE_MIFARE_MINI:
case PICC_TYPE_MIFARE_1K:
case PICC_TYPE_MIFARE_4K:
// All keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
PICC_DumpMifareClassicToSerial(uid, piccType, &key);
break;
case PICC_TYPE_MIFARE_UL:
PICC_DumpMifareUltralightToSerial();
break;
case PICC_TYPE_ISO_14443_4:
case PICC_TYPE_MIFARE_DESFIRE:
case PICC_TYPE_ISO_18092:
case PICC_TYPE_MIFARE_PLUS:
case PICC_TYPE_TNP3XXX:
Serial.println(F("Dumping memory contents not implemented for that PICC type."));
break;
case PICC_TYPE_UNKNOWN:
case PICC_TYPE_NOT_COMPLETE:
default:
break; // No memory dump here
}
Serial.println();
PICC_HaltA(); // Already done if it was a MIFARE Classic PICC.
} // End PICC_DumpToSerial()
/**
* Dumps card info (UID,SAK,Type) about the selected PICC to Serial.
*/
void MFRC522::PICC_DumpDetailsToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select().
) {
// UID
Serial.print(F("Card UID:"));
for (byte i = 0; i < uid->size; i++) {
if(uid->uidByte[i] < 0x10)
Serial.print(F(" 0"));
else
Serial.print(F(" "));
Serial.print(uid->uidByte[i], HEX);
}
Serial.println();
// SAK
Serial.print(F("Card SAK: "));
if(uid->sak < 0x10)
Serial.print(F("0"));
Serial.println(uid->sak, HEX);
// (suggested) PICC type
PICC_Type piccType = PICC_GetType(uid->sak);
Serial.print(F("PICC type: "));
Serial.println(PICC_GetTypeName(piccType));
} // End PICC_DumpDetailsToSerial()
/**
* Dumps memory contents of a MIFARE Classic PICC.
* On success the PICC is halted after dumping the data.
*/
void MFRC522::PICC_DumpMifareClassicToSerial( Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select().
PICC_Type piccType, ///< One of the PICC_Type enums.
MIFARE_Key *key ///< Key A used for all sectors.
) {
byte no_of_sectors = 0;
switch (piccType) {
case PICC_TYPE_MIFARE_MINI:
// Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes.
no_of_sectors = 5;
break;
case PICC_TYPE_MIFARE_1K:
// Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes.
no_of_sectors = 16;
break;
case PICC_TYPE_MIFARE_4K:
// Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes.
no_of_sectors = 40;
break;
default: // Should not happen. Ignore.
break;
}
// Dump sectors, highest address first.
if (no_of_sectors) {
Serial.println(F("Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits"));
for (int8_t i = no_of_sectors - 1; i >= 0; i--) {
PICC_DumpMifareClassicSectorToSerial(uid, key, i);
}
}
PICC_HaltA(); // Halt the PICC before stopping the encrypted session.
PCD_StopCrypto1();
} // End PICC_DumpMifareClassicToSerial()
/**
* Dumps memory contents of a sector of a MIFARE Classic PICC.
* Uses PCD_Authenticate(), MIFARE_Read() and PCD_StopCrypto1.
* Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits.
*/
void MFRC522::PICC_DumpMifareClassicSectorToSerial(Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select().
MIFARE_Key *key, ///< Key A for the sector.
byte sector ///< The sector to dump, 0..39.
) {
MFRC522::StatusCode status;
byte firstBlock; // Address of lowest address to dump actually last block dumped)
byte no_of_blocks; // Number of blocks in sector
bool isSectorTrailer; // Set to true while handling the "last" (ie highest address) in the sector.
// The access bits are stored in a peculiar fashion.
// There are four groups:
// g[3] Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
// g[2] Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
// g[1] Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
// g[0] Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
// Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB.
// The four CX bits are stored together in a nible cx and an inverted nible cx_.
byte c1, c2, c3; // Nibbles
byte c1_, c2_, c3_; // Inverted nibbles
bool invertedError; // True if one of the inverted nibbles did not match
byte g[4]; // Access bits for each of the four groups.
byte group; // 0-3 - active group for access bits
bool firstInGroup; // True for the first block dumped in the group
// Determine position and size of sector.
if (sector < 32) { // Sectors 0..31 has 4 blocks each
no_of_blocks = 4;
firstBlock = sector * no_of_blocks;
}
else if (sector < 40) { // Sectors 32-39 has 16 blocks each
no_of_blocks = 16;
firstBlock = 128 + (sector - 32) * no_of_blocks;
}
else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors.
return;
}
// Dump blocks, highest address first.
byte byteCount;
byte buffer[18];
byte blockAddr;
isSectorTrailer = true;
invertedError = false; // Avoid "unused variable" warning.
for (int8_t blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) {
blockAddr = firstBlock + blockOffset;
// Sector number - only on first line
if (isSectorTrailer) {
if(sector < 10)
Serial.print(F(" ")); // Pad with spaces
else
Serial.print(F(" ")); // Pad with spaces
Serial.print(sector);
Serial.print(F(" "));
}
else {
Serial.print(F(" "));
}
// Block number
if(blockAddr < 10)
Serial.print(F(" ")); // Pad with spaces
else {
if(blockAddr < 100)
Serial.print(F(" ")); // Pad with spaces
else
Serial.print(F(" ")); // Pad with spaces
}
Serial.print(blockAddr);
Serial.print(F(" "));
// Establish encrypted communications before reading the first block
if (isSectorTrailer) {
status = PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid);
if (status != STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(GetStatusCodeName(status));
return;
}
}
// Read block
byteCount = sizeof(buffer);
status = MIFARE_Read(blockAddr, buffer, &byteCount);
if (status != STATUS_OK) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(GetStatusCodeName(status));
continue;
}
// Dump data
for (byte index = 0; index < 16; index++) {
if(buffer[index] < 0x10)
Serial.print(F(" 0"));
else
Serial.print(F(" "));
Serial.print(buffer[index], HEX);
if ((index % 4) == 3) {
Serial.print(F(" "));
}
}
// Parse sector trailer data
if (isSectorTrailer) {
c1 = buffer[7] >> 4;
c2 = buffer[8] & 0xF;
c3 = buffer[8] >> 4;
c1_ = buffer[6] & 0xF;
c2_ = buffer[6] >> 4;
c3_ = buffer[7] & 0xF;
invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF));
g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0);
g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1);
g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2);
g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3);
isSectorTrailer = false;
}
// Which access group is this block in?
if (no_of_blocks == 4) {
group = blockOffset;
firstInGroup = true;
}
else {
group = blockOffset / 5;
firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5);
}
if (firstInGroup) {
// Print access bits
Serial.print(F(" [ "));
Serial.print((g[group] >> 2) & 1, DEC); Serial.print(F(" "));
Serial.print((g[group] >> 1) & 1, DEC); Serial.print(F(" "));
Serial.print((g[group] >> 0) & 1, DEC);
Serial.print(F(" ] "));
if (invertedError) {
Serial.print(F(" Inverted access bits did not match! "));
}
}
if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block
int32_t value = (int32_t(buffer[3])<<24) | (int32_t(buffer[2])<<16) | (int32_t(buffer[1])<<8) | int32_t(buffer[0]);
Serial.print(F(" Value=0x")); Serial.print(value, HEX);
Serial.print(F(" Adr=0x")); Serial.print(buffer[12], HEX);
}
Serial.println();
}
return;
} // End PICC_DumpMifareClassicSectorToSerial()
/**
* Dumps memory contents of a MIFARE Ultralight PICC.
*/
void MFRC522::PICC_DumpMifareUltralightToSerial() {
MFRC522::StatusCode status;
byte byteCount;
byte buffer[18];
byte i;
Serial.println(F("Page 0 1 2 3"));
// Try the mpages of the original Ultralight. Ultralight C has more pages.
for (byte page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time.
// Read pages
byteCount = sizeof(buffer);
status = MIFARE_Read(page, buffer, &byteCount);
if (status != STATUS_OK) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(GetStatusCodeName(status));
break;
}
// Dump data
for (byte offset = 0; offset < 4; offset++) {
i = page + offset;
if(i < 10)
Serial.print(F(" ")); // Pad with spaces
else
Serial.print(F(" ")); // Pad with spaces
Serial.print(i);
Serial.print(F(" "));
for (byte index = 0; index < 4; index++) {
i = 4 * offset + index;
if(buffer[i] < 0x10)
Serial.print(F(" 0"));
else
Serial.print(F(" "));
Serial.print(buffer[i], HEX);
}
Serial.println();
}
}
} // End PICC_DumpMifareUltralightToSerial()
/**
* Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tuples C1 is MSB (=4) and C3 is LSB (=1).
*/
void MFRC522::MIFARE_SetAccessBits( byte *accessBitBuffer, ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set.
byte g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
byte g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
byte g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
byte g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
) {
byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2);
byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1);
byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0);
accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF);
accessBitBuffer[1] = c1 << 4 | (~c3 & 0xF);
accessBitBuffer[2] = c3 << 4 | c2;
} // End MIFARE_SetAccessBits()
/**
* Performs the "magic sequence" needed to get Chinese UID changeable
* Mifare cards to allow writing to sector 0, where the card UID is stored.
*
* Note that you do not need to have selected the card through REQA or WUPA,
* this sequence works immediately when the card is in the reader vicinity.
* This means you can use this method even on "bricked" cards that your reader does
* not recognise anymore (see MFRC522::MIFARE_UnbrickUidSector).
*
* Of course with non-bricked devices, you're free to select them before calling this function.
*/
bool MFRC522::MIFARE_OpenUidBackdoor(bool logErrors) {
// Magic sequence:
// > 50 00 57 CD (HALT + CRC)
// > 40 (7 bits only)
// < A (4 bits only)
// > 43
// < A (4 bits only)
// Then you can write to sector 0 without authenticating
PICC_HaltA(); // 50 00 57 CD
byte cmd = 0x40;
byte validBits = 7; /* Our command is only 7 bits. After receiving card response,
this will contain amount of valid response bits. */
byte response[32]; // Card's response is written here
byte received = sizeof(response);
MFRC522::StatusCode status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 40
if(status != STATUS_OK) {
if(logErrors) {
Serial.println(F("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?"));
Serial.print(F("Error name: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
if (received != 1 || response[0] != 0x0A) {
if (logErrors) {
Serial.print(F("Got bad response on backdoor 0x40 command: "));
Serial.print(response[0], HEX);
Serial.print(F(" ("));
Serial.print(validBits);
Serial.print(F(" valid bits)\r\n"));
}
return false;
}
cmd = 0x43;
validBits = 8;
status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 43
if(status != STATUS_OK) {
if(logErrors) {
Serial.println(F("Error in communication at command 0x43, after successfully executing 0x40"));
Serial.print(F("Error name: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
if (received != 1 || response[0] != 0x0A) {
if (logErrors) {
Serial.print(F("Got bad response on backdoor 0x43 command: "));
Serial.print(response[0], HEX);
Serial.print(F(" ("));
Serial.print(validBits);
Serial.print(F(" valid bits)\r\n"));
}
return false;
}
// You can now write to sector 0 without authenticating!
return true;
} // End MIFARE_OpenUidBackdoor()
/**
* Reads entire block 0, including all manufacturer data, and overwrites
* that block with the new UID, a freshly calculated BCC, and the original
* manufacturer data.
*
* It assumes a default KEY A of 0xFFFFFFFFFFFF.
* Make sure to have selected the card before this function is called.
*/
bool MFRC522::MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors) {
// UID + BCC byte can not be larger than 16 together
if (!newUid || !uidSize || uidSize > 15) {
if (logErrors) {
Serial.println(F("New UID buffer empty, size 0, or size > 15 given"));
}
return false;
}
// Authenticate for reading
MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
MFRC522::StatusCode status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid);
if (status != STATUS_OK) {
if (status == STATUS_TIMEOUT) {
// We get a read timeout if no card is selected yet, so let's select one
// Wake the card up again if sleeping
// byte atqa_answer[2];
// byte atqa_size = 2;
// PICC_WakeupA(atqa_answer, &atqa_size);
if (!PICC_IsNewCardPresent() || !PICC_ReadCardSerial()) {
Serial.println(F("No card was previously selected, and none are available. Failed to set UID."));
return false;
}
status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid);
if (status != STATUS_OK) {
// We tried, time to give up
if (logErrors) {
Serial.println(F("Failed to authenticate to card for reading, could not set UID: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
}
else {
if (logErrors) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
}
// Read block 0
byte block0_buffer[18];
byte byteCount = sizeof(block0_buffer);
status = MIFARE_Read((byte)0, block0_buffer, &byteCount);
if (status != STATUS_OK) {
if (logErrors) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(GetStatusCodeName(status));
Serial.println(F("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?"));
}
return false;
}
// Write new UID to the data we just read, and calculate BCC byte
byte bcc = 0;
for (uint8_t i = 0; i < uidSize; i++) {
block0_buffer[i] = newUid[i];
bcc ^= newUid[i];
}
// Write BCC byte to buffer
block0_buffer[uidSize] = bcc;
// Stop encrypted traffic so we can send raw bytes
PCD_StopCrypto1();
// Activate UID backdoor
if (!MIFARE_OpenUidBackdoor(logErrors)) {
if (logErrors) {
Serial.println(F("Activating the UID backdoor failed."));
}
return false;
}
// Write modified block 0 back to card
status = MIFARE_Write((byte)0, block0_buffer, (byte)16);
if (status != STATUS_OK) {
if (logErrors) {
Serial.print(F("MIFARE_Write() failed: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
// Wake the card up again
byte atqa_answer[2];
byte atqa_size = 2;
PICC_WakeupA(atqa_answer, &atqa_size);
return true;
}
/**
* Resets entire sector 0 to zeroes, so the card can be read again by readers.
*/
bool MFRC522::MIFARE_UnbrickUidSector(bool logErrors) {
MIFARE_OpenUidBackdoor(logErrors);
byte block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// Write modified block 0 back to card
MFRC522::StatusCode status = MIFARE_Write((byte)0, block0_buffer, (byte)16);
if (status != STATUS_OK) {
if (logErrors) {
Serial.print(F("MIFARE_Write() failed: "));
Serial.println(GetStatusCodeName(status));
}
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
// Convenience functions - does not add extra functionality
/////////////////////////////////////////////////////////////////////////////////////
/**
* Returns true if a PICC responds to PICC_CMD_REQA.
* Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored.
*
* @return bool
*/
bool MFRC522::PICC_IsNewCardPresent() {
byte bufferATQA[2];
byte bufferSize = sizeof(bufferATQA);
// Reset baud rates
PCD_WriteRegister(TxModeReg, 0x00);
PCD_WriteRegister(RxModeReg, 0x00);
// Reset ModWidthReg
PCD_WriteRegister(ModWidthReg, 0x26);
MFRC522::StatusCode result = PICC_RequestA(bufferATQA, &bufferSize);
return (result == STATUS_OK || result == STATUS_COLLISION);
} // End PICC_IsNewCardPresent()
/**
* Simple wrapper around PICC_Select.
* Returns true if a UID could be read.
* Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first.
* The read UID is available in the class variable uid.
*
* @return bool
*/
bool MFRC522::PICC_ReadCardSerial() {
MFRC522::StatusCode result = PICC_Select(&uid);
return (result == STATUS_OK);
} // End
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 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 <amount.h>
#include <chain.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <httpserver.h>
#include <init.h>
#include <interfaces/chain.h>
#include <validation.h>
#include <key_io.h>
#include <net.h>
#include <node/transaction.h>
#include <outputtype.h>
#include <policy/feerate.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <rpc/mining.h>
#include <rpc/rawtransaction.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/descriptor.h>
#include <script/sign.h>
#include <shutdown.h>
#include <timedata.h>
#include <util/bip32.h>
#include <util/system.h>
#include <util/moneystr.h>
#include <wallet/coincontrol.h>
#include <wallet/feebumper.h>
#include <wallet/psbtwallet.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
#include <wallet/walletutil.h>
#include <miner.h>
#include <chainparams.h>
#include <stdint.h>
#include <boost/optional.hpp>
#include <univalue.h>
#include "locktrip/dgp.h"
#include "locktrip/price-oracle.h"
#include <functional>
#include <iostream>
static const std::string WALLET_ENDPOINT_BASE = "/wallet/";
bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name)
{
if (request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) == WALLET_ENDPOINT_BASE) {
// wallet endpoint was used
wallet_name = urlDecode(request.URI.substr(WALLET_ENDPOINT_BASE.size()));
return true;
}
return false;
}
std::shared_ptr<CWallet> GetWalletForJSONRPCRequest(const JSONRPCRequest& request)
{
std::string wallet_name;
if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name);
if (!pwallet) throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
return pwallet;
}
std::vector<std::shared_ptr<CWallet>> wallets = GetWallets();
return wallets.size() == 1 || (request.fHelp && wallets.size() > 0) ? wallets[0] : nullptr;
}
bool GetSenderDest(CWallet * const pwallet, const CTransactionRef& tx, CTxDestination& txSenderDest)
{
// Initialize variables
CScript senderPubKey;
// Get sender destination
if(tx->HasOpSender())
{
// Get destination from the outputs
for(CTxOut out : tx->vout)
{
if(out.scriptPubKey.HasOpSender())
{
ExtractSenderData(out.scriptPubKey, &senderPubKey, 0);
break;
}
}
}
else
{
// Get destination from the inputs
senderPubKey = pwallet->mapWallet.at(tx->vin[0].prevout.hash).tx->vout[tx->vin[0].prevout.n].scriptPubKey;
}
// Extract destination from script
return ExtractDestination(senderPubKey, txSenderDest);
}
std::string HelpRequiringPassphrase(CWallet * const pwallet)
{
return pwallet && pwallet->IsCrypted()
? "\nRequires wallet passphrase to be set with walletpassphrase call."
: "";
}
bool EnsureWalletIsAvailable(CWallet * const pwallet, bool avoidException)
{
if (pwallet) return true;
if (avoidException) return false;
if (!HasWallets()) {
throw JSONRPCError(
RPC_METHOD_NOT_FOUND, "Method not found (wallet method is disabled because no wallet is loaded)");
}
throw JSONRPCError(RPC_WALLET_NOT_SPECIFIED,
"Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).");
}
void EnsureWalletIsUnlocked(CWallet * const pwallet)
{
if (pwallet->IsLocked()) {
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
if (pwallet->m_wallet_unlock_staking_only) {
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
}
static void WalletTxToJSON(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain, const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(locked_chain);
entry.pushKV("confirmations", confirms);
if (wtx.IsCoinBase())
entry.pushKV("generated", true);
if (confirms > 0)
{
entry.pushKV("blockhash", wtx.hashBlock.GetHex());
entry.pushKV("blockindex", wtx.nIndex);
int64_t block_time;
bool found_block = chain.findBlock(wtx.hashBlock, nullptr /* block */, &block_time);
assert(found_block);
entry.pushKV("blocktime", block_time);
} else {
entry.pushKV("trusted", wtx.IsTrusted(locked_chain));
}
uint256 hash = wtx.GetHash();
entry.pushKV("txid", hash.GetHex());
UniValue conflicts(UniValue::VARR);
for (const uint256& conflict : wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.pushKV("walletconflicts", conflicts);
entry.pushKV("time", wtx.GetTxTime());
entry.pushKV("timereceived", (int64_t)wtx.nTimeReceived);
// Add opt-in RBF status
std::string rbfStatus = "no";
if (confirms <= 0) {
LOCK(mempool.cs);
RBFTransactionState rbfState = IsRBFOptIn(*wtx.tx, mempool);
if (rbfState == RBFTransactionState::UNKNOWN)
rbfStatus = "unknown";
else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125)
rbfStatus = "yes";
}
entry.pushKV("bip125-replaceable", rbfStatus);
for (const std::pair<const std::string, std::string>& item : wtx.mapValue)
entry.pushKV(item.first, item.second);
}
static std::string LabelFromValue(const UniValue& value)
{
std::string label = value.get_str();
if (label == "*")
throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, "Invalid label name");
return label;
}
bool SetDefaultPayForContractAddress(CWallet* const pwallet, interfaces::Chain::Lock& locked_chain, CCoinControl & coinControl)
{
// Set default coin to pay for the contract
// Select any valid unspent output that can be used to pay for the contract
std::vector<COutput> vecOutputs;
coinControl.fAllowOtherInputs=true;
assert(pwallet != NULL);
pwallet->AvailableCoins(locked_chain, vecOutputs, false, NULL, true);
for (const COutput& out : vecOutputs) {
CTxDestination destAdress;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, destAdress)
&& IsValidContractSenderAddress(destAdress);
if (!fValidAddress)
continue;
coinControl.Select(COutPoint(out.tx->GetHash(),out.i));
break;
}
return coinControl.HasSelected();
}
bool SetDefaultSignSenderAddress(CWallet* const pwallet, interfaces::Chain::Lock& locked_chain, CTxDestination& destAdress)
{
// Set default sender address if none provided
// Select any valid unspent output that can be used for contract sender address
std::vector<COutput> vecOutputs;
assert(pwallet != NULL);
pwallet->AvailableCoins(locked_chain, vecOutputs, false, NULL, true);
for (const COutput& out : vecOutputs) {
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, destAdress)
&& IsValidContractSenderAddress(destAdress);
if (!fValidAddress)
continue;
break;
}
return !boost::get<CNoDestination>(&destAdress);
}
static UniValue getnewaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"getnewaddress",
"\nReturns a new HYDRA address for receiving payments.\n"
"If 'label' is specified, it is added to the address book \n"
"so payments received with the address will be associated with 'label'.\n",
{
{"label", RPCArg::Type::STR, /* default */ "\"\"", "The label name for the address to be linked to. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created if there is no label by the given name."},
{"address_type", RPCArg::Type::STR, /* default */ "set by -addresstype", "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
},
RPCResult{
"\"address\" (string) The new HYDRA address\n"
},
RPCExamples{
HelpExampleCli("getnewaddress", "")
+ HelpExampleRpc("getnewaddress", "")
},
}.ToString());
LOCK(pwallet->cs_wallet);
if (!pwallet->CanGetAddresses()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
}
// Parse the label first so we don't generate a key if there's an error
std::string label;
if (!request.params[0].isNull())
label = LabelFromValue(request.params[0]);
OutputType output_type = pwallet->m_default_address_type;
if (!request.params[1].isNull()) {
if (!ParseOutputType(request.params[1].get_str(), output_type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[1].get_str()));
}
}
if (!pwallet->IsLocked()) {
pwallet->TopUpKeyPool();
}
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwallet->GetKeyFromPool(newKey)) {
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
}
pwallet->LearnRelatedScripts(newKey, output_type);
CTxDestination dest = GetDestinationForKey(newKey, output_type);
pwallet->SetAddressBook(dest, label, "receive");
return EncodeDestination(dest);
}
static UniValue getrawchangeaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"getrawchangeaddress",
"\nReturns a new HYDRA address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n",
{
{"address_type", RPCArg::Type::STR, /* default */ "set by -changetype", "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
},
RPCResult{
"\"address\" (string) The address\n"
},
RPCExamples{
HelpExampleCli("getrawchangeaddress", "")
+ HelpExampleRpc("getrawchangeaddress", "")
},
}.ToString());
LOCK(pwallet->cs_wallet);
if (!pwallet->CanGetAddresses(true)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
}
if (!pwallet->IsLocked()) {
pwallet->TopUpKeyPool();
}
OutputType output_type = pwallet->m_default_change_type != OutputType::CHANGE_AUTO ? pwallet->m_default_change_type : pwallet->m_default_address_type;
if (!request.params[0].isNull()) {
if (!ParseOutputType(request.params[0].get_str(), output_type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
}
}
CReserveKey reservekey(pwallet);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey, true))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
pwallet->LearnRelatedScripts(vchPubKey, output_type);
CTxDestination dest = GetDestinationForKey(vchPubKey, output_type);
return EncodeDestination(dest);
}
static UniValue setlabel(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
RPCHelpMan{"setlabel",
"\nSets the label associated with the given address.\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address to be associated with a label."},
{"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label to assign to the address."},
},
RPCResults{},
RPCExamples{
HelpExampleCli("setlabel", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" \"tabby\"")
+ HelpExampleRpc("setlabel", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", \"tabby\"")
},
}.ToString());
LOCK(pwallet->cs_wallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address");
}
std::string label = LabelFromValue(request.params[1]);
if (IsMine(*pwallet, dest)) {
pwallet->SetAddressBook(dest, label, "receive");
} else {
pwallet->SetAddressBook(dest, label, "send");
}
return NullUniValue;
}
static CTransactionRef SendMoney(interfaces::Chain::Lock& locked_chain, CWallet * const pwallet, const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, const CCoinControl& coin_control, mapValue_t mapValue, std::string fromAccount, bool hasSender)
{
CAmount curBalance = pwallet->GetBalance();
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
if (pwallet->GetBroadcastTransactions() && !g_connman) {
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
}
if (pwallet->m_wallet_unlock_staking_only)
{
std::string strError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse Bitcoin address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwallet);
CAmount nFeeRequired;
std::string strError;
std::vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
CTransactionRef tx;
if (!pwallet->CreateTransaction(locked_chain, vecSend, tx, reservekey, nFeeRequired, nChangePosRet, strError, coin_control, true, 0, hasSender)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance)
strError = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CValidationState state;
if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, reservekey, g_connman.get(), state)) {
strError = strprintf("Error: The transaction was rejected! Reason given: %s", FormatStateMessage(state));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
return tx;
}
static UniValue sendtoaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 10)
throw std::runtime_error(
RPCHelpMan{"sendtoaddress",
"\nSend an amount to a given address." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address to send to."},
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
{"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment used to store what the transaction is for.\n"
" This is not part of the transaction, just kept in your wallet."},
{"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment to store the name of the person or organization\n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet."},
{"subtractfeefromamount", RPCArg::Type::BOOL, /* default */ "false", "The fee will be deducted from the amount being sent.\n"
" The recipient will receive less HYDRA than you enter in the amount field."},
{"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default", "Allow this transaction to be replaced by a transaction with higher fees via BIP 125"},
{"conf_target", RPCArg::Type::NUM, /* default */ "fallback to wallet's default", "Confirmation target (in blocks)"},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
{"senderaddress", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "The HYDRA address that will be used to send money from."},
{"changeToSender", RPCArg::Type::BOOL, /* default */ "false", "Return the change to the sender."},
},
RPCResult{
"\"txid\" (string) The transaction id.\n"
},
RPCExamples{
HelpExampleCli("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 0.1")
+ HelpExampleCli("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 0.1 \"\" \"\" true")
+ HelpExampleCli("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", 0.1, \"donation\", \"seans outpost\", false, null, null, \"\", \"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", true")
+ HelpExampleRpc("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", 0.1, \"donation\", \"seans outpost\""
+ HelpExampleRpc("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", 0.1, \"donation\", \"seans outpost\", false, null, null, \"\", \"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", true"))
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address");
}
// Amount
CAmount nAmount = AmountFromValue(request.params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
mapValue_t mapValue;
if (!request.params[2].isNull() && !request.params[2].get_str().empty())
mapValue["comment"] = request.params[2].get_str();
if (!request.params[3].isNull() && !request.params[3].get_str().empty())
mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (!request.params[4].isNull()) {
fSubtractFeeFromAmount = request.params[4].get_bool();
}
CCoinControl coin_control;
if (!request.params[5].isNull()) {
coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
}
if (!request.params[6].isNull()) {
coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
}
if (request.params.size() > 7 && !request.params[7].isNull()) {
std::string estimate_mode = request.params[7].get_str();
if (!estimate_mode.empty() && !FeeModeFromString(estimate_mode, coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
}
bool fHasSender=false;
CTxDestination senderAddress;
if (request.params.size() > 8 && !request.params[8].isNull()){
senderAddress = DecodeDestination(request.params[8].get_str());
if (!IsValidDestination(senderAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address to send from");
else
fHasSender=true;
}
bool fChangeToSender=false;
if (request.params.size() > 9 && !request.params[9].isNull()){
fChangeToSender=request.params[9].get_bool();
}
if(fHasSender){
//find a UTXO with sender address
UniValue results(UniValue::VARR);
std::vector<COutput> vecOutputs;
coin_control.fAllowOtherInputs=true;
assert(pwallet != NULL);
pwallet->AvailableCoins(*locked_chain, vecOutputs, false, NULL, true);
for(const COutput& out : vecOutputs) {
CTxDestination destAdress;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, destAdress);
if (!fValidAddress || senderAddress != destAdress)
continue;
coin_control.Select(COutPoint(out.tx->GetHash(),out.i));
break;
}
if(!coin_control.HasSelected()){
throw JSONRPCError(RPC_TYPE_ERROR, "Sender address does not have any unspent outputs");
}
if(fChangeToSender){
coin_control.destChange=senderAddress;
}
}
EnsureWalletIsUnlocked(pwallet);
CTransactionRef tx = SendMoney(*locked_chain, pwallet, dest, nAmount, fSubtractFeeFromAmount, coin_control, std::move(mapValue), {} /* fromAccount */, fHasSender);
return tx->GetHash().GetHex();
}
static UniValue createcontract(const JSONRPCRequest& request){
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
QtumDGP qtumDGP(globalState.get(), fGettingValuesDGP);
uint64_t blockGasLimit = qtumDGP.getBlockGasLimit(chainActive.Height());
uint64_t minGasPrice = CAmount(qtumDGP.getMinGasPrice(chainActive.Height()));
PriceOracle oracle;
uint64_t oracleGasPrice;
oracle.getPrice(oracleGasPrice);
CAmount defaultGasPrice = (minGasPrice>DEFAULT_GAS_PRICE)?minGasPrice:oracleGasPrice;
Dgp dgp;
CAmount gasPriceBuffer;
dgp.calculateGasPriceBuffer(defaultGasPrice, gasPriceBuffer);
CAmount nGasPrice = gasPriceBuffer + defaultGasPrice;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 6)
throw std::runtime_error(
RPCHelpMan{"createcontract",
"\nCreate a contract with bytcode." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"bytecode", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "contract bytcode."},
{"gasLimit", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "gasLimit, default: "+i64tostr(DEFAULT_GAS_LIMIT_OP_CREATE)+", max: "+i64tostr(blockGasLimit)},
{"senderaddress", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The HYDRA address that will be used to create the contract."},
{"broadcast", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Whether to broadcast the transaction or not."},
{"changeToSender", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Return the change to the sender."},
},
RPCResult{
"[\n"
" {\n"
" \"txid\" : (string) The transaction id.\n"
" \"sender\" : (string) " + CURRENCY_UNIT + " address of the sender.\n"
" \"hash160\" : (string) ripemd-160 hash of the sender.\n"
" \"address\" : (string) expected contract address.\n"
" }\n"
"]\n"
},
RPCExamples{
HelpExampleCli("createcontract", "\"60606040525b33600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055506103786001600050819055505b600c80605b6000396000f360606040526008565b600256\"")
+ HelpExampleCli("createcontract", "\"60606040525b33600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055506103786001600050819055505b600c80605b6000396000f360606040526008565b600256\" 6000000 \"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" true")
},
}.ToString()
);
std::string bytecode=request.params[0].get_str();
if(bytecode.size() % 2 != 0 || !CheckHex(bytecode))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid data (data not hex)");
uint64_t nGasLimit=DEFAULT_GAS_LIMIT_OP_CREATE;
if (request.params.size() > 1){
nGasLimit = request.params[1].get_int64();
if (nGasLimit > blockGasLimit)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Maximum is: "+i64tostr(blockGasLimit)+")");
if (nGasLimit < MINIMUM_GAS_LIMIT)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Minimum is: "+i64tostr(MINIMUM_GAS_LIMIT)+")");
if (nGasLimit <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit");
}
bool fHasSender=false;
CTxDestination senderAddress;
if (request.params.size() > 2){
senderAddress = DecodeDestination(request.params[2].get_str());
if (!IsValidDestination(senderAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address to send from");
if (!IsValidContractSenderAddress(senderAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid contract sender address. Only P2PK and P2PKH allowed");
else
fHasSender=true;
}
bool fBroadcast=true;
if (request.params.size() > 3){
fBroadcast=request.params[3].get_bool();
}
bool fChangeToSender=true;
if (request.params.size() > 4){
fChangeToSender=request.params[4].get_bool();
}
CCoinControl coinControl;
CTxDestination signSenderAddress = CNoDestination();
if(fHasSender){
//find a UTXO with sender address
std::vector<COutput> vecOutputs;
coinControl.fAllowOtherInputs=true;
assert(pwallet != NULL);
pwallet->AvailableCoins(*locked_chain, vecOutputs, false, NULL, true);
for (const COutput& out : vecOutputs) {
CTxDestination destAdress;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, destAdress);
if (!fValidAddress || senderAddress != destAdress)
continue;
coinControl.Select(COutPoint(out.tx->GetHash(),out.i));
break;
}
if(coinControl.HasSelected()){
// Change to the sender
if(fChangeToSender){
coinControl.destChange=senderAddress;
}
}
else
{
// Create op sender transaction when op sender is activated
if(!(chainActive.Height() >= Params().GetConsensus().QIP5Height))
throw JSONRPCError(RPC_TYPE_ERROR, "Sender address does not have any unspent outputs");
}
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
// Set the sender address
signSenderAddress = senderAddress;
}
}
else
{
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
// If no sender provided set to the default
SetDefaultSignSenderAddress(pwallet, *locked_chain, signSenderAddress);
}
}
EnsureWalletIsUnlocked(pwallet);
CAmount nGasFee=nGasPrice*nGasLimit;
CAmount curBalance = pwallet->GetBalance();
// Check amount
if (nGasFee <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nGasFee > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
// Select default coin that will pay for the contract if none selected
if(!coinControl.HasSelected() && !SetDefaultPayForContractAddress(pwallet, *locked_chain, coinControl))
throw JSONRPCError(RPC_TYPE_ERROR, "Does not have any P2PK or P2PKH unspent outputs to pay for the contract.");
// Build OP_EXEC script
CScript scriptPubKey = CScript() << CScriptNum(VersionVM::GetEVMDefault().toRaw()) << CScriptNum(nGasLimit) << ParseHex(bytecode) << OP_CREATE;
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
if(IsValidDestination(signSenderAddress))
{
CKeyID key_id = GetKeyForDestination(*pwallet, signSenderAddress);
CKey key;
if (!pwallet->GetKey(key_id, key)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
}
std::vector<unsigned char> scriptSig;
scriptPubKey = (CScript() << CScriptNum(addresstype::PUBKEYHASH) << ToByteVector(key_id) << ToByteVector(scriptSig) << OP_SENDER) + scriptPubKey;
}
else
{
// OP_SENDER will always be used when QIP5Height is active
throw JSONRPCError(RPC_TYPE_ERROR, "Sender address fail to set for OP_SENDER.");
}
}
// Create and send the transaction
CReserveKey reservekey(pwallet);
CAmount nFeeRequired;
std::string strError;
std::vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, 0, false};
vecSend.push_back(recipient);
CTransactionRef tx;
if (!pwallet->CreateTransaction(*locked_chain, vecSend, tx, reservekey, nFeeRequired, nChangePosRet, strError, coinControl, true, nGasFee, true, signSenderAddress)) {
if (nFeeRequired > pwallet->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CTxDestination txSenderDest;
GetSenderDest(pwallet, tx, txSenderDest);
if (fHasSender && !(senderAddress == txSenderDest)){
throw JSONRPCError(RPC_TYPE_ERROR, "Sender could not be set, transaction was not committed!");
}
UniValue result(UniValue::VOBJ);
if(fBroadcast){
CValidationState state;
if (!pwallet->CommitTransaction(tx, {}, {}, reservekey, g_connman.get(), state))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of the wallet and coins were spent in the copy but not marked as spent here.");
std::string txId=tx->GetHash().GetHex();
result.pushKV("txid", txId);
CTxDestination txSenderAdress(txSenderDest);
CKeyID keyid = GetKeyForDestination(*pwallet, txSenderAdress);
result.pushKV("sender", EncodeDestination(txSenderAdress));
result.pushKV("hash160", HexStr(valtype(keyid.begin(),keyid.end())));
std::vector<unsigned char> SHA256TxVout(32);
std::vector<unsigned char> contractAddress(20);
std::vector<unsigned char> txIdAndVout(tx->GetHash().begin(), tx->GetHash().end());
uint32_t voutNumber=0;
for (const CTxOut& txout : tx->vout) {
if(txout.scriptPubKey.HasOpCreate()){
std::vector<unsigned char> voutNumberChrs;
if (voutNumberChrs.size() < sizeof(voutNumber))voutNumberChrs.resize(sizeof(voutNumber));
std::memcpy(voutNumberChrs.data(), &voutNumber, sizeof(voutNumber));
txIdAndVout.insert(txIdAndVout.end(),voutNumberChrs.begin(),voutNumberChrs.end());
break;
}
voutNumber++;
}
CSHA256().Write(txIdAndVout.data(), txIdAndVout.size()).Finalize(SHA256TxVout.data());
CRIPEMD160().Write(SHA256TxVout.data(), SHA256TxVout.size()).Finalize(contractAddress.data());
result.pushKV("address", HexStr(contractAddress));
}else{
std::string strHex = EncodeHexTx(*tx, RPCSerializationFlags());
result.pushKV("raw transaction", strHex);
}
return result;
}
static UniValue sendtocontract(const JSONRPCRequest& request){
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
QtumDGP qtumDGP(globalState.get(), fGettingValuesDGP);
uint64_t blockGasLimit = qtumDGP.getBlockGasLimit(chainActive.Height());
uint64_t minGasPrice = CAmount(qtumDGP.getMinGasPrice(chainActive.Height()));
PriceOracle oracle;
uint64_t oracleGasPrice;
oracle.getPrice(oracleGasPrice);
CAmount defaultGasPrice = (minGasPrice>DEFAULT_GAS_PRICE)?minGasPrice:oracleGasPrice;
Dgp dgp;
CAmount gasPriceBuffer;
dgp.calculateGasPriceBuffer(defaultGasPrice, gasPriceBuffer);
CAmount nGasPrice = gasPriceBuffer + defaultGasPrice;
if (request.fHelp || request.params.size() < 2 || request.params.size() > 8)
throw std::runtime_error(
RPCHelpMan{"sendtocontract",
"\nSend funds and data to a contract." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"contractaddress", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The contract address that will receive the funds and data."},
{"datahex", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "data to send."},
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1, default: 0"},
{"gasLimit", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "gasLimit, default: "+i64tostr(DEFAULT_GAS_LIMIT_OP_SEND)+", max: "+i64tostr(blockGasLimit)},
{"senderaddress", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The HYDRA address that will be used as sender."},
{"broadcast", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Whether to broadcast the transaction or not."},
{"changeToSender", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Return the change to the sender."},
},
RPCResult{
"[\n"
" {\n"
" \"txid\" : (string) The transaction id.\n"
" \"sender\" : (string) " + CURRENCY_UNIT + " address of the sender.\n"
" \"hash160\" : (string) ripemd-160 hash of the sender.\n"
" }\n"
"]\n"
},
RPCExamples{
HelpExampleCli("sendtocontract", "\"c6ca2697719d00446d4ea51f6fac8fd1e9310214\" \"54f6127f\"")
+ HelpExampleCli("sendtocontract", "\"c6ca2697719d00446d4ea51f6fac8fd1e9310214\" \"54f6127f\" 12.0015 6000000 \"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\"")
},
}.ToString()
);
std::string contractaddress = request.params[0].get_str();
if(contractaddress.size() != 40 || !CheckHex(contractaddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect contract address");
dev::Address addrAccount(contractaddress);
if(!globalState->addressInUse(addrAccount))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "contract address does not exist");
std::string datahex = request.params[1].get_str();
if(datahex.size() % 2 != 0 || !CheckHex(datahex))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid data (data not hex)");
CAmount nAmount = 0;
if (request.params.size() > 2){
nAmount = AmountFromValue(request.params[2]);
if (nAmount < 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
}
uint64_t nGasLimit=DEFAULT_GAS_LIMIT_OP_SEND;
if (request.params.size() > 3){
nGasLimit = request.params[3].get_int64();
if (nGasLimit > blockGasLimit)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Maximum is: "+i64tostr(blockGasLimit)+")");
if (nGasLimit < MINIMUM_GAS_LIMIT)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Minimum is: "+i64tostr(MINIMUM_GAS_LIMIT)+")");
if (nGasLimit <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit");
}
bool fHasSender=false;
CTxDestination senderAddress;
if (request.params.size() > 4){
senderAddress = DecodeDestination(request.params[4].get_str());
if (!IsValidDestination(senderAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address to send from");
if (!IsValidContractSenderAddress(senderAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid contract sender address. Only P2PK and P2PKH allowed");
else
fHasSender=true;
}
bool fBroadcast=true;
if (request.params.size() > 5){
fBroadcast=request.params[5].get_bool();
}
bool fChangeToSender=true;
if (request.params.size() > 6){
fChangeToSender=request.params[6].get_bool();
}
CCoinControl coinControl;
CTxDestination signSenderAddress = CNoDestination();
if(fHasSender){
// Find a UTXO with sender address
std::vector<COutput> vecOutputs;
coinControl.fAllowOtherInputs=true;
assert(pwallet != NULL);
pwallet->AvailableCoins(*locked_chain, vecOutputs, false, NULL, true);
for (const COutput& out : vecOutputs) {
CTxDestination destAdress;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, destAdress);
if (!fValidAddress || senderAddress != destAdress)
continue;
coinControl.Select(COutPoint(out.tx->GetHash(),out.i));
break;
}
if(coinControl.HasSelected())
{
// Change to the sender
if(fChangeToSender){
coinControl.destChange=senderAddress;
}
}
else
{
// Create op sender transaction when op sender is activated
if(!(chainActive.Height() >= Params().GetConsensus().QIP5Height))
throw JSONRPCError(RPC_TYPE_ERROR, "Sender address does not have any unspent outputs");
}
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
// Set the sender address
signSenderAddress = senderAddress;
}
}
else
{
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
// If no sender address provided set to the default sender address
SetDefaultSignSenderAddress(pwallet, *locked_chain, signSenderAddress);
}
}
EnsureWalletIsUnlocked(pwallet);
CAmount nGasFee=nGasPrice*nGasLimit;
CAmount curBalance = pwallet->GetBalance();
// Check amount
if (nGasFee <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount for gas fee");
if (nAmount+nGasFee > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
// Select default coin that will pay for the contract if none selected
if(!coinControl.HasSelected() && !SetDefaultPayForContractAddress(pwallet, *locked_chain, coinControl))
throw JSONRPCError(RPC_TYPE_ERROR, "Does not have any P2PK or P2PKH unspent outputs to pay for the contract.");
// Build OP_EXEC_ASSIGN script
CScript scriptPubKey = CScript() << CScriptNum(VersionVM::GetEVMDefault().toRaw()) << CScriptNum(nGasLimit) << ParseHex(datahex) << ParseHex(contractaddress) << OP_CALL;
if(chainActive.Height() >= Params().GetConsensus().QIP5Height)
{
if(IsValidDestination(signSenderAddress))
{
CKeyID key_id = GetKeyForDestination(*pwallet, signSenderAddress);
CKey key;
if (!pwallet->GetKey(key_id, key)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
}
std::vector<unsigned char> scriptSig;
scriptPubKey = (CScript() << CScriptNum(addresstype::PUBKEYHASH) << ToByteVector(key_id) << ToByteVector(scriptSig) << OP_SENDER) + scriptPubKey;
}
else
{
// OP_SENDER will always be used when QIP5Height is active
throw JSONRPCError(RPC_TYPE_ERROR, "Sender address fail to set for OP_SENDER.");
}
}
// Create and send the transaction
CReserveKey reservekey(pwallet);
CAmount nFeeRequired;
std::string strError;
std::vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nAmount, false};
vecSend.push_back(recipient);
CTransactionRef tx;
if (!pwallet->CreateTransaction(*locked_chain, vecSend, tx, reservekey, nFeeRequired, nChangePosRet, strError, coinControl, true, nGasFee, true, signSenderAddress)) {
if (nFeeRequired > pwallet->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CTxDestination txSenderDest;
GetSenderDest(pwallet, tx, txSenderDest);
if (fHasSender && !(senderAddress == txSenderDest)){
throw JSONRPCError(RPC_TYPE_ERROR, "Sender could not be set, transaction was not committed!");
}
UniValue result(UniValue::VOBJ);
if(fBroadcast){
CValidationState state;
if (!pwallet->CommitTransaction(tx, {}, {}, reservekey, g_connman.get(), state))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of the wallet and coins were spent in the copy but not marked as spent here.");
std::string txId=tx->GetHash().GetHex();
result.pushKV("txid", txId);
CTxDestination txSenderAdress(txSenderDest);
CKeyID keyid = GetKeyForDestination(*pwallet, txSenderAdress);
result.pushKV("sender", EncodeDestination(txSenderAdress));
result.pushKV("hash160", HexStr(valtype(keyid.begin(),keyid.end())));
}else{
std::string strHex = EncodeHexTx(*tx, RPCSerializationFlags());
result.pushKV("raw transaction", strHex);
}
return result;
}
static UniValue listaddressgroupings(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"listaddressgroupings",
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n",
{},
RPCResult{
"[\n"
" [\n"
" [\n"
" \"address\", (string) The HYDRA address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" (string, optional) The label\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("listaddressgroupings", "")
+ HelpExampleRpc("listaddressgroupings", "")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances(*locked_chain);
for (const std::set<CTxDestination>& grouping : pwallet->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR);
for (const CTxDestination& address : grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(EncodeDestination(address));
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwallet->mapAddressBook.find(address) != pwallet->mapAddressBook.end()) {
addressInfo.push_back(pwallet->mapAddressBook.find(address)->second.name);
}
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
static UniValue signmessage(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
RPCHelpMan{"signmessage",
"\nSign a message with the private key of an address" +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address to use for the private key."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."},
},
RPCResult{
"\"signature\" (string) The signature of the message encoded in base 64\n"
},
RPCExamples{
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("signmessage", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", \"my message\"")
},
}.ToString());
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strAddress = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CTxDestination dest = DecodeDestination(strAddress);
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
}
const CKeyID *keyID = boost::get<CKeyID>(&dest);
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
CKey key;
if (!pwallet->GetKey(*keyID, key)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(vchSig.data(), vchSig.size());
}
static UniValue getbalanceofaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"getbalanceofaddress",
"\nReturns the balance of an address",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address that will be used."},
},
RPCResult{
"[\n"
" [\n"
" [\n"
" \"address\", (string) The HYDRA address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" (string, optional) The label\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("getbalanceofaddress", "HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC")
+ HelpExampleRpc("getbalanceofaddress", "HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
std::string strAddress = request.params[0].get_str();
std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances(*locked_chain);
return ValueFromAmount(balances[DecodeDestination(strAddress)]);
}
static UniValue getreceivedbyaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"getreceivedbyaddress",
"\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address for transactions."},
{"minconf", RPCArg::Type::NUM, /* default */ "1", "Only include transactions confirmed at least this many times."},
},
RPCResult{
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
},
RPCExamples{
"\nThe amount from transactions with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n"
+ HelpExampleCli("getreceivedbyaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 0") +
"\nThe amount with at least 6 confirmations, very safe\n"
+ HelpExampleCli("getreceivedbyaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 6") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("getreceivedbyaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\", 6")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
LockAnnotation lock(::cs_main); // Temporary, for CheckFinalTx below. Removed in upcoming commit.
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Bitcoin address
CTxDestination dest = DecodeDestination(request.params[0].get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HYDRA address");
}
CScript scriptPubKey = GetScriptForDestination(dest);
if (!IsMine(*pwallet, scriptPubKey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet");
}
// Minimum confirmations
int nMinDepth = 1;
if (!request.params[1].isNull())
nMinDepth = request.params[1].get_int();
// Tally
CAmount nAmount = 0;
for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
const CWalletTx& wtx = pairWtx.second;
if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
continue;
for (const CTxOut& txout : wtx.tx->vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain(*locked_chain) >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
static UniValue getreceivedbylabel(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"getreceivedbylabel",
"\nReturns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.\n",
{
{"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The selected label, may be the default label using \"\"."},
{"minconf", RPCArg::Type::NUM, /* default */ "1", "Only include transactions confirmed at least this many times."},
},
RPCResult{
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this label.\n"
},
RPCExamples{
"\nAmount received by the default label with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbylabel", "\"\"") +
"\nAmount received at the tabby label including unconfirmed amounts with zero confirmations\n"
+ HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmations\n"
+ HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
LockAnnotation lock(::cs_main); // Temporary, for CheckFinalTx below. Removed in upcoming commit.
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (!request.params[1].isNull())
nMinDepth = request.params[1].get_int();
// Get the set of pub keys assigned to label
std::string label = LabelFromValue(request.params[0]);
std::set<CTxDestination> setAddress = pwallet->GetLabelAddresses(label);
// Tally
CAmount nAmount = 0;
for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
const CWalletTx& wtx = pairWtx.second;
if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
continue;
for (const CTxOut& txout : wtx.tx->vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwallet, address) && setAddress.count(address)) {
if (wtx.GetDepthInMainChain(*locked_chain) >= nMinDepth)
nAmount += txout.nValue;
}
}
}
return ValueFromAmount(nAmount);
}
static UniValue getbalance(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || (request.params.size() > 3 ))
throw std::runtime_error(
RPCHelpMan{"getbalance",
"\nReturns the total available balance.\n"
"The available balance is what the wallet considers currently spendable, and is\n"
"thus affected by options which limit spendability such as -spendzeroconfchange.\n",
{
{"dummy", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Remains for backward compatibility. Must be excluded or set to \"*\"."},
{"minconf", RPCArg::Type::NUM, /* default */ "0", "Only include transactions confirmed at least this many times."},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Also include balance in watch-only addresses (see 'importaddress')"},
},
RPCResult{
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this wallet.\n"
},
RPCExamples{
"\nThe total amount in the wallet with 1 or more confirmations\n"
+ HelpExampleCli("getbalance", "") +
"\nThe total amount in the wallet at least 6 blocks confirmed\n"
+ HelpExampleCli("getbalance", "\"*\" 6") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("getbalance", "\"*\", 6")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
const UniValue& dummy_value = request.params[0];
if (!dummy_value.isNull() && dummy_value.get_str() != "*") {
throw JSONRPCError(RPC_METHOD_DEPRECATED, "dummy first argument must be excluded or set to \"*\".");
}
int min_depth = 0;
if (!request.params[1].isNull()) {
min_depth = request.params[1].get_int();
}
isminefilter filter = ISMINE_SPENDABLE;
if (!request.params[2].isNull() && request.params[2].get_bool()) {
filter = filter | ISMINE_WATCH_ONLY;
}
return ValueFromAmount(pwallet->GetBalance(filter, min_depth));
}
static UniValue getunconfirmedbalance(const JSONRPCRequest &request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 0)
throw std::runtime_error(
RPCHelpMan{"getunconfirmedbalance",
"Returns the server's total unconfirmed balance\n",
{},
RPCResults{},
RPCExamples{""},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
return ValueFromAmount(pwallet->GetUnconfirmedBalance());
}
static UniValue sendmany(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 8) {
throw std::runtime_error(
RPCHelpMan{"sendmany",
"\nSend multiple times. Amounts are double-precision floating point numbers." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"dummy", RPCArg::Type::STR, RPCArg::Optional::NO,
"Must be set to \"\" for backwards compatibility.", "\"\""},
{"amounts", RPCArg::Type::OBJ, RPCArg::Optional::NO,
"A json object with addresses and amounts",
{
{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO,
"The HYDRA address is the key, the numeric amount (can be string) in " +
CURRENCY_UNIT + " is the value"},
},
},
{"minconf", RPCArg::Type::NUM, /* default */ "1",
"Only use the balance confirmed at least this many times."},
{"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment"},
{"subtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG,
"A json array with addresses.\n"
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less HYDRA than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED,
"Subtract fee from this address"},
},
},
{"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default",
"Allow this transaction to be replaced by a transaction with higher fees via BIP 125"},
{"conf_target", RPCArg::Type::NUM, /* default */ "fallback to wallet's default",
"Confirmation target (in blocks)"},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET",
"The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
},
RPCResult{
"\"txid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
},
RPCExamples{
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmany",
"\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmany",
"\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
"\nSend two amounts to two different addresses, subtract fee from amount:\n"
+ HelpExampleCli("sendmany",
"\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"HD1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\",\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("sendmany",
"\"\", {\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\":0.01,\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}, 6, \"testing\"")
}
}.ToString());
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (pwallet->GetBroadcastTransactions() && !g_connman) {
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
}
if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"\"");
}
UniValue sendTo = request.params[1].get_obj();
int nMinDepth = 1;
if (!request.params[2].isNull())
nMinDepth = request.params[2].get_int();
mapValue_t mapValue;
if (!request.params[3].isNull() && !request.params[3].get_str().empty())
mapValue["comment"] = request.params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (!request.params[4].isNull())
subtractFeeFromAmount = request.params[4].get_array();
CCoinControl coin_control;
if (!request.params[5].isNull()) {
coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
}
if (!request.params[6].isNull()) {
coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
}
if (!request.params[7].isNull()) {
if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
}
std::set<CTxDestination> destinations;
std::vector<CRecipient> vecSend;
CAmount totalAmount = 0;
std::vector<std::string> keys = sendTo.getKeys();
for (const std::string& name_ : keys) {
CTxDestination dest = DecodeDestination(name_);
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid HYDRA address: ") + name_);
}
if (destinations.count(dest)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
}
destinations.insert(dest);
CScript scriptPubKey = GetScriptForDestination(dest);
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked(pwallet);
// Check funds
if (totalAmount > pwallet->GetLegacyBalance(ISMINE_SPENDABLE, nMinDepth)) {
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Wallet has insufficient funds");
}
// Shuffle recipient list
std::shuffle(vecSend.begin(), vecSend.end(), FastRandomContext());
// Send
CReserveKey keyChange(pwallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
CTransactionRef tx;
bool fCreated = pwallet->CreateTransaction(*locked_chain, vecSend, tx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
CValidationState state;
if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, keyChange, g_connman.get(), state)) {
strFailReason = strprintf("Transaction commit failed:: %s", FormatStateMessage(state));
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
return tx->GetHash().GetHex();
}
static UniValue sendmanywithdupes(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 5)
throw std::runtime_error(
RPCHelpMan{"sendmanywithdupes",
"\nSend multiple times. Amounts are double-precision floating point numbers. Supports duplicate addresses" +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"fromaccount", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "DEPRECATED. The account to send the funds from. Should be \"\" for the default account"},
{"amounts", RPCArg::Type::OBJ, RPCArg::Optional::NO, "A json object with addresses and amounts",
{
{"address", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The HYDRA address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value"},
},
},
{"minconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Only use the balance confirmed at least this many times."},
{"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment"},
{"ubtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "A json array with addresses."
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less HYDRA than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.\n",
{
{"address", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "Subtract fee from this address"},
},
},
},
RPCResult{
"\"txid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
},
RPCExamples{
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmanywithdupes", "\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmanywithdupes", "\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
"\nSend two amounts to two different addresses, subtract fee from amount:\n"
+ HelpExampleCli("sendmanywithdupes", "\"\" \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"HD1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\",\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendmanywithdupes", "\"\", \"{\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\":0.01,\\\"H353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\", 6, \"testing\"")
},
}.ToString()
);
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (pwallet->GetBroadcastTransactions() && !g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
std::string strAccount = LabelFromValue(request.params[0]);
UniValue sendTo = request.params[1].get_obj();
int nMinDepth = 1;
if (request.params.size() > 2)
nMinDepth = request.params[2].get_int();
mapValue_t mapValue;
if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty())
mapValue["comment"] = request.params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (request.params.size() > 4)
subtractFeeFromAmount = request.params[4].get_array();
std::set<CTxDestination> setAddress;
std::vector<CRecipient> vecSend;
CAmount totalAmount = 0;
std::vector<std::string> keys = sendTo.getKeys();
for (const std::string& name_ : keys)
{
CTxDestination address = DecodeDestination(name_);
if (!IsValidDestination(address))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid HYDRA address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address);
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked(pwallet);
// Check funds
CAmount nBalance = pwallet->GetLegacyBalance(ISMINE_SPENDABLE, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CTransactionRef tx;
CReserveKey keyChange(pwallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
CCoinControl coin_control;
bool fCreated = pwallet->CreateTransaction(*locked_chain, vecSend, tx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
CValidationState state;
if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, keyChange, g_connman.get(), state)) {
strFailReason = strprintf("Transaction commit failed:: %s", state.GetRejectReason());
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
return tx->GetHash().GetHex();
}
static UniValue addmultisigaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
std::string msg =
RPCHelpMan{"addmultisigaddress",
"\nAdd a nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
"Each key is a HYDRA address or hex-encoded public key.\n"
"This functionality is only intended for use with non-watchonly addresses.\n"
"See `importaddress` for watchonly p2sh address support.\n"
"If 'label' is specified, assign address to that label.\n",
{
{"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys or addresses."},
{"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "A json array of HYDRA addresses or hex-encoded public keys",
{
{"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "HYDRA address or hex-encoded public key"},
},
},
{"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A label to assign the addresses to."},
{"address_type", RPCArg::Type::STR, /* default */ "set by -addresstype", "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
},
RPCResult{
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
},
RPCExamples{
"\nAdd a multisig address from 2 addresses\n"
+ HelpExampleCli("addmultisigaddress", "2 \"[\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\",\\\"H6sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\"]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\",\\\"H6sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\"]\"")
},
}.ToString();
throw std::runtime_error(msg);
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
std::string label;
if (!request.params[2].isNull())
label = LabelFromValue(request.params[2]);
int required = request.params[0].get_int();
// Get the public keys
const UniValue& keys_or_addrs = request.params[1].get_array();
std::vector<CPubKey> pubkeys;
for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) {
if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
} else {
pubkeys.push_back(AddrToPubKey(pwallet, keys_or_addrs[i].get_str()));
}
}
OutputType output_type = pwallet->m_default_address_type;
if (!request.params[3].isNull()) {
if (!ParseOutputType(request.params[3].get_str(), output_type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str()));
}
}
// Construct using pay-to-script-hash:
CScript inner;
CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, *pwallet, inner);
pwallet->SetAddressBook(dest, label, "send");
UniValue result(UniValue::VOBJ);
result.pushKV("address", EncodeDestination(dest));
result.pushKV("redeemScript", HexStr(inner.begin(), inner.end()));
return result;
}
struct tallyitem
{
CAmount nAmount{0};
int nConf{std::numeric_limits<int>::max()};
std::vector<uint256> txids;
bool fIsWatchonly{false};
tallyitem()
{
}
};
static UniValue ListReceived(interfaces::Chain::Lock& locked_chain, CWallet * const pwallet, const UniValue& params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
{
LockAnnotation lock(::cs_main); // Temporary, for CheckFinalTx below. Removed in upcoming commit.
// Minimum confirmations
int nMinDepth = 1;
if (!params[0].isNull())
nMinDepth = params[0].get_int();
// Whether to include empty labels
bool fIncludeEmpty = false;
if (!params[1].isNull())
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if(!params[2].isNull())
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
bool has_filtered_address = false;
CTxDestination filtered_address = CNoDestination();
if (!by_label && params.size() > 3) {
if (!IsValidDestinationString(params[3].get_str())) {
throw JSONRPCError(RPC_WALLET_ERROR, "address_filter parameter was invalid");
}
filtered_address = DecodeDestination(params[3].get_str());
has_filtered_address = true;
}
// Tally
std::map<CTxDestination, tallyitem> mapTally;
for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
const CWalletTx& wtx = pairWtx.second;
if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
continue;
int nDepth = wtx.GetDepthInMainChain(locked_chain);
if (nDepth < nMinDepth)
continue;
for (const CTxOut& txout : wtx.tx->vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
if (has_filtered_address && !(filtered_address == address)) {
continue;
}
isminefilter mine = IsMine(*pwallet, address);
if(!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = std::min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
std::map<std::string, tallyitem> label_tally;
// Create mapAddressBook iterator
// If we aren't filtering, go from begin() to end()
auto start = pwallet->mapAddressBook.begin();
auto end = pwallet->mapAddressBook.end();
// If we are filtering, find() the applicable entry
if (has_filtered_address) {
start = pwallet->mapAddressBook.find(filtered_address);
if (start != end) {
end = std::next(start);
}
}
for (auto item_it = start; item_it != end; ++item_it)
{
const CTxDestination& address = item_it->first;
const std::string& label = item_it->second.name;
auto it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (by_label)
{
tallyitem& _item = label_tally[label];
_item.nAmount += nAmount;
_item.nConf = std::min(_item.nConf, nConf);
_item.fIsWatchonly = fIsWatchonly;
}
else
{
UniValue obj(UniValue::VOBJ);
if(fIsWatchonly)
obj.pushKV("involvesWatchonly", true);
obj.pushKV("address", EncodeDestination(address));
obj.pushKV("amount", ValueFromAmount(nAmount));
obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
obj.pushKV("label", label);
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
for (const uint256& _item : (*it).second.txids)
{
transactions.push_back(_item.GetHex());
}
}
obj.pushKV("txids", transactions);
ret.push_back(obj);
}
}
if (by_label)
{
for (const auto& entry : label_tally)
{
CAmount nAmount = entry.second.nAmount;
int nConf = entry.second.nConf;
UniValue obj(UniValue::VOBJ);
if (entry.second.fIsWatchonly)
obj.pushKV("involvesWatchonly", true);
obj.pushKV("amount", ValueFromAmount(nAmount));
obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
obj.pushKV("label", entry.first);
ret.push_back(obj);
}
}
return ret;
}
static UniValue listreceivedbyaddress(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 4)
throw std::runtime_error(
RPCHelpMan{"listreceivedbyaddress",
"\nList balances by receiving address.\n",
{
{"minconf", RPCArg::Type::NUM, /* default */ "1", "The minimum number of confirmations before payments are included."},
{"include_empty", RPCArg::Type::BOOL, /* default */ "false", "Whether to include addresses that haven't received any payments."},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Whether to include watch-only addresses (see 'importaddress')."},
{"address_filter", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "If present, only return information on this address."},
},
RPCResult{
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"label\" : \"label\", (string) The label of the receiving address. The default label is \"\".\n"
" \"txids\": [\n"
" \"txid\", (string) The ids of transactions received with the address \n"
" ...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("listreceivedbyaddress", "")
+ HelpExampleCli("listreceivedbyaddress", "6 true")
+ HelpExampleRpc("listreceivedbyaddress", "6, true, true")
+ HelpExampleRpc("listreceivedbyaddress", "6, true, true, \"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\"")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
return ListReceived(*locked_chain, pwallet, request.params, false);
}
static UniValue listreceivedbylabel(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 3)
throw std::runtime_error(
RPCHelpMan{"listreceivedbylabel",
"\nList received transactions by label.\n",
{
{"minconf", RPCArg::Type::NUM, /* default */ "1", "The minimum number of confirmations before payments are included."},
{"include_empty", RPCArg::Type::BOOL, /* default */ "false", "Whether to include labels that haven't received any payments."},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Whether to include watch-only addresses (see 'importaddress')."},
},
RPCResult{
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this label\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) The label of the receiving address. The default label is \"\".\n"
" }\n"
" ,...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("listreceivedbylabel", "")
+ HelpExampleCli("listreceivedbylabel", "6 true")
+ HelpExampleRpc("listreceivedbylabel", "6, true, true")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
return ListReceived(*locked_chain, pwallet, request.params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
if (IsValidDestination(dest)) {
entry.pushKV("address", EncodeDestination(dest));
}
}
/**
* List transactions based on the given criteria.
*
* @param pwallet The wallet.
* @param wtx The wallet transaction.
* @param nMinDepth The minimum confirmation depth.
* @param fLong Whether to include the JSON version of the transaction.
* @param ret The UniValue into which the result is stored.
* @param filter_ismine The "is mine" filter flags.
* @param filter_label Optional label string to filter incoming transactions.
*/
static void ListTransactions(interfaces::Chain::Lock& locked_chain, CWallet* const pwallet, const CWalletTx& wtx, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter_ismine, const std::string* filter_label) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
{
CAmount nFee;
std::list<COutputEntry> listReceived;
std::list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, filter_ismine);
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if (!filter_label)
{
for (const COutputEntry& s : listSent)
{
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwallet, s.destination) & ISMINE_WATCH_ONLY)) {
entry.pushKV("involvesWatchonly", true);
}
MaybePushAddress(entry, s.destination);
entry.pushKV("category", "send");
entry.pushKV("amount", ValueFromAmount(-s.amount));
if (pwallet->mapAddressBook.count(s.destination)) {
entry.pushKV("label", pwallet->mapAddressBook[s.destination].name);
}
entry.pushKV("vout", s.vout);
entry.pushKV("fee", ValueFromAmount(-nFee));
if (fLong)
WalletTxToJSON(pwallet->chain(), locked_chain, wtx, entry);
entry.pushKV("abandoned", wtx.isAbandoned());
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain(locked_chain) >= nMinDepth)
{
for (const COutputEntry& r : listReceived)
{
std::string label;
if (pwallet->mapAddressBook.count(r.destination)) {
label = pwallet->mapAddressBook[r.destination].name;
}
if (filter_label && label != *filter_label) {
continue;
}
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwallet, r.destination) & ISMINE_WATCH_ONLY)) {
entry.pushKV("involvesWatchonly", true);
}
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain(locked_chain) < 1)
entry.pushKV("category", "orphan");
else if (wtx.IsImmature(locked_chain))
entry.pushKV("category", "immature");
else
entry.pushKV("category", "generate");
}
else
{
entry.pushKV("category", "receive");
}
entry.pushKV("amount", ValueFromAmount(r.amount));
if (pwallet->mapAddressBook.count(r.destination)) {
entry.pushKV("label", label);
}
entry.pushKV("vout", r.vout);
if (fLong)
WalletTxToJSON(pwallet->chain(), locked_chain, wtx, entry);
ret.push_back(entry);
}
}
}
UniValue listtransactions(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 4)
throw std::runtime_error(
RPCHelpMan{"listtransactions",
"\nIf a label name is provided, this will return only incoming transactions paying to addresses with the specified label.\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions.\n",
{
{"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "If set, should be a valid label name to return only incoming transactions\n"
" with the specified label, or \"*\" to disable filtering and return all transactions."},
{"count", RPCArg::Type::NUM, /* default */ "10", "The number of transactions to return"},
{"skip", RPCArg::Type::NUM, /* default */ "0", "The number of transactions to skip"},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Include transactions to watch-only addresses (see 'importaddress')"},
},
RPCResult{
"[\n"
" {\n"
" \"address\":\"address\", (string) The HYDRA address of the transaction.\n"
" \"category\": (string) The transaction category.\n"
" \"send\" Transactions sent.\n"
" \"receive\" Non-coinbase transactions received.\n"
" \"generate\" Coinbase transactions received with more than 100 confirmations.\n"
" \"immature\" Coinbase transactions received with 100 or fewer confirmations.\n"
" \"orphan\" Orphaned coinbase transactions received.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
" for all other categories\n"
" \"label\": \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\": n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Negative confirmations indicate the\n"
" transaction conflicts with the block chain\n"
" \"trusted\": xxx, (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
" 'send' category of transactions.\n"
" }\n"
"]\n"
},
RPCExamples{
"\nList the most recent 10 transactions in the systems\n"
+ HelpExampleCli("listtransactions", "") +
"\nList transactions 100 to 120\n"
+ HelpExampleCli("listtransactions", "\"*\" 20 100") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
const std::string* filter_label = nullptr;
if (!request.params[0].isNull() && request.params[0].get_str() != "*") {
filter_label = &request.params[0].get_str();
if (filter_label->empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Label argument must be a valid label name or \"*\".");
}
}
int nCount = 10;
if (!request.params[1].isNull())
nCount = request.params[1].get_int();
int nFrom = 0;
if (!request.params[2].isNull())
nFrom = request.params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(!request.params[3].isNull())
if(request.params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
const CWallet::TxItems & txOrdered = pwallet->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second;
ListTransactions(*locked_chain, pwallet, *pwtx, 0, true, ret, filter, filter_label);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
std::vector<UniValue> arrTmp = ret.getValues();
std::vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
std::vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
static UniValue listsinceblock(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 4)
throw std::runtime_error(
RPCHelpMan{"listsinceblock",
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted.\n"
"If \"blockhash\" is no longer a part of the main chain, transactions from the fork point onward are included.\n"
"Additionally, if include_removed is set, transactions affecting the wallet which were removed are returned in the \"removed\" array.\n",
{
{"blockhash", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "If set, the block hash to list transactions since, otherwise list all transactions."},
{"target_confirmations", RPCArg::Type::NUM, /* default */ "1", "Return the nth block hash from the main chain. e.g. 1 would mean the best block hash. Note: this is not used as a filter, but only affects [lastblock] in the return value"},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Include transactions to watch-only addresses (see 'importaddress')"},
{"include_removed", RPCArg::Type::BOOL, /* default */ "true", "Show transactions that were removed due to a reorg in the \"removed\" array\n"
" (not guaranteed to work on pruned nodes)"},
},
RPCResult{
"{\n"
" \"transactions\": [\n"
" \"address\":\"address\", (string) The HYDRA address of the transaction.\n"
" \"category\": (string) The transaction category.\n"
" \"send\" Transactions sent.\n"
" \"receive\" Non-coinbase transactions received.\n"
" \"generate\" Coinbase transactions received with more than 100 confirmations.\n"
" \"immature\" Coinbase transactions received with 100 or fewer confirmations.\n"
" \"orphan\" Orphaned coinbase transactions received.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
" for all other categories\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction.\n"
" When it's < 0, it means the transaction conflicted that many blocks ago.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT).\n"
" \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"abandoned\": xxx, (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the 'send' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"removed\": [\n"
" <structure is the same as \"transactions\" above, only present if include_removed=true>\n"
" Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the block (target_confirmations-1) from the best block on the main chain. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones\n"
"}\n"
},
RPCExamples{
HelpExampleCli("listsinceblock", "")
+ HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// The way the 'height' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
Optional<int> height = MakeOptional(false, int()); // Height of the specified block or the common ancestor, if the block provided was in a deactivated chain.
Optional<int> altheight; // Height of the specified block, even if it's in a deactivated chain.
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
uint256 blockId;
if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
blockId = ParseHashV(request.params[0], "blockhash");
height = locked_chain->findFork(blockId, &altheight);
if (!height) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
}
if (!request.params[1].isNull()) {
target_confirms = request.params[1].get_int();
if (target_confirms < 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
}
if (!request.params[2].isNull() && request.params[2].get_bool()) {
filter = filter | ISMINE_WATCH_ONLY;
}
bool include_removed = (request.params[3].isNull() || request.params[3].get_bool());
const Optional<int> tip_height = locked_chain->getHeight();
int depth = tip_height && height ? (1 + *tip_height - *height) : -1;
UniValue transactions(UniValue::VARR);
for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
CWalletTx tx = pairWtx.second;
if (depth == -1 || tx.GetDepthInMainChain(*locked_chain) < depth) {
ListTransactions(*locked_chain, pwallet, tx, 0, true, transactions, filter, nullptr /* filter_label */);
}
}
// when a reorg'd block is requested, we also list any relevant transactions
// in the blocks of the chain that was detached
UniValue removed(UniValue::VARR);
while (include_removed && altheight && *altheight > *height) {
CBlock block;
if (!pwallet->chain().findBlock(blockId, &block) || block.IsNull()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
}
for (const CTransactionRef& tx : block.vtx) {
auto it = pwallet->mapWallet.find(tx->GetHash());
if (it != pwallet->mapWallet.end()) {
// We want all transactions regardless of confirmation count to appear here,
// even negative confirmation ones, hence the big negative.
ListTransactions(*locked_chain, pwallet, it->second, -100000000, true, removed, filter, nullptr /* filter_label */);
}
}
blockId = block.hashPrevBlock;
--*altheight;
}
int last_height = tip_height ? *tip_height + 1 - target_confirms : -1;
uint256 lastblock = last_height >= 0 ? locked_chain->getBlockHash(last_height) : uint256();
UniValue ret(UniValue::VOBJ);
ret.pushKV("transactions", transactions);
if (include_removed) ret.pushKV("removed", removed);
ret.pushKV("lastblock", lastblock.GetHex());
return ret;
}
static UniValue gettransaction(const JSONRPCRequest& request_)
{
// long-poll
JSONRPCRequest& request = (JSONRPCRequest&) request_;
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
RPCHelpMan{"gettransaction",
"\nGet detailed information about in-wallet transaction <txid>\n",
{
{"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
{"include_watchonly", RPCArg::Type::BOOL, /* default */ "false", "Whether to include watch-only addresses in balance calculation and details[]"},
{"waitconf", RPCArg::Type::NUM, /* default */ "0", "Wait for enough confirmations before returning."},
},
RPCResult{
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"details\" : [\n"
" {\n"
" \"address\" : \"address\", (string) The HYDRA address involved in the transaction\n"
" \"category\" : (string) The transaction category.\n"
" \"send\" Transactions sent.\n"
" \"receive\" Non-coinbase transactions received.\n"
" \"generate\" Coinbase transactions received with more than 100 confirmations.\n"
" \"immature\" Coinbase transactions received with 100 or fewer confirmations.\n"
" \"orphan\" Orphaned coinbase transactions received.\n"
" \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
" 'send' category of transactions.\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
},
RPCExamples{
HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
uint256 hash(ParseHashV(request.params[0], "txid"));
isminefilter filter = ISMINE_SPENDABLE;
if(!request.params[1].isNull())
if(request.params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int waitconf = 0;
if(request.params.size() > 2) {
waitconf = request.params[2].get_int();
}
bool shouldWaitConf = request.params.size() > 2 && waitconf > 0;
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (!pwallet->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
}
CWalletTx* _wtx = nullptr;
// avoid long-poll if API caller does not specify waitconf
if (!shouldWaitConf) {
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
_wtx = &pwallet->mapWallet.at(hash);
}
} else {
request.PollStart();
while (true) {
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
_wtx = &pwallet->mapWallet.at(hash);
if (_wtx->GetDepthInMainChain(*locked_chain) >= waitconf) {
break;
}
}
request.PollPing();
std::unique_lock<std::mutex> lock(cs_blockchange);
cond_blockchange.wait_for(lock, std::chrono::milliseconds(300));
if (!request.PollAlive() || !IsRPCRunning()) {
return NullUniValue;
}
}
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
CWalletTx& wtx = *_wtx;
UniValue entry(UniValue::VOBJ);
CAmount nCredit = wtx.GetCredit(*locked_chain, filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.tx->GetValueOut() - nDebit : 0);
entry.pushKV("amount", ValueFromAmount(nNet - nFee));
if (wtx.IsFromMe(filter))
entry.pushKV("fee", ValueFromAmount(nFee));
WalletTxToJSON(pwallet->chain(), *locked_chain, wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(*locked_chain, pwallet, wtx, 0, false, details, filter, nullptr /* filter_label */);
entry.pushKV("details", details);
std::string strHex = EncodeHexTx(*wtx.tx, RPCSerializationFlags());
entry.pushKV("hex", strHex);
return entry;
}
static UniValue abandontransaction(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
RPCHelpMan{"abandontransaction",
"\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
"for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
"It only works on transactions which are not included in a block and are not currently in the mempool.\n"
"It has no effect on transactions which are already abandoned.\n",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
},
}.ToString());
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
uint256 hash(ParseHashV(request.params[0], "txid"));
if (!pwallet->mapWallet.count(hash)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
}
if (!pwallet->AbandonTransaction(*locked_chain, hash)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
}
return NullUniValue;
}
static UniValue backupwallet(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"backupwallet",
"\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n",
{
{"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("backupwallet", "\"backup.dat\"")
+ HelpExampleRpc("backupwallet", "\"backup.dat\"")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
std::string strDest = request.params[0].get_str();
if (!pwallet->BackupWallet(strDest)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
}
return NullUniValue;
}
static UniValue keypoolrefill(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"keypoolrefill",
"\nFills the keypool."+
HelpRequiringPassphrase(pwallet) + "\n",
{
{"newsize", RPCArg::Type::NUM, /* default */ "100", "The new keypool size"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("keypoolrefill", "")
+ HelpExampleRpc("keypoolrefill", "")
},
}.ToString());
if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (!request.params[0].isNull()) {
if (request.params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)request.params[0].get_int();
}
EnsureWalletIsUnlocked(pwallet);
pwallet->TopUpKeyPool(kpSize);
if (pwallet->GetKeyPoolSize() < kpSize) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
}
return NullUniValue;
}
static UniValue walletpassphrase(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || (pwallet->IsCrypted() && (request.params.size() < 2 || request.params.size() > 3))) {
throw std::runtime_error(
RPCHelpMan{"walletpassphrase",
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending HYDRA and staking\n"
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one.\n",
{
{"passphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet passphrase"},
{"timeout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The time to keep the decryption key in seconds; capped at 100000000 (~3 years)."},
{"staking only", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Unlock wallet for staking only"},
},
RPCResults{},
RPCExamples{
"\nUnlock the wallet for 60 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nLock the wallet again (before 60 seconds)\n"
+ HelpExampleCli("walletlock", "") +
"\nUnlock the wallet for staking only, for a long time\n"
+ HelpExampleCli("walletpassphrase","\"my pass phrase\" 99999999 true") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
},
}.ToString());
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (request.fHelp)
return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
}
// Note that the walletpassphrase is stored in request.params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make request.params[0] mlock()'d to begin with.
strWalletPass = request.params[0].get_str().c_str();
// Get the timeout
int64_t nSleepTime = request.params[1].get_int64();
// Timeout cannot be negative, otherwise it will relock immediately
if (nSleepTime < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative.");
}
// Clamp timeout
constexpr int64_t MAX_SLEEP_TIME = 100000000; // larger values trigger a macos/libevent bug?
if (nSleepTime > MAX_SLEEP_TIME) {
nSleepTime = MAX_SLEEP_TIME;
}
if (strWalletPass.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase can not be empty");
}
// Used to restore m_wallet_unlock_staking_only value in case of unlock failure
bool tmpStakingOnly = pwallet->m_wallet_unlock_staking_only;
// ppcoin: if user OS account compromised prevent trivial sendmoney commands
if (request.params.size() > 2)
pwallet->m_wallet_unlock_staking_only = request.params[2].get_bool();
else
pwallet->m_wallet_unlock_staking_only = false;
if (!pwallet->Unlock(strWalletPass)) {
pwallet->m_wallet_unlock_staking_only = tmpStakingOnly;
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
pwallet->TopUpKeyPool();
pwallet->nRelockTime = GetTime() + nSleepTime;
// Keep a weak pointer to the wallet so that it is possible to unload the
// wallet before the following callback is called. If a valid shared pointer
// is acquired in the callback then the wallet is still loaded.
std::weak_ptr<CWallet> weak_wallet = wallet;
RPCRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), [weak_wallet] {
if (auto shared_wallet = weak_wallet.lock()) {
LOCK(shared_wallet->cs_wallet);
shared_wallet->Lock();
shared_wallet->nRelockTime = 0;
}
}, nSleepTime);
return NullUniValue;
}
static UniValue walletpassphrasechange(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || (pwallet->IsCrypted() && (request.params.size() != 2))) {
throw std::runtime_error(
RPCHelpMan{"walletpassphrasechange",
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n",
{
{"oldpassphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The current passphrase"},
{"newpassphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The new passphrase"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
+ HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
},
}.ToString());
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (request.fHelp)
return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
}
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make request.params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = request.params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = request.params[1].get_str().c_str();
if (strOldWalletPass.empty() || strNewWalletPass.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase can not be empty");
}
if (!pwallet->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) {
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
return NullUniValue;
}
static UniValue walletlock(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || (pwallet->IsCrypted() && (request.params.size() != 0))) {
throw std::runtime_error(
RPCHelpMan{"walletlock",
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n",
{},
RPCResults{},
RPCExamples{
"\nSet the passphrase for 2 minutes to perform a transaction\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n"
+ HelpExampleCli("sendtoaddress", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("walletlock", "")
},
}.ToString());
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (request.fHelp)
return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
}
pwallet->Lock();
pwallet->nRelockTime = 0;
return NullUniValue;
}
static UniValue encryptwallet(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || (!pwallet->IsCrypted() && (request.params.size() != 1))) {
throw std::runtime_error(
RPCHelpMan{"encryptwallet",
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n",
{
{"passphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long."},
},
RPCResults{},
RPCExamples{
"\nEncrypt your wallet\n"
+ HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending HYDRA\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can do something like sign\n"
+ HelpExampleCli("signmessage", "\"address\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
},
}.ToString());
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (request.fHelp)
return true;
if (pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
}
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make request.params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = request.params[0].get_str().c_str();
if (strWalletPass.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase can not be empty");
}
if (!pwallet->EncryptWallet(strWalletPass)) {
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
}
return "wallet encrypted; The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup.";
}
static UniValue reservebalance(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"reservebalance",
"\nSet reserve amount not participating in network protection."
"\nIf no parameters provided current setting is printed.\n",
{
{"reserve", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,"is true or false to turn balance reserve on or off."},
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "is a real and rounded to cent."},
},
RPCResults{},
RPCExamples{
"\nSet reserve balance to 100\n"
+ HelpExampleCli("reservebalance", "true 100") +
"\nSet reserve balance to 0\n"
+ HelpExampleCli("reservebalance", "false") +
"\nGet reserve balance\n"
+ HelpExampleCli("reservebalance", "") },
}.ToString()
);
if (request.params.size() > 0)
{
bool fReserve = request.params[0].get_bool();
if (fReserve)
{
if (request.params.size() == 1)
throw std::runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(request.params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw std::runtime_error("amount cannot be negative.\n");
pwallet->m_reserve_balance = nAmount;
}
else
{
if (request.params.size() > 1)
throw std::runtime_error("cannot specify amount to turn off reserve.\n");
pwallet->m_reserve_balance = 0;
}
}
UniValue result(UniValue::VOBJ);
result.pushKV("reserve", (pwallet->m_reserve_balance > 0));
result.pushKV("amount", ValueFromAmount(pwallet->m_reserve_balance));
return result;
}
static UniValue lockunspent(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"lockunspent",
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending HYDRA.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n",
{
{"unlock", RPCArg::Type::BOOL, RPCArg::Optional::NO, "Whether to unlock (true) or lock (false) the specified transactions"},
{"transactions", RPCArg::Type::ARR, /* default */ "empty array", "A json array of objects. Each object the txid (string) vout (numeric).",
{
{"", 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"},
},
},
},
},
},
RPCResult{
"true|false (boolean) Whether the command was successful or not\n"
},
RPCExamples{
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
RPCTypeCheckArgument(request.params[0], UniValue::VBOOL);
bool fUnlock = request.params[0].get_bool();
if (request.params[1].isNull()) {
if (fUnlock)
pwallet->UnlockAllCoins();
return true;
}
RPCTypeCheckArgument(request.params[1], UniValue::VARR);
const UniValue& output_params = request.params[1];
// Create and validate the COutPoints first.
std::vector<COutPoint> outputs;
outputs.reserve(output_params.size());
for (unsigned int idx = 0; idx < output_params.size(); idx++) {
const UniValue& o = output_params[idx].get_obj();
RPCTypeCheckObj(o,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
});
const uint256 txid(ParseHashO(o, "txid"));
const int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
}
const COutPoint outpt(txid, nOutput);
const auto it = pwallet->mapWallet.find(outpt.hash);
if (it == pwallet->mapWallet.end()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, unknown transaction");
}
const CWalletTx& trans = it->second;
if (outpt.n >= trans.tx->vout.size()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout index out of bounds");
}
if (pwallet->IsSpent(*locked_chain, outpt.hash, outpt.n)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected unspent output");
}
const bool is_locked = pwallet->IsLockedCoin(outpt.hash, outpt.n);
if (fUnlock && !is_locked) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected locked output");
}
if (!fUnlock && is_locked) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output already locked");
}
outputs.push_back(outpt);
}
// Atomically set (un)locked status for the outputs.
for (const COutPoint& outpt : outputs) {
if (fUnlock) pwallet->UnlockCoin(outpt);
else pwallet->LockCoin(outpt);
}
return true;
}
static UniValue listlockunspent(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 0)
throw std::runtime_error(
RPCHelpMan{"listlockunspent",
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n",
{},
RPCResult{
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
},
RPCExamples{
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("listlockunspent", "")
},
}.ToString());
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
std::vector<COutPoint> vOutpts;
pwallet->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
for (const COutPoint& outpt : vOutpts) {
UniValue o(UniValue::VOBJ);
o.pushKV("txid", outpt.hash.GetHex());
o.pushKV("vout", (int)outpt.n);
ret.push_back(o);
}
return ret;
}
static UniValue settxfee(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) {
throw std::runtime_error(
RPCHelpMan{"settxfee",
"\nSet the transaction fee per kB for this wallet. Overrides the global -paytxfee command line parameter.\n",
{
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The transaction fee in " + CURRENCY_UNIT + "/kB"},
},
RPCResult{
"true|false (boolean) Returns true if successful\n"
},
RPCExamples{
HelpExampleCli("settxfee", "0.00001")
+ HelpExampleRpc("settxfee", "0.00001")
},
}.ToString());
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
CAmount nAmount = AmountFromValue(request.params[0]);
CFeeRate tx_fee_rate(nAmount, 1000);
if (tx_fee_rate == 0) {
// automatic selection
} else if (tx_fee_rate < ::minRelayTxFee) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than min relay tx fee (%s)", ::minRelayTxFee.ToString()));
} else if (tx_fee_rate < pwallet->m_min_fee) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than wallet min fee (%s)", pwallet->m_min_fee.ToString()));
}
pwallet->m_pay_tx_fee = tx_fee_rate;
return true;
}
static UniValue getwalletinfo(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getwalletinfo",
"Returns an object containing various wallet state info.\n",
{},
RPCResult{
"{\n"
" \"walletname\": xxxxx, (string) the wallet name\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"stake\": xxxxxxx, (numeric) the total stake balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n"
" \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
" \"hdseedid\": \"<hash160>\" (string, optional) the Hash160 of the HD seed (only present when HD is enabled)\n"
" \"private_keys_enabled\": true|false (boolean) false if privatekeys are disabled for this wallet (enforced watch-only wallet)\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getwalletinfo", "")
+ HelpExampleRpc("getwalletinfo", "")
},
}.ToString());
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
UniValue obj(UniValue::VOBJ);
size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
obj.pushKV("walletname", pwallet->GetName());
obj.pushKV("walletversion", pwallet->GetVersion());
obj.pushKV("balance", ValueFromAmount(pwallet->GetBalance()));
obj.pushKV("stake", ValueFromAmount(pwallet->GetStake()));
obj.pushKV("unconfirmed_balance", ValueFromAmount(pwallet->GetUnconfirmedBalance()));
obj.pushKV("immature_balance", ValueFromAmount(pwallet->GetImmatureBalance()));
obj.pushKV("txcount", (int)pwallet->mapWallet.size());
obj.pushKV("keypoololdest", pwallet->GetOldestKeyPoolTime());
obj.pushKV("keypoolsize", (int64_t)kpExternalSize);
CKeyID seed_id = pwallet->GetHDChain().seed_id;
if (pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) {
obj.pushKV("keypoolsize_hd_internal", (int64_t)(pwallet->GetKeyPoolSize() - kpExternalSize));
}
if (pwallet->IsCrypted()) {
obj.pushKV("unlocked_until", pwallet->nRelockTime);
}
obj.pushKV("paytxfee", ValueFromAmount(pwallet->m_pay_tx_fee.GetFeePerK()));
if (!seed_id.IsNull()) {
obj.pushKV("hdseedid", seed_id.GetHex());
}
obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
return obj;
}
static UniValue listwalletdir(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
RPCHelpMan{"listwalletdir",
"Returns a list of wallets in the wallet directory.\n",
{},
RPCResult{
"{\n"
" \"wallets\" : [ (json array of objects)\n"
" {\n"
" \"name\" : \"name\" (string) The wallet name\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
},
RPCExamples{
HelpExampleCli("listwalletdir", "")
+ HelpExampleRpc("listwalletdir", "")
},
}.ToString());
}
UniValue wallets(UniValue::VARR);
for (const auto& path : ListWalletDir()) {
UniValue wallet(UniValue::VOBJ);
wallet.pushKV("name", path.string());
wallets.push_back(wallet);
}
UniValue result(UniValue::VOBJ);
result.pushKV("wallets", wallets);
return result;
}
static UniValue listwallets(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"listwallets",
"Returns a list of currently loaded wallets.\n"
"For full information on the wallet, use \"getwalletinfo\"\n",
{},
RPCResult{
"[ (json array of strings)\n"
" \"walletname\" (string) the wallet name\n"
" ...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("listwallets", "")
+ HelpExampleRpc("listwallets", "")
},
}.ToString());
UniValue obj(UniValue::VARR);
for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
if (!EnsureWalletIsAvailable(wallet.get(), request.fHelp)) {
return NullUniValue;
}
LOCK(wallet->cs_wallet);
obj.push_back(wallet->GetName());
}
return obj;
}
static UniValue loadwallet(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"loadwallet",
"\nLoads a wallet from a wallet file or directory."
"\nNote that all wallet command-line options used when starting hydrad will be"
"\napplied to the new wallet (eg -zapwallettxes, upgradewallet, rescan, etc).\n",
{
{"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet directory or .dat file."},
},
RPCResult{
"{\n"
" \"name\" : <wallet_name>, (string) The wallet name if loaded successfully.\n"
" \"warning\" : <warning>, (string) Warning message if wallet was not loaded cleanly.\n"
"}\n"
},
RPCExamples{
HelpExampleCli("loadwallet", "\"test.dat\"")
+ HelpExampleRpc("loadwallet", "\"test.dat\"")
},
}.ToString());
WalletLocation location(request.params[0].get_str());
if (!location.Exists()) {
throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Wallet " + location.GetName() + " not found.");
} else if (fs::is_directory(location.GetPath())) {
// The given filename is a directory. Check that there's a wallet.dat file.
fs::path wallet_dat_file = location.GetPath() / "wallet.dat";
if (fs::symlink_status(wallet_dat_file).type() == fs::file_not_found) {
throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Directory " + location.GetName() + " does not contain a wallet.dat file.");
}
}
std::string error, warning;
std::shared_ptr<CWallet> const wallet = LoadWallet(*g_rpc_interfaces->chain, location, error, warning);
if (!wallet) throw JSONRPCError(RPC_WALLET_ERROR, error);
UniValue obj(UniValue::VOBJ);
obj.pushKV("name", wallet->GetName());
obj.pushKV("warning", warning);
return obj;
}
static UniValue createwallet(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) {
throw std::runtime_error(
RPCHelpMan{"createwallet",
"\nCreates and loads a new wallet.\n",
{
{"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name for the new wallet. If this is a path, the wallet will be created at the path location."},
{"disable_private_keys", RPCArg::Type::BOOL, /* default */ "false", "Disable the possibility of private keys (only watchonlys are possible in this mode)."},
{"blank", RPCArg::Type::BOOL, /* default */ "false", "Create a blank wallet. A blank wallet has no keys or HD seed. One can be set using sethdseed."},
},
RPCResult{
"{\n"
" \"name\" : <wallet_name>, (string) The wallet name if created successfully. If the wallet was created using a full path, the wallet_name will be the full path.\n"
" \"warning\" : <warning>, (string) Warning message if wallet was not loaded cleanly.\n"
"}\n"
},
RPCExamples{
HelpExampleCli("createwallet", "\"testwallet\"")
+ HelpExampleRpc("createwallet", "\"testwallet\"")
},
}.ToString());
}
std::string error;
std::string warning;
CScheduler scheduler;
uint64_t flags = 0;
if (!request.params[1].isNull() && request.params[1].get_bool()) {
flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS;
}
if (!request.params[2].isNull() && request.params[2].get_bool()) {
flags |= WALLET_FLAG_BLANK_WALLET;
}
WalletLocation location(request.params[0].get_str());
if (location.Exists()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet " + location.GetName() + " already exists.");
}
// Wallet::Verify will check if we're trying to create a wallet with a duplication name.
if (!CWallet::Verify(*g_rpc_interfaces->chain, location, false, error, warning)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet file verification failed: " + error);
}
std::shared_ptr<CWallet> const wallet = CWallet::CreateWalletFromFile(*g_rpc_interfaces->chain, location, flags);
if (!wallet) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet creation failed.");
}
AddWallet(wallet);
wallet->postInitProcess(scheduler);
UniValue obj(UniValue::VOBJ);
obj.pushKV("name", wallet->GetName());
obj.pushKV("warning", warning);
return obj;
}
static UniValue unloadwallet(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1) {
throw std::runtime_error(
RPCHelpMan{"unloadwallet",
"Unloads the wallet referenced by the request endpoint otherwise unloads the wallet specified in the argument.\n"
"Specifying the wallet name on a wallet endpoint is invalid.",
{
{"wallet_name", RPCArg::Type::STR, /* default */ "the wallet name from the RPC request", "The name of the wallet to unload."},
},
RPCResults{},
RPCExamples{
HelpExampleCli("unloadwallet", "wallet_name")
+ HelpExampleRpc("unloadwallet", "wallet_name")
},
}.ToString());
}
std::string wallet_name;
if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
if (!request.params[0].isNull()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot unload the requested wallet");
}
} else {
wallet_name = request.params[0].get_str();
}
std::shared_ptr<CWallet> wallet = GetWallet(wallet_name);
if (!wallet) {
throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
}
// Release the "main" shared pointer and prevent further notifications.
// Note that any attempt to load the same wallet would fail until the wallet
// is destroyed (see CheckUniqueFileid).
if (!RemoveWallet(wallet)) {
throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded");
}
UnloadWallet(std::move(wallet));
return NullUniValue;
}
static UniValue resendwallettransactions(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"resendwallettransactions",
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n"
"automatically.\n",
{},
RPCResult{
"Returns an RPC error if -walletbroadcast is set to false.\n"
"Returns array of transaction ids that were re-broadcast.\n"
},
RPCExamples{""},
}.ToString()
);
if (!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (!pwallet->GetBroadcastTransactions()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet transaction broadcasting is disabled with -walletbroadcast");
}
std::vector<uint256> txids = pwallet->ResendWalletTransactionsBefore(*locked_chain, GetTime(), g_connman.get());
UniValue result(UniValue::VARR);
for (const uint256& txid : txids)
{
result.push_back(txid.ToString());
}
return result;
}
static UniValue listunspent(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 5)
throw std::runtime_error(
RPCHelpMan{"listunspent",
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n",
{
{"minconf", RPCArg::Type::NUM, /* default */ "1", "The minimum confirmations to filter"},
{"maxconf", RPCArg::Type::NUM, /* default */ "9999999", "The maximum confirmations to filter"},
{"addresses", RPCArg::Type::ARR, /* default */ "empty array", "A json array of HYDRA addresses to filter",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "HYDRA address"},
},
},
{"include_unsafe", RPCArg::Type::BOOL, /* default */ "true", "Include outputs that are not safe to spend\n"
" See description of \"safe\" attribute below."},
{"query_options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "JSON with query options",
{
{"minimumAmount", RPCArg::Type::AMOUNT, /* default */ "0", "Minimum value of each UTXO in " + CURRENCY_UNIT + ""},
{"maximumAmount", RPCArg::Type::AMOUNT, /* default */ "unlimited", "Maximum value of each UTXO in " + CURRENCY_UNIT + ""},
{"maximumCount", RPCArg::Type::NUM, /* default */ "unlimited", "Maximum number of UTXOs"},
{"minimumSumAmount", RPCArg::Type::AMOUNT, /* default */ "unlimited", "Minimum sum value of all UTXOs in " + CURRENCY_UNIT + ""},
},
"query_options"},
},
RPCResult{
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the HYDRA address\n"
" \"label\" : \"label\", (string) The associated label, or \"\" for the default label\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction output amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"redeemScript\" : \"script\" (string) The redeemScript if scriptPubKey is P2SH\n"
" \"witnessScript\" : \"script\" (string) witnessScript if the scriptPubKey is P2WSH or P2SH-P2WSH\n"
" \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n"
" \"solvable\" : xxx, (bool) Whether we know how to spend this output, ignoring the lack of keys\n"
" \"desc\" : xxx, (string, only when solvable) A descriptor for spending this output\n"
" \"safe\" : xxx (bool) Whether this output is considered safe to spend. Unconfirmed transactions\n"
" from outside keys and unconfirmed replacement transactions are considered unsafe\n"
" and are not eligible for spending by fundrawtransaction and sendtoaddress.\n"
" }\n"
" ,...\n"
"]\n"
},
RPCExamples{
HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\",\\\"H6sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\\\",\\\"H6sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\"]\"")
+ HelpExampleCli("listunspent", "6 9999999 '[]' true '{ \"minimumAmount\": 0.005 }'")
+ HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ")
},
}.ToString());
int nMinDepth = 1;
if (!request.params[0].isNull()) {
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
nMinDepth = request.params[0].get_int();
}
int nMaxDepth = 9999999;
if (!request.params[1].isNull()) {
RPCTypeCheckArgument(request.params[1], UniValue::VNUM);
nMaxDepth = request.params[1].get_int();
}
std::set<CTxDestination> destinations;
if (!request.params[2].isNull()) {
RPCTypeCheckArgument(request.params[2], UniValue::VARR);
UniValue inputs = request.params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
CTxDestination dest = DecodeDestination(input.get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid HYDRA address: ") + input.get_str());
}
if (!destinations.insert(dest).second) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
}
}
}
bool include_unsafe = true;
if (!request.params[3].isNull()) {
RPCTypeCheckArgument(request.params[3], UniValue::VBOOL);
include_unsafe = request.params[3].get_bool();
}
CAmount nMinimumAmount = 0;
CAmount nMaximumAmount = MAX_MONEY;
CAmount nMinimumSumAmount = MAX_MONEY;
uint64_t nMaximumCount = 0;
if (!request.params[4].isNull()) {
const UniValue& options = request.params[4].get_obj();
if (options.exists("minimumAmount"))
nMinimumAmount = AmountFromValue(options["minimumAmount"]);
if (options.exists("maximumAmount"))
nMaximumAmount = AmountFromValue(options["maximumAmount"]);
if (options.exists("minimumSumAmount"))
nMinimumSumAmount = AmountFromValue(options["minimumSumAmount"]);
if (options.exists("maximumCount"))
nMaximumCount = options["maximumCount"].get_int64();
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
UniValue results(UniValue::VARR);
std::vector<COutput> vecOutputs;
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
pwallet->AvailableCoins(*locked_chain, vecOutputs, !include_unsafe, nullptr, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
LOCK(pwallet->cs_wallet);
for (const COutput& out : vecOutputs) {
CTxDestination address;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, address);
if (destinations.size() && (!fValidAddress || !destinations.count(address)))
continue;
UniValue entry(UniValue::VOBJ);
entry.pushKV("txid", out.tx->GetHash().GetHex());
entry.pushKV("vout", out.i);
if (fValidAddress) {
entry.pushKV("address", EncodeDestination(address));
auto i = pwallet->mapAddressBook.find(address);
if (i != pwallet->mapAddressBook.end()) {
entry.pushKV("label", i->second.name);
}
if (scriptPubKey.IsPayToScriptHash()) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwallet->GetCScript(hash, redeemScript)) {
entry.pushKV("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()));
// Now check if the redeemScript is actually a P2WSH script
CTxDestination witness_destination;
if (redeemScript.IsPayToWitnessScriptHash()) {
bool extracted = ExtractDestination(redeemScript, witness_destination);
assert(extracted);
// Also return the witness script
const WitnessV0ScriptHash& whash = boost::get<WitnessV0ScriptHash>(witness_destination);
CScriptID id;
CRIPEMD160().Write(whash.begin(), whash.size()).Finalize(id.begin());
CScript witnessScript;
if (pwallet->GetCScript(id, witnessScript)) {
entry.pushKV("witnessScript", HexStr(witnessScript.begin(), witnessScript.end()));
}
}
}
} else if (scriptPubKey.IsPayToWitnessScriptHash()) {
const WitnessV0ScriptHash& whash = boost::get<WitnessV0ScriptHash>(address);
CScriptID id;
CRIPEMD160().Write(whash.begin(), whash.size()).Finalize(id.begin());
CScript witnessScript;
if (pwallet->GetCScript(id, witnessScript)) {
entry.pushKV("witnessScript", HexStr(witnessScript.begin(), witnessScript.end()));
}
}
}
entry.pushKV("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
entry.pushKV("amount", ValueFromAmount(out.tx->tx->vout[out.i].nValue));
entry.pushKV("confirmations", out.nDepth);
entry.pushKV("spendable", out.fSpendable);
entry.pushKV("solvable", out.fSolvable);
if (out.fSolvable) {
auto descriptor = InferDescriptor(scriptPubKey, *pwallet);
entry.pushKV("desc", descriptor->ToString());
}
entry.pushKV("safe", out.fSafe);
results.push_back(entry);
}
return results;
}
void FundTransaction(CWallet* const pwallet, CMutableTransaction& tx, CAmount& fee_out, int& change_position, UniValue options)
{
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
CCoinControl coinControl;
change_position = -1;
bool lockUnspents = false;
UniValue subtractFeeFromOutputs;
std::set<int> setSubtractFeeFromOutputs;
if (!options.isNull()) {
if (options.type() == UniValue::VBOOL) {
// backward compatibility bool only fallback
coinControl.fAllowWatchOnly = options.get_bool();
}
else {
RPCTypeCheckArgument(options, UniValue::VOBJ);
RPCTypeCheckObj(options,
{
{"changeAddress", UniValueType(UniValue::VSTR)},
{"changePosition", UniValueType(UniValue::VNUM)},
{"change_type", UniValueType(UniValue::VSTR)},
{"includeWatching", UniValueType(UniValue::VBOOL)},
{"lockUnspents", UniValueType(UniValue::VBOOL)},
{"feeRate", UniValueType()}, // will be checked below
{"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
{"replaceable", UniValueType(UniValue::VBOOL)},
{"conf_target", UniValueType(UniValue::VNUM)},
{"estimate_mode", UniValueType(UniValue::VSTR)},
},
true, true);
if (options.exists("changeAddress")) {
CTxDestination dest = DecodeDestination(options["changeAddress"].get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "changeAddress must be a valid HYDRA address");
}
coinControl.destChange = dest;
}
if (options.exists("changePosition"))
change_position = options["changePosition"].get_int();
if (options.exists("change_type")) {
if (options.exists("changeAddress")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both changeAddress and address_type options");
}
coinControl.m_change_type = pwallet->m_default_change_type;
if (!ParseOutputType(options["change_type"].get_str(), *coinControl.m_change_type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
}
}
if (options.exists("includeWatching"))
coinControl.fAllowWatchOnly = options["includeWatching"].get_bool();
if (options.exists("lockUnspents"))
lockUnspents = options["lockUnspents"].get_bool();
if (options.exists("feeRate"))
{
coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
coinControl.fOverrideFeeRate = true;
}
if (options.exists("subtractFeeFromOutputs"))
subtractFeeFromOutputs = options["subtractFeeFromOutputs"].get_array();
if (options.exists("replaceable")) {
coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool();
}
if (options.exists("conf_target")) {
if (options.exists("feeRate")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and feeRate");
}
coinControl.m_confirm_target = ParseConfirmTarget(options["conf_target"]);
}
if (options.exists("estimate_mode")) {
if (options.exists("feeRate")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
}
if (!FeeModeFromString(options["estimate_mode"].get_str(), coinControl.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
}
}
}
if (tx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
if (change_position != -1 && (change_position < 0 || (unsigned int)change_position > tx.vout.size()))
throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
int pos = subtractFeeFromOutputs[idx].get_int();
if (setSubtractFeeFromOutputs.count(pos))
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos));
if (pos < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos));
if (pos >= int(tx.vout.size()))
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos));
setSubtractFeeFromOutputs.insert(pos);
}
std::string strFailReason;
if (!pwallet->FundTransaction(tx, fee_out, change_position, strFailReason, lockUnspents, setSubtractFeeFromOutputs, coinControl)) {
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
}
static UniValue fundrawtransaction(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
const RPCHelpMan help{"fundrawtransaction",
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add at most one change output to the outputs.\n"
"No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransactionwithkey\n"
" or signrawtransactionwithwallet for that.\n"
"Note that all existing inputs must have their previous output transaction be in the wallet.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be\n"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
"Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n",
{
{"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}",
{
{"changeAddress", RPCArg::Type::STR, /* default */ "pool address", "The HYDRA address to receive the change"},
{"changePosition", RPCArg::Type::NUM, /* default */ "random", "The index of the change output"},
{"change_type", RPCArg::Type::STR, /* default */ "set by -changetype", "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
{"includeWatching", RPCArg::Type::BOOL, /* default */ "false", "Also select inputs which are watch only"},
{"lockUnspents", RPCArg::Type::BOOL, /* default */ "false", "Lock selected unspent outputs"},
{"feeRate", RPCArg::Type::AMOUNT, /* default */ "not set: makes wallet determine the fee", "Set a specific fee rate in " + CURRENCY_UNIT + "/kB"},
{"subtractFeeFromOutputs", RPCArg::Type::ARR, /* default */ "empty array", "A json array of integers.\n"
" The fee will be equally deducted from the amount of each specified output.\n"
" Those recipients will receive less HYDRA than you enter in their corresponding amount field.\n"
" If no outputs are specified here, the sender pays the fee.",
{
{"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
},
},
{"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default", "Marks this transaction as BIP125 replaceable.\n"
" Allows this transaction to be replaced by a transaction with higher fees"},
{"conf_target", RPCArg::Type::NUM, /* default */ "fallback to wallet's default", "Confirmation target (in blocks)"},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
},
"options"},
{"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"
" \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
" \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
},
RPCExamples{
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
"\nAdd sufficient unsigned inputs to meet the output value\n"
+ HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
"\nSign the transaction\n"
+ HelpExampleCli("signrawtransactionwithwallet", "\"fundedtransactionhex\"") +
"\nSend the transaction\n"
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
},
};
if (request.fHelp || !help.IsValidNumArgs(request.params.size())) {
throw std::runtime_error(help.ToString());
}
RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType(), UniValue::VBOOL});
// parse hex string from parameter
CMutableTransaction tx;
bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool();
bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool();
if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
CAmount fee;
int change_position;
FundTransaction(pwallet, tx, fee, change_position, request.params[1]);
UniValue result(UniValue::VOBJ);
result.pushKV("hex", EncodeHexTx(CTransaction(tx)));
result.pushKV("fee", ValueFromAmount(fee));
result.pushKV("changepos", change_position);
return result;
}
UniValue signrawtransactionwithwallet(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
RPCHelpMan{"signrawtransactionwithwallet",
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second 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." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
{"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::NO, "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\""},
},
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("signrawtransactionwithwallet", "\"myhex\"")
+ HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")
},
}.ToString());
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VSTR}, true);
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
// Sign the transaction
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
return SignTransaction(pwallet->chain(), mtx, request.params[1], pwallet, false, request.params[2]);
}
UniValue signrawsendertransactionwithwallet(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"signrawsendertransactionwithwallet",
"\nSign OP_SENDER outputs for raw transaction (serialized, hex-encoded).\n" +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
{"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\""},
},
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"
" \"amount\" : n, (numeric) The amount of the output\n"
" \"scriptPubKey\" : \"hex\", (string) The hex-encoded public key script of the output\n"
" \"error\" : \"text\" (string) Verification or signing error related to the output\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
},
RPCExamples{
HelpExampleCli("signrawsendertransactionwithwallet", "\"myhex\"")
+ HelpExampleRpc("signrawsendertransactionwithwallet", "\"myhex\"")
},
}.ToString());
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR}, true);
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
// Sign the transaction
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
return SignTransactionSender(pwallet->chain(), mtx, pwallet, request.params[1]);
}
static UniValue bumpfee(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"bumpfee",
"\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n"
"An opt-in RBF transaction with the given txid must be in the wallet.\n"
"The command will pay the additional fee by decreasing (or perhaps removing) its change output.\n"
"If the change output is not big enough to cover the increased fee, the command will currently fail\n"
"instead of adding new inputs to compensate. (A future implementation could improve this.)\n"
"The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
"By default, the new fee will be calculated automatically using estimatesmartfee.\n"
"The user can specify a confirmation target for estimatesmartfee.\n"
"Alternatively, the user can specify totalFee, or use RPC settxfee to set a higher fee rate.\n"
"At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
"returned by getnetworkinfo) to enter the node's mempool.\n",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid to be bumped"},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "",
{
{"confTarget", RPCArg::Type::NUM, /* default */ "fallback to wallet's default", "Confirmation target (in blocks)"},
{"totalFee", RPCArg::Type::NUM, /* default */ "fallback to 'confTarget'", "Total fee (NOT feerate) to pay, in satoshis.\n"
" In rare cases, the actual fee paid might be slightly higher than the specified\n"
" totalFee if the tx change output has to be removed because it is too close to\n"
" the dust threshold."},
{"replaceable", RPCArg::Type::BOOL, /* default */ "true", "Whether the new transaction should still be\n"
" marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
" be left unchanged from the original. If false, any input sequence numbers in the\n"
" original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n"
" so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
" still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
" are replaceable)."},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
},
"options"},
},
RPCResult{
"{\n"
" \"txid\": \"value\", (string) The id of the new transaction\n"
" \"origfee\": n, (numeric) Fee of the replaced transaction\n"
" \"fee\": n, (numeric) Fee of the new transaction\n"
" \"errors\": [ str... ] (json array of strings) Errors encountered during processing (may be empty)\n"
"}\n"
},
RPCExamples{
"\nBump the fee, get the new transaction\'s txid\n" +
HelpExampleCli("bumpfee", "<txid>")
},
}.ToString());
}
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
uint256 hash(ParseHashV(request.params[0], "txid"));
// optional parameters
CAmount totalFee = 0;
CCoinControl coin_control;
coin_control.m_signal_bip125_rbf = true;
if (!request.params[1].isNull()) {
UniValue options = request.params[1];
RPCTypeCheckObj(options,
{
{"confTarget", UniValueType(UniValue::VNUM)},
{"totalFee", UniValueType(UniValue::VNUM)},
{"replaceable", UniValueType(UniValue::VBOOL)},
{"estimate_mode", UniValueType(UniValue::VSTR)},
},
true, true);
if (options.exists("confTarget") && options.exists("totalFee")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and totalFee options should not both be set. Please provide either a confirmation target for fee estimation or an explicit total fee for the transaction.");
} else if (options.exists("confTarget")) { // TODO: alias this to conf_target
coin_control.m_confirm_target = ParseConfirmTarget(options["confTarget"]);
} else if (options.exists("totalFee")) {
totalFee = options["totalFee"].get_int64();
if (totalFee <= 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid totalFee %s (must be greater than 0)", FormatMoney(totalFee)));
}
}
if (options.exists("replaceable")) {
coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool();
}
if (options.exists("estimate_mode")) {
if (!FeeModeFromString(options["estimate_mode"].get_str(), coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
}
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::vector<std::string> errors;
CAmount old_fee;
CAmount new_fee;
CMutableTransaction mtx;
feebumper::Result res = feebumper::CreateTransaction(pwallet, hash, coin_control, totalFee, errors, old_fee, new_fee, mtx);
if (res != feebumper::Result::OK) {
switch(res) {
case feebumper::Result::INVALID_ADDRESS_OR_KEY:
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errors[0]);
break;
case feebumper::Result::INVALID_REQUEST:
throw JSONRPCError(RPC_INVALID_REQUEST, errors[0]);
break;
case feebumper::Result::INVALID_PARAMETER:
throw JSONRPCError(RPC_INVALID_PARAMETER, errors[0]);
break;
case feebumper::Result::WALLET_ERROR:
throw JSONRPCError(RPC_WALLET_ERROR, errors[0]);
break;
default:
throw JSONRPCError(RPC_MISC_ERROR, errors[0]);
break;
}
}
// sign bumped transaction
if (!feebumper::SignTransaction(pwallet, mtx)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
}
// commit the bumped transaction
uint256 txid;
if (feebumper::CommitTransaction(pwallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
throw JSONRPCError(RPC_WALLET_ERROR, errors[0]);
}
UniValue result(UniValue::VOBJ);
result.pushKV("txid", txid.GetHex());
result.pushKV("origfee", ValueFromAmount(old_fee));
result.pushKV("fee", ValueFromAmount(new_fee));
UniValue result_errors(UniValue::VARR);
for (const std::string& error : errors) {
result_errors.push_back(error);
}
result.pushKV("errors", result_errors);
return result;
}
UniValue generate(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"generate",
"\nMine up to nblocks blocks immediately (before the RPC call returns) to an address in the wallet.\n",
{
{"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
{"maxtries", RPCArg::Type::NUM, /* default */ "1000000", "How many iterations to try."},
},
RPCResult{
"[ blockhashes ] (array) hashes of blocks generated\n"
},
RPCExamples{
"\nGenerate 11 blocks\n"
+ HelpExampleCli("generate", "11")
},
}.ToString());
}
if (!IsDeprecatedRPCEnabled("generate")) {
throw JSONRPCError(RPC_METHOD_DEPRECATED, "The wallet generate rpc method is deprecated and will be fully removed in v0.19. "
"To use generate in v0.18, restart hydrad with -deprecatedrpc=generate.\n"
"Clients should transition to using the node rpc method generatetoaddress\n");
}
int num_generate = request.params[0].get_int();
uint64_t max_tries = 1000000;
if (!request.params[1].isNull()) {
max_tries = request.params[1].get_int();
}
std::shared_ptr<CReserveScript> coinbase_script;
pwallet->GetScriptForMining(coinbase_script);
// If the keypool is exhausted, no script is returned at all. Catch this.
if (!coinbase_script) {
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
}
//throw an error if no script was provided
if (coinbase_script->reserveScript.empty()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available");
}
return generateBlocks(coinbase_script, num_generate, max_tries, true);
}
UniValue rescanblockchain(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"rescanblockchain",
"\nRescan the local blockchain for wallet related transactions.\n",
{
{"start_height", RPCArg::Type::NUM, /* default */ "0", "block height where the rescan should start"},
{"stop_height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "the last block height that should be scanned. If none is provided it will rescan up to the tip at return time of this call."},
},
RPCResult{
"{\n"
" \"start_height\" (numeric) The block height where the rescan started (the requested height or 0)\n"
" \"stop_height\" (numeric) The height of the last rescanned block. May be null in rare cases if there was a reorg and the call didn't scan any blocks because they were already scanned in the background.\n"
"}\n"
},
RPCExamples{
HelpExampleCli("rescanblockchain", "100000 120000")
+ HelpExampleRpc("rescanblockchain", "100000, 120000")
},
}.ToString());
}
WalletRescanReserver reserver(pwallet);
if (!reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
int start_height = 0;
uint256 start_block, stop_block;
{
auto locked_chain = pwallet->chain().lock();
Optional<int> tip_height = locked_chain->getHeight();
if (!request.params[0].isNull()) {
start_height = request.params[0].get_int();
if (start_height < 0 || !tip_height || start_height > *tip_height) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height");
}
}
Optional<int> stop_height;
if (!request.params[1].isNull()) {
stop_height = request.params[1].get_int();
if (*stop_height < 0 || !tip_height || *stop_height > *tip_height) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
}
else if (*stop_height < start_height) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater than start_height");
}
}
// We can't rescan beyond non-pruned blocks, stop and throw an error
if (locked_chain->findPruned(start_height, stop_height)) {
throw JSONRPCError(RPC_MISC_ERROR, "Can't rescan beyond pruned data. Use RPC call getblockchaininfo to determine your pruned height.");
}
if (tip_height) {
start_block = locked_chain->getBlockHash(start_height);
// If called with a stop_height, set the stop_height here to
// trigger a rescan to that height.
// If called without a stop height, leave stop_height as null here
// so rescan continues to the tip (even if the tip advances during
// rescan).
if (stop_height) {
stop_block = locked_chain->getBlockHash(*stop_height);
}
}
}
CWallet::ScanResult result =
pwallet->ScanForWalletTransactions(start_block, stop_block, reserver, true /* fUpdate */);
switch (result.status) {
case CWallet::ScanResult::SUCCESS:
break;
case CWallet::ScanResult::FAILURE:
throw JSONRPCError(RPC_MISC_ERROR, "Rescan failed. Potentially corrupted data files.");
case CWallet::ScanResult::USER_ABORT:
throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted.");
// no default case, so the compiler can warn about missing cases
}
UniValue response(UniValue::VOBJ);
response.pushKV("start_height", start_height);
response.pushKV("stop_height", result.last_scanned_height ? *result.last_scanned_height : UniValue());
return response;
}
class DescribeWalletAddressVisitor : public boost::static_visitor<UniValue>
{
public:
CWallet * const pwallet;
void ProcessSubScript(const CScript& subscript, UniValue& obj) const
{
// Always present: script type and redeemscript
std::vector<std::vector<unsigned char>> solutions_data;
txnouttype which_type = Solver(subscript, solutions_data);
obj.pushKV("script", GetTxnOutputType(which_type));
obj.pushKV("hex", HexStr(subscript.begin(), subscript.end()));
CTxDestination embedded;
if (ExtractDestination(subscript, embedded)) {
// Only when the script corresponds to an address.
UniValue subobj(UniValue::VOBJ);
UniValue detail = DescribeAddress(embedded);
subobj.pushKVs(detail);
UniValue wallet_detail = boost::apply_visitor(*this, embedded);
subobj.pushKVs(wallet_detail);
subobj.pushKV("address", EncodeDestination(embedded));
subobj.pushKV("scriptPubKey", HexStr(subscript.begin(), subscript.end()));
// Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
obj.pushKV("embedded", std::move(subobj));
} else if (which_type == TX_MULTISIG) {
// Also report some information on multisig scripts (which do not have a corresponding address).
// TODO: abstract out the common functionality between this logic and ExtractDestinations.
obj.pushKV("sigsrequired", solutions_data[0][0]);
UniValue pubkeys(UniValue::VARR);
for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
pubkeys.push_back(HexStr(key.begin(), key.end()));
}
obj.pushKV("pubkeys", std::move(pubkeys));
}
}
explicit DescribeWalletAddressVisitor(CWallet* _pwallet) : pwallet(_pwallet) {}
UniValue operator()(const CNoDestination& dest) const { return UniValue(UniValue::VOBJ); }
UniValue operator()(const CKeyID& keyID) const
{
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
obj.pushKV("pubkey", HexStr(vchPubKey));
obj.pushKV("iscompressed", vchPubKey.IsCompressed());
}
return obj;
}
UniValue operator()(const CScriptID& scriptID) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
ProcessSubScript(subscript, obj);
}
return obj;
}
UniValue operator()(const WitnessV0KeyHash& id) const
{
UniValue obj(UniValue::VOBJ);
CPubKey pubkey;
if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) {
obj.pushKV("pubkey", HexStr(pubkey));
}
return obj;
}
UniValue operator()(const WitnessV0ScriptHash& id) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
CRIPEMD160 hasher;
uint160 hash;
hasher.Write(id.begin(), 32).Finalize(hash.begin());
if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) {
ProcessSubScript(subscript, obj);
}
return obj;
}
UniValue operator()(const WitnessUnknown& id) const { return UniValue(UniValue::VOBJ); }
};
static UniValue DescribeWalletAddress(CWallet* pwallet, const CTxDestination& dest)
{
UniValue ret(UniValue::VOBJ);
UniValue detail = DescribeAddress(dest);
ret.pushKVs(detail);
ret.pushKVs(boost::apply_visitor(DescribeWalletAddressVisitor(pwallet), dest));
return ret;
}
/** Convert CAddressBookData to JSON record. */
static UniValue AddressBookDataToJSON(const CAddressBookData& data, const bool verbose)
{
UniValue ret(UniValue::VOBJ);
if (verbose) {
ret.pushKV("name", data.name);
}
ret.pushKV("purpose", data.purpose);
return ret;
}
UniValue getaddressinfo(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
RPCHelpMan{"getaddressinfo",
"\nReturn information about the given HYDRA address. Some information requires the address\n"
"to be in the wallet.\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The HYDRA address to get the information of."},
},
RPCResult{
"{\n"
" \"address\" : \"address\", (string) The HYDRA address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex-encoded scriptPubKey generated by the address\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
" \"solvable\" : true|false, (boolean) Whether we know how to spend coins sent to this address, ignoring the possible lack of private keys\n"
" \"desc\" : \"desc\", (string, optional) A descriptor for spending coins sent to this address (only when solvable)\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"ischange\" : true|false, (boolean) If the address was used for change output\n"
" \"iswitness\" : true|false, (boolean) If the address is a witness address\n"
" \"witness_version\" : version (numeric, optional) The version number of the witness program\n"
" \"witness_program\" : \"hex\" (string, optional) The hex value of the witness program\n"
" \"script\" : \"type\" (string, optional) The output script type. Only if \"isscript\" is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown\n"
" \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n"
" \"pubkeys\" (string, optional) Array of pubkeys associated with the known redeemscript (only if \"script\" is \"multisig\")\n"
" [\n"
" \"pubkey\"\n"
" ,...\n"
" ]\n"
" \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output (only if \"script\" is \"multisig\")\n"
" \"pubkey\" : \"publickeyhex\", (string, optional) The hex value of the raw public key, for single-key addresses (possibly embedded in P2SH or P2WSH)\n"
" \"embedded\" : {...}, (object, optional) Information about the address embedded in P2SH or P2WSH, if relevant and known. It includes all getaddressinfo output fields for the embedded address, excluding metadata (\"timestamp\", \"hdkeypath\", \"hdseedid\") and relation to the wallet (\"ismine\", \"iswatchonly\").\n"
" \"iscompressed\" : true|false, (boolean, optional) If the pubkey is compressed\n"
" \"label\" : \"label\" (string) The label associated with the address, \"\" is the default label\n"
" \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
" \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
" \"hdseedid\" : \"<hash160>\" (string, optional) The Hash160 of the HD seed\n"
" \"hdmasterfingerprint\" : \"<hash160>\" (string, optional) The fingperint of the master key.\n"
" \"labels\" (object) Array of labels associated with the address.\n"
" [\n"
" { (json object of label data)\n"
" \"name\": \"labelname\" (string) The label\n"
" \"purpose\": \"string\" (string) Purpose of address (\"send\" for sending address, \"receive\" for receiving address)\n"
" },...\n"
" ]\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getaddressinfo", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\"")
+ HelpExampleRpc("getaddressinfo", "\"HBvKE1Vk4gDgu5j7TZUX9P3QMAhVErMYoC\"")
}
}.ToString());
}
LOCK(pwallet->cs_wallet);
UniValue ret(UniValue::VOBJ);
CTxDestination dest = DecodeDestination(request.params[0].get_str());
// Make sure the destination is valid
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::string currentAddress = EncodeDestination(dest);
ret.pushKV("address", currentAddress);
CScript scriptPubKey = GetScriptForDestination(dest);
ret.pushKV("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
isminetype mine = IsMine(*pwallet, dest);
ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
bool solvable = IsSolvable(*pwallet, scriptPubKey);
ret.pushKV("solvable", solvable);
if (solvable) {
ret.pushKV("desc", InferDescriptor(scriptPubKey, *pwallet)->ToString());
}
ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
UniValue detail = DescribeWalletAddress(pwallet, dest);
ret.pushKVs(detail);
if (pwallet->mapAddressBook.count(dest)) {
ret.pushKV("label", pwallet->mapAddressBook[dest].name);
}
ret.pushKV("ischange", pwallet->IsChange(scriptPubKey));
const CKeyMetadata* meta = nullptr;
CKeyID key_id = GetKeyForDestination(*pwallet, dest);
if (!key_id.IsNull()) {
auto it = pwallet->mapKeyMetadata.find(key_id);
if (it != pwallet->mapKeyMetadata.end()) {
meta = &it->second;
}
}
if (!meta) {
auto it = pwallet->m_script_metadata.find(CScriptID(scriptPubKey));
if (it != pwallet->m_script_metadata.end()) {
meta = &it->second;
}
}
if (meta) {
ret.pushKV("timestamp", meta->nCreateTime);
if (meta->has_key_origin) {
ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path));
ret.pushKV("hdseedid", meta->hd_seed_id.GetHex());
ret.pushKV("hdmasterfingerprint", HexStr(meta->key_origin.fingerprint, meta->key_origin.fingerprint + 4));
}
}
// Currently only one label can be associated with an address, return an array
// so the API remains stable if we allow multiple labels to be associated with
// an address.
UniValue labels(UniValue::VARR);
std::map<CTxDestination, CAddressBookData>::iterator mi = pwallet->mapAddressBook.find(dest);
if (mi != pwallet->mapAddressBook.end()) {
labels.push_back(AddressBookDataToJSON(mi->second, true));
}
ret.pushKV("labels", std::move(labels));
return ret;
}
static UniValue getaddressesbylabel(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"getaddressesbylabel",
"\nReturns the list of addresses assigned the specified label.\n",
{
{"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label."},
},
RPCResult{
"{ (json object with addresses as keys)\n"
" \"address\": { (json object with information about address)\n"
" \"purpose\": \"string\" (string) Purpose of address (\"send\" for sending address, \"receive\" for receiving address)\n"
" },...\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getaddressesbylabel", "\"tabby\"")
+ HelpExampleRpc("getaddressesbylabel", "\"tabby\"")
},
}.ToString());
LOCK(pwallet->cs_wallet);
std::string label = LabelFromValue(request.params[0]);
// Find all addresses that have the given label
UniValue ret(UniValue::VOBJ);
for (const std::pair<const CTxDestination, CAddressBookData>& item : pwallet->mapAddressBook) {
if (item.second.name == label) {
ret.pushKV(EncodeDestination(item.first), AddressBookDataToJSON(item.second, false));
}
}
if (ret.empty()) {
throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label));
}
return ret;
}
static UniValue listlabels(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"listlabels",
"\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n",
{
{"purpose", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Address purpose to list labels for ('send','receive'). An empty string is the same as not providing this argument."},
},
RPCResult{
"[ (json array of string)\n"
" \"label\", (string) Label name\n"
" ...\n"
"]\n"
},
RPCExamples{
"\nList all labels\n"
+ HelpExampleCli("listlabels", "") +
"\nList labels that have receiving addresses\n"
+ HelpExampleCli("listlabels", "receive") +
"\nList labels that have sending addresses\n"
+ HelpExampleCli("listlabels", "send") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("listlabels", "receive")
},
}.ToString());
LOCK(pwallet->cs_wallet);
std::string purpose;
if (!request.params[0].isNull()) {
purpose = request.params[0].get_str();
}
// Add to a set to sort by label name, then insert into Univalue array
std::set<std::string> label_set;
for (const std::pair<const CTxDestination, CAddressBookData>& entry : pwallet->mapAddressBook) {
if (purpose.empty() || entry.second.purpose == purpose) {
label_set.insert(entry.second.name);
}
}
UniValue ret(UniValue::VARR);
for (const std::string& name : label_set) {
ret.push_back(name);
}
return ret;
}
UniValue sethdseed(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"sethdseed",
"\nSet or generate a new HD wallet seed. Non-HD wallets will not be upgraded to being a HD wallet. Wallets that are already\n"
"HD will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n"
"\nNote that you will need to MAKE A NEW BACKUP of your wallet after setting the HD wallet seed." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"newkeypool", RPCArg::Type::BOOL, /* default */ "true", "Whether to flush old unused addresses, including change addresses, from the keypool and regenerate it.\n"
" If true, the next address from getnewaddress and change address from getrawchangeaddress will be from this new seed.\n"
" If false, addresses (including change addresses if the wallet already had HD Chain Split enabled) from the existing\n"
" keypool will be used until it has been depleted."},
{"seed", RPCArg::Type::STR, /* default */ "random seed", "The WIF private key to use as the new HD seed.\n"
" The seed value can be retrieved using the dumpwallet command. It is the private key marked hdseed=1"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("sethdseed", "")
+ HelpExampleCli("sethdseed", "false")
+ HelpExampleCli("sethdseed", "true \"wifkey\"")
+ HelpExampleRpc("sethdseed", "true, \"wifkey\"")
},
}.ToString());
}
if (IsInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot set a new HD seed while still in Initial Block Download");
}
if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed to a wallet with private keys disabled");
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Do not do anything to non-HD wallets
if (!pwallet->CanSupportFeature(FEATURE_HD)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed on a non-HD wallet. Start with -upgradewallet in order to upgrade a non-HD wallet to HD");
}
EnsureWalletIsUnlocked(pwallet);
bool flush_key_pool = true;
if (!request.params[0].isNull()) {
flush_key_pool = request.params[0].get_bool();
}
CPubKey master_pub_key;
if (request.params[1].isNull()) {
master_pub_key = pwallet->GenerateNewSeed();
} else {
CKey key = DecodeSecret(request.params[1].get_str());
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
}
if (HaveKey(*pwallet, key)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)");
}
master_pub_key = pwallet->DeriveNewSeed(key);
}
pwallet->SetHDSeed(master_pub_key);
if (flush_key_pool) pwallet->NewKeyPool();
return NullUniValue;
}
void AddKeypathToMap(const CWallet* pwallet, const CKeyID& keyID, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
{
CPubKey vchPubKey;
if (!pwallet->GetPubKey(keyID, vchPubKey)) {
return;
}
KeyOriginInfo info;
if (!pwallet->GetKeyOrigin(keyID, info)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Internal keypath is broken");
}
hd_keypaths.emplace(vchPubKey, std::move(info));
}
UniValue walletprocesspsbt(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
RPCHelpMan{"walletprocesspsbt",
"\nUpdate a PSBT with input information from our wallet and then sign inputs\n"
"that we can sign for." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
{"sign", RPCArg::Type::BOOL, /* default */ "true", "Also sign the transaction when updating"},
{"sighashtype", RPCArg::Type::STR, /* default */ "ALL", "The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\""},
{"bip32derivs", RPCArg::Type::BOOL, /* default */ "false", "If true, includes the BIP 32 derivation paths for public keys if we know them"},
},
RPCResult{
"{\n"
" \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" ]\n"
"}\n"
},
RPCExamples{
HelpExampleCli("walletprocesspsbt", "\"psbt\"")
},
}.ToString());
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, 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));
}
// Get the sighash type
int nHashType = ParseSighashString(request.params[2]);
// Fill transaction with our data and also sign
bool sign = request.params[1].isNull() ? true : request.params[1].get_bool();
bool bip32derivs = request.params[3].isNull() ? false : request.params[3].get_bool();
bool complete = true;
const TransactionError err = FillPSBT(pwallet, psbtx, complete, nHashType, sign, bip32derivs);
if (err != TransactionError::OK) {
throw JSONRPCTransactionError(err);
}
UniValue result(UniValue::VOBJ);
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << psbtx;
result.pushKV("psbt", EncodeBase64(ssTx.str()));
result.pushKV("complete", complete);
return result;
}
UniValue walletcreatefundedpsbt(const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet* const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 5)
throw std::runtime_error(
RPCHelpMan{"walletcreatefundedpsbt",
"\nCreates and funds a transaction in the Partially Signed Transaction format. Inputs will be added if supplied inputs are not enough\n"
"Implements the Creator and Updater roles.\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, RPCArg::Optional::NO, "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 HYDRA 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"},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "",
{
{"changeAddress", RPCArg::Type::STR_HEX, /* default */ "pool address", "The HYDRA address to receive the change"},
{"changePosition", RPCArg::Type::NUM, /* default */ "random", "The index of the change output"},
{"change_type", RPCArg::Type::STR, /* default */ "set by -changetype", "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
{"includeWatching", RPCArg::Type::BOOL, /* default */ "false", "Also select inputs which are watch only"},
{"lockUnspents", RPCArg::Type::BOOL, /* default */ "false", "Lock selected unspent outputs"},
{"feeRate", RPCArg::Type::AMOUNT, /* default */ "not set: makes wallet determine the fee", "Set a specific fee rate in " + CURRENCY_UNIT + "/kB"},
{"subtractFeeFromOutputs", RPCArg::Type::ARR, /* default */ "empty array", "A json array of integers.\n"
" The fee will be equally deducted from the amount of each specified output.\n"
" Those recipients will receive less HYDRA than you enter in their corresponding amount field.\n"
" If no outputs are specified here, the sender pays the fee.",
{
{"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
},
},
{"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"},
{"conf_target", RPCArg::Type::NUM, /* default */ "Fallback to wallet's confirmation target", "Confirmation target (in blocks)"},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
},
"options"},
{"bip32derivs", RPCArg::Type::BOOL, /* default */ "false", "If true, includes the BIP 32 derivation paths for public keys if we know them"},
},
RPCResult{
"{\n"
" \"psbt\": \"value\", (string) The resulting raw transaction (base64-encoded string)\n"
" \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
},
RPCExamples{
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("walletcreatefundedpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
},
}.ToString());
RPCTypeCheck(request.params, {
UniValue::VARR,
UniValueType(), // ARR or OBJ, checked later
UniValue::VNUM,
UniValue::VOBJ,
UniValue::VBOOL
}, true
);
CAmount fee;
int change_position;
CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]["replaceable"]);
FundTransaction(pwallet, rawTx, fee, change_position, request.params[3]);
// Make a blank psbt
PartiallySignedTransaction psbtx(rawTx);
// Fill transaction with out data but don't sign
bool bip32derivs = request.params[4].isNull() ? false : request.params[4].get_bool();
bool complete = true;
const TransactionError err = FillPSBT(pwallet, psbtx, complete, 1, false, bip32derivs);
if (err != TransactionError::OK) {
throw JSONRPCTransactionError(err);
}
// Serialize the PSBT
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << psbtx;
UniValue result(UniValue::VOBJ);
result.pushKV("psbt", EncodeBase64(ssTx.str()));
result.pushKV("fee", ValueFromAmount(fee));
result.pushKV("changepos", change_position);
return result;
}
UniValue abortrescan(const JSONRPCRequest& request); // in rpcdump.cpp
UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp
UniValue importprivkey(const JSONRPCRequest& request);
UniValue importaddress(const JSONRPCRequest& request);
UniValue importpubkey(const JSONRPCRequest& request);
UniValue dumpwallet(const JSONRPCRequest& request);
UniValue importwallet(const JSONRPCRequest& request);
UniValue importprunedfunds(const JSONRPCRequest& request);
UniValue removeprunedfunds(const JSONRPCRequest& request);
UniValue importmulti(const JSONRPCRequest& request);
// clang-format off
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "generating", "generate", &generate, {"nblocks","maxtries"} },
{ "hidden", "resendwallettransactions", &resendwallettransactions, {} },
{ "rawtransactions", "fundrawtransaction", &fundrawtransaction, {"hexstring","options","iswitness"} },
{ "wallet", "abandontransaction", &abandontransaction, {"txid"} },
{ "wallet", "abortrescan", &abortrescan, {} },
{ "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","label","address_type"} },
{ "wallet", "backupwallet", &backupwallet, {"destination"} },
{ "wallet", "bumpfee", &bumpfee, {"txid", "options"} },
{ "wallet", "createwallet", &createwallet, {"wallet_name", "disable_private_keys", "blank"} },
{ "wallet", "dumpprivkey", &dumpprivkey, {"address"} },
{ "wallet", "dumpwallet", &dumpwallet, {"filename"} },
{ "wallet", "encryptwallet", &encryptwallet, {"passphrase"} },
{ "wallet", "getaddressesbylabel", &getaddressesbylabel, {"label"} },
{ "wallet", "getaddressinfo", &getaddressinfo, {"address"} },
{ "wallet", "getbalance", &getbalance, {"dummy","minconf","include_watchonly"} },
{ "wallet", "getbalanceofaddress", &getbalanceofaddress, {"address"} },
{ "wallet", "getnewaddress", &getnewaddress, {"label","address_type"} },
{ "wallet", "getrawchangeaddress", &getrawchangeaddress, {"address_type"} },
{ "wallet", "getreceivedbyaddress", &getreceivedbyaddress, {"address","minconf"} },
{ "wallet", "getreceivedbylabel", &getreceivedbylabel, {"label","minconf"} },
{ "wallet", "gettransaction", &gettransaction, {"txid","include_watchonly", "waitconf"} },
{ "wallet", "getunconfirmedbalance", &getunconfirmedbalance, {} },
{ "wallet", "getwalletinfo", &getwalletinfo, {} },
{ "wallet", "importaddress", &importaddress, {"address","label","rescan","p2sh"} },
{ "wallet", "importmulti", &importmulti, {"requests","options"} },
{ "wallet", "importprivkey", &importprivkey, {"privkey","label","rescan"} },
{ "wallet", "importprunedfunds", &importprunedfunds, {"rawtransaction","txoutproof"} },
{ "wallet", "importpubkey", &importpubkey, {"pubkey","label","rescan"} },
{ "wallet", "importwallet", &importwallet, {"filename"} },
{ "wallet", "keypoolrefill", &keypoolrefill, {"newsize"} },
{ "wallet", "listaddressgroupings", &listaddressgroupings, {} },
{ "wallet", "listlabels", &listlabels, {"purpose"} },
{ "wallet", "listlockunspent", &listlockunspent, {} },
{ "wallet", "listreceivedbyaddress", &listreceivedbyaddress, {"minconf","include_empty","include_watchonly","address_filter"} },
{ "wallet", "listreceivedbylabel", &listreceivedbylabel, {"minconf","include_empty","include_watchonly"} },
{ "wallet", "listsinceblock", &listsinceblock, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
{ "wallet", "listtransactions", &listtransactions, {"label|dummy","count","skip","include_watchonly"} },
{ "wallet", "listunspent", &listunspent, {"minconf","maxconf","addresses","include_unsafe","query_options"} },
{ "wallet", "listwalletdir", &listwalletdir, {} },
{ "wallet", "listwallets", &listwallets, {} },
{ "wallet", "loadwallet", &loadwallet, {"filename"} },
{ "wallet", "lockunspent", &lockunspent, {"unlock","transactions"} },
{ "wallet", "removeprunedfunds", &removeprunedfunds, {"txid"} },
{ "wallet", "rescanblockchain", &rescanblockchain, {"start_height", "stop_height"} },
{ "wallet", "sendmany", &sendmany, {"dummy","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
{ "wallet", "sendmanywithdupes", &sendmanywithdupes, {"fromaccount","amounts","minconf","comment","subtractfeefrom"} },
{ "wallet", "sendtoaddress", &sendtoaddress, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode","senderAddress","changeToSender"} },
{ "wallet", "sethdseed", &sethdseed, {"newkeypool","seed"} },
{ "wallet", "setlabel", &setlabel, {"address","label"} },
{ "wallet", "settxfee", &settxfee, {"amount"} },
{ "wallet", "signmessage", &signmessage, {"address","message"} },
{ "wallet", "signrawtransactionwithwallet", &signrawtransactionwithwallet, {"hexstring","prevtxs","sighashtype"} },
{ "wallet", "signrawsendertransactionwithwallet", &signrawsendertransactionwithwallet, {"hexstring","sighashtype"} },
{ "wallet", "unloadwallet", &unloadwallet, {"wallet_name"} },
{ "wallet", "walletcreatefundedpsbt", &walletcreatefundedpsbt, {"inputs","outputs","locktime","options","bip32derivs"} },
{ "wallet", "walletlock", &walletlock, {} },
{ "wallet", "walletpassphrase", &walletpassphrase, {"passphrase","timeout","stakingonly"} },
{ "wallet", "walletpassphrasechange", &walletpassphrasechange, {"oldpassphrase","newpassphrase"} },
{ "wallet", "walletprocesspsbt", &walletprocesspsbt, {"psbt","sign","sighashtype","bip32derivs"} },
{ "wallet", "reservebalance", &reservebalance, {"reserve", "amount"} },
{ "wallet", "createcontract", &createcontract, {"bytecode", "gasLimit", "senderAddress", "broadcast", "changeToSender"} },
{ "wallet", "sendtocontract", &sendtocontract, {"contractaddress", "bytecode", "amount", "gasLimit", "senderAddress", "broadcast", "changeToSender"} },
};
// clang-format on
void RegisterWalletRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
|
#include <string>
#include <utility>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <esapp/segmenter.hpp>
namespace py = pybind11;
class py_list_inserter {
public:
explicit py_list_inserter(py::list &list) // NOLINT(runtime/references)
: list_(list) { /* do nothing */ }
py_list_inserter &operator=(std::string &&s) {
list_.append(std::move(s));
return *this;
}
py_list_inserter &operator*() { return *this; }
py_list_inserter &operator++() { return *this; }
py_list_inserter &operator++(int) { return *this; }
private:
py::list &list_;
};
PYBIND11_PLUGIN(esapp_python) {
py::module m("esapp_python");
py::class_<esapp::segmenter>(m, "Segmenter")
.def(py::init<double>())
.def("fit", [](esapp::segmenter &seg, std::string const &s) {
seg.fit(s.begin(), s.end());
})
.def("optimize", &esapp::segmenter::optimize)
.def("segment", [](esapp::segmenter const &seg, std::string const &s) {
py::list list;
seg.segment(s.begin(), s.end(), py_list_inserter(list));
return list;
});
return m.ptr();
}
|
/* $OpenBSD: ieee80211_proto.c,v 1.46 2012/01/18 14:35:56 stsp Exp $ */
/* $NetBSD: ieee80211_proto.c,v 1.8 2004/04/30 23:58:20 dyoung Exp $ */
/*-
* Copyright (c) 2001 Atsushi Onoe
* Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
* Copyright (c) 2008, 2009 Damien Bergamini
* All rights reserved.
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*
* IEEE 802.11 protocol support.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include "sys/endian.h"
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <net/if_arp.h>
#include <net/if_llc.h>
#if NBPFILTER > 0
#include <net/bpf.h>
#endif
#ifdef INET
#include <netinet/in.h>
#include <netinet/if_ether.h>
#endif
#include "Voodoo80211Device.h"
const char * const ieee80211_mgt_subtype_name[] = {
"assoc_req", "assoc_resp", "reassoc_req", "reassoc_resp",
"probe_req", "probe_resp", "reserved#6", "reserved#7",
"beacon", "atim", "disassoc", "auth",
"deauth", "action", "action_noack", "reserved#15"
};
const char * const ieee80211_state_name[IEEE80211_S_MAX] = {
"INIT", /* IEEE80211_S_INIT */
"SCAN", /* IEEE80211_S_SCAN */
"AUTH", /* IEEE80211_S_AUTH */
"ASSOC", /* IEEE80211_S_ASSOC */
"RUN" /* IEEE80211_S_RUN */
};
const char * const ieee80211_phymode_name[] = {
"auto", /* IEEE80211_MODE_AUTO */
"11a", /* IEEE80211_MODE_11A */
"11b", /* IEEE80211_MODE_11B */
"11g", /* IEEE80211_MODE_11G */
"turbo", /* IEEE80211_MODE_TURBO */
};
void Voodoo80211Device::
ieee80211_proto_attach(struct ieee80211com *ic)
{
// XXX: ifp->if_hdrlen = sizeof(struct ieee80211_frame);
// assuming that IO80211Interface automatically sets this (setMediaHeaderLength() is protected)
#ifdef notdef
ic->ic_rtsthreshold = IEEE80211_RTS_DEFAULT;
#else
ic->ic_rtsthreshold = IEEE80211_RTS_MAX;
#endif
ic->ic_fragthreshold = 2346; /* XXX not used yet */
ic->ic_fixed_rate = -1; /* no fixed rate */
ic->ic_protmode = IEEE80211_PROT_CTSONLY;
}
void Voodoo80211Device::
ieee80211_proto_detach(struct ieee80211com *ic)
{
//TODO ic->ic_mgtq->flush();
//TODO ic->ic_pwrsaveq->flush();
}
void Voodoo80211Device::
ieee80211_print_essid(const u_int8_t *essid, int len)
{
int i;
const u_int8_t *p;
if (len > IEEE80211_NWID_LEN)
len = IEEE80211_NWID_LEN;
/* determine printable or not */
for (i = 0, p = essid; i < len; i++, p++) {
if (*p < ' ' || *p > 0x7e)
break;
}
if (i == len) {
printf("\"");
for (i = 0, p = essid; i < len; i++, p++)
printf("%c", *p);
printf("\"");
} else {
printf("0x");
for (i = 0, p = essid; i < len; i++, p++)
printf("%02x", *p);
}
}
#ifdef IEEE80211_DEBUG
void Voodoo80211Device::
ieee80211_dump_pkt(const u_int8_t *buf, int len, int rate, int rssi)
{
struct ieee80211_frame *wh;
int i;
wh = (struct ieee80211_frame *)buf;
switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
case IEEE80211_FC1_DIR_NODS:
printf("NODS %s", ether_sprintf(wh->i_addr2));
printf("->%s", ether_sprintf(wh->i_addr1));
printf("(%s)", ether_sprintf(wh->i_addr3));
break;
case IEEE80211_FC1_DIR_TODS:
printf("TODS %s", ether_sprintf(wh->i_addr2));
printf("->%s", ether_sprintf(wh->i_addr3));
printf("(%s)", ether_sprintf(wh->i_addr1));
break;
case IEEE80211_FC1_DIR_FROMDS:
printf("FRDS %s", ether_sprintf(wh->i_addr3));
printf("->%s", ether_sprintf(wh->i_addr1));
printf("(%s)", ether_sprintf(wh->i_addr2));
break;
case IEEE80211_FC1_DIR_DSTODS:
printf("DSDS %s", ether_sprintf((u_int8_t *)&wh[1]));
printf("->%s", ether_sprintf(wh->i_addr3));
printf("(%s", ether_sprintf(wh->i_addr2));
printf("->%s)", ether_sprintf(wh->i_addr1));
break;
}
switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
case IEEE80211_FC0_TYPE_DATA:
printf(" data");
break;
case IEEE80211_FC0_TYPE_MGT:
printf(" %s", ieee80211_mgt_subtype_name[
(wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
>> IEEE80211_FC0_SUBTYPE_SHIFT]);
break;
default:
printf(" type#%d", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
break;
}
if (wh->i_fc[1] & IEEE80211_FC1_WEP)
printf(" WEP");
if (rate >= 0)
printf(" %d%sM", rate / 2, (rate & 1) ? ".5" : "");
if (rssi >= 0)
printf(" +%d", rssi);
printf("\n");
if (len > 0) {
for (i = 0; i < len; i++) {
if ((i & 1) == 0)
printf(" ");
printf("%02x", buf[i]);
}
printf("\n");
}
}
#endif
int Voodoo80211Device::
ieee80211_fix_rate(struct ieee80211com *ic, struct ieee80211_node *ni,
int flags)
{
#define RV(v) ((v) & IEEE80211_RATE_VAL)
int i, j, ignore, error;
int okrate, badrate, fixedrate;
const struct ieee80211_rateset *srs;
struct ieee80211_rateset *nrs;
u_int8_t r;
/*
* If the fixed rate check was requested but no fixed rate has been
* defined then just remove the check.
*/
if ((flags & IEEE80211_F_DOFRATE) && ic->ic_fixed_rate == -1)
flags &= ~IEEE80211_F_DOFRATE;
error = 0;
okrate = badrate = fixedrate = 0;
srs = &ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
nrs = &ni->ni_rates;
for (i = 0; i < nrs->rs_nrates; ) {
ignore = 0;
if (flags & IEEE80211_F_DOSORT) {
/*
* Sort rates.
*/
for (j = i + 1; j < nrs->rs_nrates; j++) {
if (RV(nrs->rs_rates[i]) >
RV(nrs->rs_rates[j])) {
r = nrs->rs_rates[i];
nrs->rs_rates[i] = nrs->rs_rates[j];
nrs->rs_rates[j] = r;
}
}
}
r = nrs->rs_rates[i] & IEEE80211_RATE_VAL;
badrate = r;
if (flags & IEEE80211_F_DOFRATE) {
/*
* Check fixed rate is included.
*/
if (r == RV(srs->rs_rates[ic->ic_fixed_rate]))
fixedrate = r;
}
if (flags & IEEE80211_F_DONEGO) {
/*
* Check against supported rates.
*/
for (j = 0; j < srs->rs_nrates; j++) {
if (r == RV(srs->rs_rates[j])) {
/*
* Overwrite with the supported rate
* value so any basic rate bit is set.
* This insures that response we send
* to stations have the necessary basic
* rate bit set.
*/
nrs->rs_rates[i] = srs->rs_rates[j];
break;
}
}
if (j == srs->rs_nrates) {
/*
* A rate in the node's rate set is not
* supported. If this is a basic rate and we
* are operating as an AP then this is an error.
* Otherwise we just discard/ignore the rate.
* Note that this is important for 11b stations
* when they want to associate with an 11g AP.
*/
ignore++;
}
}
if (flags & IEEE80211_F_DODEL) {
/*
* Delete unacceptable rates.
*/
if (ignore) {
nrs->rs_nrates--;
for (j = i; j < nrs->rs_nrates; j++)
nrs->rs_rates[j] = nrs->rs_rates[j + 1];
nrs->rs_rates[j] = 0;
continue;
}
}
if (!ignore)
okrate = nrs->rs_rates[i];
i++;
}
if (okrate == 0 || error != 0 ||
((flags & IEEE80211_F_DOFRATE) && fixedrate == 0))
return badrate | IEEE80211_RATE_BASIC;
else
return RV(okrate);
#undef RV
}
/*
* Reset 11g-related state.
*/
void Voodoo80211Device::
ieee80211_reset_erp(struct ieee80211com *ic)
{
ic->ic_flags &= ~IEEE80211_F_USEPROT;
ic->ic_nonerpsta = 0;
ic->ic_longslotsta = 0;
/*
* Enable short slot time iff:
* - we're operating in 802.11a or
* - we're operating in 802.11g and we're not in IBSS mode and
* the device supports short slot time
*/
ieee80211_set_shortslottime(ic,
ic->ic_curmode == IEEE80211_MODE_11A
);
if (ic->ic_curmode == IEEE80211_MODE_11A ||
(ic->ic_caps & IEEE80211_C_SHPREAMBLE))
ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
else
ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
}
/*
* Set the short slot time state and notify the driver.
*/
void Voodoo80211Device::
ieee80211_set_shortslottime(struct ieee80211com *ic, int on)
{
if (on)
ic->ic_flags |= IEEE80211_F_SHSLOT;
else
ic->ic_flags &= ~IEEE80211_F_SHSLOT;
/* notify the driver */
ieee80211_updateslot(ic);
}
/*
* This function is called by the 802.1X PACP machine (via an ioctl) when
* the transmit key machine (4-Way Handshake for 802.11) should run.
*/
int Voodoo80211Device::
ieee80211_keyrun(struct ieee80211com *ic, u_int8_t *macaddr)
{
/* STA must be associated or AP must be ready */
if (ic->ic_state != IEEE80211_S_RUN ||
!(ic->ic_flags & IEEE80211_F_RSNON))
return ENETDOWN;
return 0; /* supplicant only, do nothing */
}
#ifndef IEEE80211_NO_HT
void Voodoo80211Device::
ieee80211_tx_ba_timeout(void *arg)
{
struct ieee80211_tx_ba *ba = (struct ieee80211_tx_ba *)arg;
struct ieee80211_node *ni = ba->ba_ni;
struct ieee80211com *ic = ni->ni_ic;
u_int8_t tid;
int s;
s = splnet();
if (ba->ba_state == IEEE80211_BA_REQUESTED) {
/* MLME-ADDBA.confirm(TIMEOUT) */
ba->ba_state = IEEE80211_BA_INIT;
} else if (ba->ba_state == IEEE80211_BA_AGREED) {
/* Block Ack inactivity timeout */
tid = ((caddr_t)ba - (caddr_t)ni->ni_tx_ba) / sizeof(*ba);
ieee80211_delba_request(ic, ni, IEEE80211_REASON_TIMEOUT,
1, tid);
}
splx(s);
}
void Voodoo80211Device::
ieee80211_rx_ba_timeout(void *arg)
{
struct ieee80211_rx_ba *ba = (struct ieee80211_rx_ba *)arg;
struct ieee80211_node *ni = ba->ba_ni;
struct ieee80211com *ic = ni->ni_ic;
u_int8_t tid;
int s;
s = splnet();
/* Block Ack inactivity timeout */
tid = ((caddr_t)ba - (caddr_t)ni->ni_rx_ba) / sizeof(*ba);
ieee80211_delba_request(ic, ni, IEEE80211_REASON_TIMEOUT, 0, tid);
splx(s);
}
/*
* Request initiation of Block Ack with the specified peer.
*/
int Voodoo80211Device::
ieee80211_addba_request(struct ieee80211com *ic, struct ieee80211_node *ni,
u_int16_t ssn, u_int8_t tid)
{
struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
/* MLME-ADDBA.request */
/* setup Block Ack */
ba->ba_state = IEEE80211_BA_REQUESTED;
ba->ba_token = ic->ic_dialog_token++;
ba->ba_timeout_val = IEEE80211_BA_MAX_TIMEOUT;
timeout_set(ba->ba_to, OSMemberFunctionCast(VoodooTimeout::CallbackFunction, this, &Voodoo80211Device::ieee80211_tx_ba_timeout), ba);
ba->ba_winsize = IEEE80211_BA_MAX_WINSZ;
ba->ba_winstart = ssn;
ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
timeout_add_sec(ba->ba_to, 1); /* dot11ADDBAResponseTimeout */
IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
IEEE80211_ACTION_ADDBA_REQ, tid);
return 0;
}
/*
* Request the deletion of Block Ack with a peer.
*/
void Voodoo80211Device::
ieee80211_delba_request(struct ieee80211com *ic, struct ieee80211_node *ni,
u_int16_t reason, u_int8_t dir, u_int8_t tid)
{
/* MLME-DELBA.request */
/* transmit a DELBA frame */
IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
IEEE80211_ACTION_DELBA, reason << 16 | dir << 8 | tid);
if (dir) {
/* MLME-DELBA.confirm(Originator) */
struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
ieee80211_ampdu_tx_stop(ic, ni, tid);
ba->ba_state = IEEE80211_BA_INIT;
/* stop Block Ack inactivity timer */
timeout_del(ba->ba_to);
} else {
/* MLME-DELBA.confirm(Recipient) */
struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
int i;
ieee80211_ampdu_rx_stop(ic, ni, tid);
ba->ba_state = IEEE80211_BA_INIT;
/* stop Block Ack inactivity timer */
timeout_del(ba->ba_to);
if (ba->ba_buf != NULL) {
/* free all MSDUs stored in reordering buffer */
for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
if (ba->ba_buf[i].m != NULL)
mbuf_freem(ba->ba_buf[i].m);
/* free reordering buffer */
free(ba->ba_buf);
ba->ba_buf = NULL;
}
}
}
#endif /* !IEEE80211_NO_HT */
void Voodoo80211Device::
ieee80211_auth_open(struct ieee80211com *ic, const struct ieee80211_frame *wh,
struct ieee80211_node *ni, struct ieee80211_rxinfo *rxi, u_int16_t seq,
u_int16_t status)
{
// TODO struct ifnet *ifp = &ic->ic_if;
switch (ic->ic_opmode) {
case IEEE80211_M_STA:
if (ic->ic_state != IEEE80211_S_AUTH ||
seq != IEEE80211_AUTH_OPEN_RESPONSE) {
ic->ic_stats.is_rx_bad_auth++;
DPRINTF(("discard auth from %s; state %u, seq %u\n",
ether_sprintf((u_int8_t *)wh->i_addr2),
ic->ic_state, seq));
return;
}
if (ic->ic_flags & IEEE80211_F_RSNON) {
/* XXX not here! */
ic->ic_bss->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
ic->ic_bss->ni_port_valid = 0;
ic->ic_bss->ni_replaycnt_ok = 0;
ieee80211_delete_key(ic, ic->ic_bss,
&ic->ic_bss->ni_pairwise_key);
}
if (status != 0) {
/* TODO
if (ifp->if_flags & IFF_DEBUG)
printf("%s: open authentication failed "
"(reason %d) for %s\n", ifp->if_xname,
status,
ether_sprintf((u_int8_t *)wh->i_addr3));
*/
if (ni != ic->ic_bss)
ni->ni_fails++;
ic->ic_stats.is_rx_auth_fail++;
return;
}
ieee80211_newstate(ic, IEEE80211_S_ASSOC,
wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
break;
default:
break;
}
}
int Voodoo80211Device::
ieee80211_newstate(struct ieee80211com *ic, enum ieee80211_state nstate,
int mgt)
{
// TODO struct ifnet *ifp = &ic->ic_if;
struct ieee80211_node *ni;
enum ieee80211_state ostate;
// TODO u_int rate; (needed in debug printf below)
ostate = ic->ic_state;
DPRINTF(("%s -> %s\n", ieee80211_state_name[ostate],
ieee80211_state_name[nstate]));
ic->ic_state = nstate; /* state transition */
ni = ic->ic_bss; /* NB: no reference held */
if (ostate == IEEE80211_S_RUN)
ieee80211_set_link_state(ic, kIO80211NetworkLinkUp);
switch (nstate) {
case IEEE80211_S_INIT:
/*
* If mgt = -1, driver is already partway down, so do
* not send management frames.
*/
switch (ostate) {
case IEEE80211_S_INIT:
break;
case IEEE80211_S_RUN:
if (mgt == -1)
goto justcleanup;
switch (ic->ic_opmode) {
case IEEE80211_M_STA:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_DISASSOC,
IEEE80211_REASON_ASSOC_LEAVE);
break;
default:
break;
}
/* FALLTHROUGH */
case IEEE80211_S_ASSOC:
if (mgt == -1)
goto justcleanup;
switch (ic->ic_opmode) {
case IEEE80211_M_STA:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_DEAUTH,
IEEE80211_REASON_AUTH_LEAVE);
break;
default:
break;
}
/* FALLTHROUGH */
case IEEE80211_S_AUTH:
case IEEE80211_S_SCAN:
justcleanup:
ic->ic_mgt_timer = 0;
//TODO ic->ic_mgtq->flush();
//TODO ic->ic_pwrsaveq->flush();
ieee80211_free_allnodes(ic);
break;
}
break;
case IEEE80211_S_SCAN:
ic->ic_flags &= ~IEEE80211_F_SIBSS;
/* initialize bss for probe request */
IEEE80211_ADDR_COPY(ni->ni_macaddr, etherbroadcastaddr);
IEEE80211_ADDR_COPY(ni->ni_bssid, etherbroadcastaddr);
ni->ni_rates = ic->ic_sup_rates[
ieee80211_chan2mode(ic, ni->ni_chan)];
ni->ni_associd = 0;
ni->ni_rstamp = 0;
switch (ostate) {
case IEEE80211_S_INIT:
ieee80211_begin_scan(ic);
break;
case IEEE80211_S_SCAN:
/* scan next */
if (ic->ic_flags & IEEE80211_F_ASCAN) {
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_PROBE_REQ, 0);
}
break;
case IEEE80211_S_RUN:
/* beacon miss */
// TODO
//if (ifp->if_flags & IFF_DEBUG) {
// /* XXX bssid clobbered above */
// printf("%s: no recent beacons from %s;"
// " rescanning\n", ifp->if_xname,
// ether_sprintf(ic->ic_bss->ni_bssid));
//}
ieee80211_free_allnodes(ic);
/* FALLTHROUGH */
case IEEE80211_S_AUTH:
case IEEE80211_S_ASSOC:
/* timeout restart scan */
ni = ieee80211_find_node(ic, ic->ic_bss->ni_macaddr);
if (ni != NULL)
ni->ni_fails++;
ieee80211_begin_scan(ic);
break;
}
break;
case IEEE80211_S_AUTH:
switch (ostate) {
case IEEE80211_S_INIT:
DPRINTF(("invalid transition\n"));
break;
case IEEE80211_S_SCAN:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_AUTH, 1);
break;
case IEEE80211_S_AUTH:
case IEEE80211_S_ASSOC:
switch (mgt) {
case IEEE80211_FC0_SUBTYPE_AUTH:
/* ??? */
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_AUTH, 2);
break;
case IEEE80211_FC0_SUBTYPE_DEAUTH:
/* ignore and retry scan on timeout */
break;
}
break;
case IEEE80211_S_RUN:
switch (mgt) {
case IEEE80211_FC0_SUBTYPE_AUTH:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_AUTH, 2);
ic->ic_state = ostate; /* stay RUN */
break;
case IEEE80211_FC0_SUBTYPE_DEAUTH:
/* try to reauth */
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_AUTH, 1);
break;
}
break;
}
break;
case IEEE80211_S_ASSOC:
switch (ostate) {
case IEEE80211_S_INIT:
case IEEE80211_S_SCAN:
case IEEE80211_S_ASSOC:
DPRINTF(("invalid transition\n"));
break;
case IEEE80211_S_AUTH:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_ASSOC_REQ, 0);
break;
case IEEE80211_S_RUN:
IEEE80211_SEND_MGMT(ic, ni,
IEEE80211_FC0_SUBTYPE_ASSOC_REQ, 1);
break;
}
break;
case IEEE80211_S_RUN:
switch (ostate) {
case IEEE80211_S_INIT:
case IEEE80211_S_AUTH:
case IEEE80211_S_RUN:
DPRINTF(("invalid transition\n"));
break;
case IEEE80211_S_SCAN: /* adhoc/hostap mode */
case IEEE80211_S_ASSOC: /* infra mode */
if (ni->ni_txrate >= ni->ni_rates.rs_nrates)
panic("%s: bogus xmit rate %u setup",
__func__, ni->ni_txrate);
/* TODO
if (ifp->if_flags & IFF_DEBUG) {
printf("%s: %s with %s ssid ",
ifp->if_xname,
ic->ic_opmode == IEEE80211_M_STA ?
"associated" : "synchronized",
ether_sprintf(ni->ni_bssid));
ieee80211_print_essid(ic->ic_bss->ni_essid,
ni->ni_esslen);
rate = ni->ni_rates.rs_rates[ni->ni_txrate] &
IEEE80211_RATE_VAL;
printf(" channel %d start %u%sMb",
ieee80211_chan2ieee(ic, ni->ni_chan),
rate / 2, (rate & 1) ? ".5" : "");
printf(" %s preamble %s slot time%s\n",
(ic->ic_flags & IEEE80211_F_SHPREAMBLE) ?
"short" : "long",
(ic->ic_flags & IEEE80211_F_SHSLOT) ?
"short" : "long",
(ic->ic_flags & IEEE80211_F_USEPROT) ?
" protection enabled" : "");
}
*/
if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
/*
* NB: When RSN is enabled, we defer setting
* the link up until the port is valid.
*/
fInterface->postMessage(APPLE80211_M_ASSOC_DONE);
ieee80211_set_link_state(ic, kIO80211NetworkLinkUp);
}
ic->ic_mgt_timer = 0;
fOutputQueue->start();
break;
}
break;
}
return 0;
}
void Voodoo80211Device::
ieee80211_set_link_state(struct ieee80211com *ic, IO80211LinkState nstate)
{
switch (ic->ic_opmode) {
case IEEE80211_M_MONITOR:
nstate = kIO80211NetworkLinkDown;
break;
default:
break;
}
fInterface->setLinkState((IO80211LinkState) nstate, 0);
}
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, 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.
*/
#include "executors.h"
#include <daemon/cookie.h>
#include <daemon/mc_time.h>
#include <memcached/protocol_binary.h>
#include <platform/platform_time.h>
/**
* The adjust_timeofday_executor implements the ability to mock the internal
* clock in the memcached server. It is only used during unit testing of
* the server (over the network), and the validator will return NOT_SUPPORTED
* unless the environment variable MEMCACHED_UNIT_TESTS is set.
*/
void adjust_timeofday_executor(Cookie& cookie) {
auto extras = cookie.getRequest().getExtdata();
using cb::mcbp::request::AdjustTimePayload;
auto* payload = reinterpret_cast<const AdjustTimePayload*>(extras.data());
switch (payload->getTimeType()) {
case AdjustTimePayload::TimeType::TimeOfDay:
cb_set_timeofday_offset(gsl::narrow_cast<int>(payload->getOffset()));
mc_time_clock_tick();
cookie.sendResponse(cb::mcbp::Status::Success);
return;
case AdjustTimePayload::TimeType::Uptime:
cb_set_uptime_offset(payload->getOffset());
mc_time_clock_tick();
cookie.sendResponse(cb::mcbp::Status::Success);
return;
}
cookie.sendResponse(cb::mcbp::Status::Einval);
}
|
#include "executor.hpp"
#include <cstdint>
#include <stdexcept>
using namespace quickcalc;
Executor::Executor(): NodeVisitor() {
pushState();
}
Executor::Executor(NodeVisitor *next): NodeVisitor(next) {
pushState();
}
void Executor::visit(ExprStmtNode *node) {
_lastResult = evaluate(node->expression());
_hasResult = true;
}
void Executor::visit(FuncDefNode *node) {
getState().setFunction(node->name(), [node] (Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
ExecutorState &newState = exec.pushState();
for (int i = 0; i < params.size() && i < node->paramNames().size(); i++) {
const ExprNode::ptr &ast = params[i];
newState.setFunction(node->paramNames()[i], [&ast] (Executor &exec, const std::vector<ExprNode::ptr> &) {
ExecutorState prevState = exec.popState();
double val = exec.evaluate(ast.get());
exec.pushState(std::move(prevState));
return val;
});
}
double result = exec.evaluate(node->expression());
exec.popState();
return result;
});
_hasResult = false;
}
void Executor::visit(ConstNode *node) {
_valueStack.push(node->value());
}
void Executor::visit(UnaryOperationNode *node) {
node->value()->accept(*this);
double value = pop();
switch (node->operation()) {
case UnaryOperation::NEGATE:
push(-value);
break;
case UnaryOperation::NOT:
push(~static_cast<int32_t>(value));
break;
}
}
void Executor::visit(BinaryOperationNode *node) {
node->lhs()->accept(*this);
node->rhs()->accept(*this);
double rhs = pop();
double lhs = pop();
double result;
switch (node->operation()) {
case BinaryOperation::ADD:
result = lhs + rhs;
break;
case BinaryOperation::SUBTRACT:
result = lhs - rhs;
break;
case BinaryOperation::MULTIPLY:
result = lhs * rhs;
break;
case BinaryOperation::DIVIDE:
result = lhs / rhs;
break;
case BinaryOperation::AND:
result = static_cast<int32_t>(lhs) & static_cast<int32_t>(rhs);
break;
case BinaryOperation::OR:
result = static_cast<int32_t>(lhs) | static_cast<int32_t>(rhs);
break;
case BinaryOperation::XOR:
result = static_cast<int32_t>(lhs) ^ static_cast<int32_t>(rhs);
break;
}
push(result);
}
void Executor::visit(FunctionInvocationNode *node) {
const ExecutorState::Func *func;
if (getState().tryGetFunction(node->name(), func)) {
push((*func)(*this, node->params()));
} else {
throw std::runtime_error("Undefined function " + node->name());
}
}
double Executor::evaluate(ExprNode *node) {
node->accept(*this);
return pop();
}
double Executor::lastResult() const {
return _lastResult;
}
bool Executor::hasResult() const {
return _hasResult;
}
void Executor::push(double value) {
_valueStack.push(value);
}
double Executor::pop() {
double value = _valueStack.top();
_valueStack.pop();
return value;
}
ExecutorState &Executor::getState() {
return _stateStack.top();
}
ExecutorState &Executor::pushState() {
if (_stateStack.empty()) {
return _stateStack.emplace();
} else {
return _stateStack.emplace(&_stateStack.top());
}
}
ExecutorState &Executor::pushState(const ExecutorState &state) {
ExecutorState *parent = _stateStack.empty() ? nullptr :&_stateStack.top();
ExecutorState &newstate = _stateStack.emplace(state);
newstate._parent = parent;
return newstate;
}
ExecutorState &Executor::pushState(ExecutorState &&state) {
state._parent = _stateStack.empty() ? nullptr :&_stateStack.top();
return _stateStack.emplace(std::move(state));
}
ExecutorState Executor::popState() {
ExecutorState state = std::move(_stateStack.top());
_stateStack.pop();
return state;
}
ExecutorState::ExecutorState(): ExecutorState(nullptr) {
}
ExecutorState::ExecutorState(ExecutorState *parent): _parent(parent) {
}
void ExecutorState::setFunction(const std::string &name, const Func &function) {
_funcMap[name] = function;
}
void ExecutorState::setFunction(const std::string &name, Func &&function) {
_funcMap[name] = std::move(function);
}
void ExecutorState::setFunction(std::string &&name, Func &&function) {
_funcMap[std::move(name)] = std::move(function);
}
const ExecutorState::Func &ExecutorState::getFunction(const std::string &name) const {
const Func *func;
if (tryGetFunction(name, func)) {
return *func;
} else {
throw std::logic_error("Couldn't find function " + name);
}
}
bool ExecutorState::hasFunction(const std::string &name) const {
const Func *func;
return tryGetFunction(name, func);
}
bool ExecutorState::tryGetFunction(const std::string &name, const Func *&function) const {
auto it = _funcMap.find(name);
if (it != _funcMap.end()) {
function = &it->second;
return true;
} else if (_parent) {
return _parent->tryGetFunction(name, function);
} else {
return false;
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <dsn/cpp/message_utils.h>
#include <dsn/dist/replication/replication.codes.h>
#include <dsn/cpp/rpc_holder.h>
#include <gtest/gtest.h>
using namespace dsn;
DEFINE_TASK_CODE_RPC(RPC_CODE_FOR_TEST, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)
typedef rpc_holder<configuration_query_by_index_request, configuration_query_by_index_response>
t_rpc;
TEST(message_utils, msg_blob_convertion)
{
std::string data = "hello";
blob b(data.c_str(), 0, data.size());
dsn::message_ex *m = from_blob_to_received_msg(RPC_CODE_FOR_TEST, std::move(b));
ASSERT_EQ(m->header->body_length, data.size());
ASSERT_EQ(b.to_string(), move_message_to_blob(m).to_string());
}
TEST(message_utils, thrift_msg_convertion)
{
configuration_query_by_index_request request;
request.app_name = "haha";
dsn::message_ex *msg =
from_thrift_request_to_received_message(request, RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX);
t_rpc rpc(msg);
ASSERT_EQ(rpc.request().app_name, "haha");
}
TEST(message_utils, complex_convertion)
{
configuration_query_by_index_request request;
request.app_name = "haha";
dsn::message_ex *msg =
from_thrift_request_to_received_message(request, RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX);
blob b = move_message_to_blob(msg);
msg = from_blob_to_received_msg(RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX, std::move(b));
t_rpc rpc(msg);
ASSERT_EQ(rpc.request().app_name, "haha");
}
|
/*
Copyright 2016 AllThingsTalk
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.
*/
#include "ATT_LoRaWAN_TRACKTRACE.h"
#include <Wire.h>
#define BATTERY_REPORT_SEC 59 //determins how frequently the interrupt clock wakes up to send battery stats.
#define BATTERY_REPORT_MIN 59
#define BATTERY_REPORT_HOUR 23
#define BATTERY_REPORT_EVERY RTCZero::MATCH_MMSS //MATCH_HHMMSS
//These constants are used for reading the battery voltage
#define ADC_AREF 3.3
#define BATVOLT_PIN BAT_VOLT
#define BATVOLT_R1 4.7
#define BATVOLT_R2 10
#define SENDBATTERYEVERY 86400000 //send battery every 24 hours, used to check time if we missed a hartbeat from the interrupt clock.
/**
* Turns the led on according to the given color. Makes no assumptions about the status of the pins
* i.e. it sets them every time,
*/
void setLedColor(LedColor color)
{
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
digitalWrite(LED_RED, HIGH);
digitalWrite(LED_GREEN, HIGH);
digitalWrite(LED_BLUE, HIGH);
switch (color)
{
case NONE:
break;
case RED:
digitalWrite(LED_RED, LOW);
break;
case GREEN:
digitalWrite(LED_GREEN, LOW);
break;
case BLUE:
digitalWrite(LED_BLUE, LOW);
break;
case YELLOW:
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, LOW);
break;
case MAGENTA:
digitalWrite(LED_BLUE, LOW);
digitalWrite(LED_RED, LOW);
break;
case CYAN:
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_BLUE, LOW);
break;
case WHITE:
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, LOW);
digitalWrite(LED_BLUE, LOW);
break;
default:
break;
}
}
//power
void initPower()
{
pinMode(ENABLE_PIN_IO, OUTPUT);
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; //prepare the board for deep sleep mode.
}
void setGPSPower(int8_t value)
{
digitalWrite(GPS_ENABLE, value);
}
void setPower(int8_t value)
{
digitalWrite(ENABLE_PIN_IO, value);
}
// wire communication
#define ACCEL_ADR 0b0011110
uint8_t writeReg(uint8_t reg, uint8_t val)
{
Wire.beginTransmission(ACCEL_ADR);
Wire.write(reg);
Wire.write(val);
Wire.endTransmission();
delayMicroseconds(10000);
}
uint8_t readReg(uint8_t reg)
{
Wire.beginTransmission(ACCEL_ADR);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(ACCEL_ADR, 0x01);
uint8_t val = Wire.read();
Wire.endTransmission();
return val;
}
//board
volatile bool _reportMovement = false;
volatile bool _reportMagneto = false;
void onAccelInterrupt()
{
_reportMovement = true;
}
void onMagnetoInterrupt()
{
_reportMagneto = true;
}
void initAcceleroInterrupts()
{
pinMode(ACCEL_INT1, INPUT_PULLUP);
pinMode(ACCEL_INT2, INPUT_PULLUP);
attach(ACCEL_INT1, onAccelInterrupt, FALLING);
attach(ACCEL_INT2, onAccelInterrupt, FALLING);
}
void attach(int pin, voidFuncPtr callback, int mode)
{
attachInterrupt(pin, callback, mode);
//has to be set after first call to attachinterrupt
SYSCTRL->XOSC32K.bit.RUNSTDBY = 1; // Set the XOSC32K to run in standby
//possibly that we have to do |= in the next statement, to keep the settings done by the rtczero timer.
GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(GCM_EIC) | GCLK_CLKCTRL_GEN_GCLK1 | GCLK_CLKCTRL_CLKEN;// Configure EIC to use GCLK1 which uses XOSC32K
}
//returns true if the accelerometer reported movement
//resets the switch so that new movement can be detected on the next run.
bool hasMoved()
{
if (_reportMovement) {
_reportMovement = false;
return true;
}
return false;
}
//returns true if the accelerometer reported a change in the magnetic field
//resets the switch so that a new change can be detected on the next run.
bool magnetoChanged()
{
if (_reportMagneto) {
_reportMagneto = false;
return true;
}
return false;
}
void disableUSB()
{
USB->DEVICE.CTRLA.reg &= ~USB_CTRLA_ENABLE;
}
void enableUSB()
{
USB->DEVICE.CTRLA.reg |= USB_CTRLA_ENABLE;
}
//put the device is a deep sleep mode.
void sleep()
{
delay(180);
//disableUSB();
__WFI(); //Enter sleep mode
//...Sleep forever or until interupt has arrived.
//enableUSB();
delay(180); //after waking up, give the device a little bit of time to wake up, if we don't do this, the serial will block and the first call to SerialUSB will make the app fail.
}
//battery
int batteryStatus()
{
SerialUSB.println("reporting battery status");
uint16_t batteryVoltage = analogRead(BATVOLT_PIN);
uint16_t battery = (ADC_AREF / 1.023) * (BATVOLT_R1 + BATVOLT_R2) / BATVOLT_R2 * (float)batteryVoltage;
battery = (uint16_t)((100.0/ 1200.) * (float) (battery-3000));
if (battery > 100)
battery = 100;
SerialUSB.print("level: "); SerialUSB.println(battery);
return battery;
}
|
//
// Created by david on 28/12/2019.
//
#include "testbench.h"
#include <cmath>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
#include <list>
#include <set>
#include <random>
#include <chrono>
#include <utils/Randoms.h>
#include <utils/BitSet.h>
#include <typing/TypeInfos.h>
#include <typing/iterator.h>
#include "typing/TypeInfo.h"
#include <boost/format.hpp>
#include <boost/any.hpp>
using std::cout, std::unordered_map, std::vector, std::set, std::list, std::string;
int getFIndex(unsigned long a) {
for (int i = 0; i < 64; i++) {
if (a & 1) return i;
a = a >> 1;
}
return -1;
}
int getCIndex(unsigned long a) {
return (int) log2(a);
}
unordered_map<unsigned long, int> init_map() {
unordered_map<unsigned long, int> res;
unsigned long a = 1;
for (int i = 0; i < 64; i++) {
res[a] = i;
a = a << 1;
}
return res;
}
int getLIndex(unsigned long a) {
static auto lookup_table = init_map();
return lookup_table[a];
}
void algo() {
const int COMPONENTS = 10000000;
const int CLICKS = 1000;
const int W = 1920;
const int H = 1080;
vector<BitSet> ys;
vector<BitSet> xs;
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> distx(0, W); // distribution in range [1, 6]
std::uniform_int_distribution<std::mt19937::result_type> disty(0, H); // distribution in range [1, 6]
std::uniform_int_distribution<std::mt19937::result_type> distw(10, 10); // distribution in range [1, 6]
std::uniform_int_distribution<std::mt19937::result_type> disth(10, 10); // distribution in range [1, 6]
cout << "Initializing sets\n";
for (int ix = 0; ix <= W; ix++)
xs.emplace_back(COMPONENTS);
for (int iy = 0; iy <= H; iy++)
ys.emplace_back(COMPONENTS);
cout << "Populating sets\n";
/*vector<Context *> contexts;
for (int i = 0; i < COMPONENTS; i++) {
contexts.push_back(new Context(Randoms::random_string()));
}*/
int area = 1;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < COMPONENTS; i++) {
int x = distx(rng);
int y = disty(rng);
int w = distw(rng);
int h = disth(rng);
area += w + h;
for (int ix = x; ix < x + w && ix < W; ix++)
xs[ix].set(i);
for (int iy = y; iy < y + h && iy < H; iy++)
ys[iy].set(i);
}
auto finish = std::chrono::high_resolution_clock::now();
std::cout << "Area: " << area << " Time/100px: "
<< std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / (1000.0f * area / 100)
<< " in "
<< std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / 1000.0f
<< " ms\n";
int avg_fill = 0;
for (int ix = 0; ix < W; ix++)
avg_fill += xs[ix].count();
for (int iy = 0; iy < H; iy++)
avg_fill += ys[iy].count();
cout << "avg_fill:" << avg_fill / (W + H) << "\n";
vector<int> txs;
vector<int> tys;
for (int i = 0; i < CLICKS; i++) {
txs.push_back(distx(rng));
tys.push_back(disty(rng));
}
int intersections = 0;
cout << "Intersecting sets\n";
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < CLICKS; i++) {
intersections += xs[txs[i]].fintersect(ys[tys[i]]);
}
finish = std::chrono::high_resolution_clock::now();
std::cout << "Intersections: " << intersections / (1.0f * CLICKS) << " in "
<< std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / (1000.0f * CLICKS)
<< " ms\n";
}
void test_indexing() {
int SAMPLES;
std::cin >> SAMPLES;
vector<unsigned long> l;
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(0, 63); // distribution in range [1, 6]
unsigned long one = 1;
for (int i = 0; i < SAMPLES; i++)
l.push_back(one << dist6(rng));
// Record start time
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < SAMPLES; i++) {
if (getFIndex(l[i]) < 0)
cout << "negative\n";
}
auto finish = std::chrono::high_resolution_clock::now();
std::cout << "For: " << std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / 1000.0f
<< " ms\n";
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < SAMPLES; i++) {
if (getCIndex(l[i]) < 0)
cout << "negative\n";
}
finish = std::chrono::high_resolution_clock::now();
std::cout << "Calculated: "
<< std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / 1000.0f << " ms\n";
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < SAMPLES; i++) {
if (getLIndex(l[i]) < 0)
cout << "negative\n";
}
finish = std::chrono::high_resolution_clock::now();
std::cout << "Lookup: " << std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / 1000.0f
<< " ms\n";
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < SAMPLES; i++) {
if (SAMPLES < 200) {
if (getFIndex(l[i]) < 0)
cout << "negative\n";
} else {
if (getCIndex(l[i]) < 0)
cout << "negative\n";
}
}
finish = std::chrono::high_resolution_clock::now();
std::cout << "Best: " << std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() / 1000.0f
<< " ms\n";
}
void indirect_tb() {
vector<int> original;
vector<int> first;
vector<int> second;
vector<int> third;
int N = 100000000;
for (int i = 0; i < N; i++) {
original.push_back(i);
first.push_back(original[i]);
second.push_back(first[i]);
third.push_back(second[i]);
}
int total = 0;
auto t0 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++) {
total += original[first[second[third[i]]]];
}
auto t1 = std::chrono::high_resolution_clock::now();
cout << "Avg time:"
<< static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()) / 1000
<< ", ans: " << total << "\n";
total = 0;
t0 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++) {
total += original[first[i]];
}
t1 = std::chrono::high_resolution_clock::now();
cout << "Avg time:"
<< static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()) / 1000
<< ", ans: " << total << "\n";
total = 0;
t0 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++) {
total += original[first[second[i]]];
}
t1 = std::chrono::high_resolution_clock::now();
cout << "Avg time:"
<< static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()) / 1000
<< ", ans: " << total << "\n";
total = 0;
t0 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < N; i++) {
total += original[i];
}
t1 = std::chrono::high_resolution_clock::now();
cout << "Avg time:"
<< static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()) / 1000
<< ", ans: " << total << "\n";
//fatal_error();
}
void TB::run_windowing() {
algo();
}
void TB::run_anyvector() {
struct banana {
int a;
int b;
int c;
};
using std::vector;
using boost::any, boost::any_cast;
vector<any> myvec;
myvec.reserve(10);
printf("\n first: %p \n second: %p \n 10th: %p \n", &myvec[0], &myvec[1], &myvec[2]);
struct banana ban = {1, 2, 3};
myvec[0] = (char) 5;
myvec[1] = ban;
myvec[2] = (double) 5.0;
printf("\n first: %p \n second: %p \n 10th: %p \n", &myvec[0], &myvec[1], &myvec[2]);
void *p = &myvec[1];
printf("\n a: %d \n b: %p \n c: %p \n", any_cast<struct banana>(myvec[1]).c, &myvec[1], &myvec[2]);
}
void TB::deallocating() {
using namespace std;
const int size = 100000000;
double *buffy = new double[size];
for (int i = 0; i < size; i++)
buffy[i] = i * 1.2;
cout << "deallocate?\n";
double sum = 0.0;
for (int i = 0; i < size; i++)
sum += buffy[i];
cout << sum << endl;
int a;
cin >> a;
void *p = buffy;
delete[] p;
cin >> a;
}
template<typename T, size_t offset>
T *access(void *pointy) {
return (T *) ((char *) pointy + offset);
}
void TB::fancy_types() {
void *mymem = new char[sizeof(int) + sizeof(double) + 10];
auto myint = &access<int, 0>;
auto mydouble = &access<double, sizeof(int)>;
auto mystring = &access<char, sizeof(int) + sizeof(double)>;
*myint(mymem) = 10;
*mydouble(mymem) = 10.0 / 7;
memset(mystring(mymem), 0, *myint(mymem));
strcpy(mystring(mymem), "hello");
cout << *myint(mymem) << " " << *mydouble(mymem) << " " << mystring(mymem);
}
namespace FancyTyping {
template<typename... Types>
size_t size_sum() {
return (sizeof(Types)+...);
}
template<>
size_t size_sum() {
return 0;
}
template<typename T, typename... Types>
T *access(void *mem) {
return (T *) ((char *) mem + size_sum<Types...>());
}
template<void *mem, typename T, typename... Types>
T *access() {
return (T *) ((char *) mem + size_sum<Types...>());
}
template<typename... Types>
void *allocate() {
return new char[size_sum<Types...>()];
}
template<typename... Types>
void copy(void *dest, void *src) {
memcpy(dest, src, size_sum<Types...>());
}
}
class FancyNode {
public:
static constexpr auto create = &FancyTyping::allocate<int, double>;
static constexpr auto copy = &FancyTyping::copy<int, double>;
static constexpr auto age = &FancyTyping::access<int>;
static constexpr auto kg = &FancyTyping::access<double, int>;
void *mem;
operator void *() {
return this;
}
FancyNode() {
mem = create();
}
FancyNode(void *mem) {
this->mem = create();
copy(this->mem, mem);
}
};
void TB::fancy_access() {
void *mem = FancyNode::create();
*FancyNode::age(mem) = 11;
*FancyNode::kg(mem) = 60.15 + *FancyNode::age(mem);
cout << *FancyNode::age(mem) << " " << *FancyNode::kg(mem) << "\n";
auto not_pointy = (FancyNode) mem;
cout << *not_pointy.age(not_pointy) << " " << *not_pointy.kg(not_pointy) << "\n";
cout << *not_pointy.age(not_pointy) << " " << *not_pointy.kg(not_pointy) << "\n";
//FancyNode dupl1(not_pointy);
FancyNode dupl2(mem);
/*
//*dupl1.age() = 7;
*dupl2.kg() = 30.2;
//cout << *dupl1.age() << " " << *dupl1.kg() << "\n";
cout << *dupl2.age() << " " << *dupl2.kg() << "\n";
not_pointy._age(¬_pointy);
*/
}
class FancierNode {
public:
void *mem;
FancyTypes::TypeInfo *t;
FancierNode(FancyTypes::TypeInfo &type) {
this->t = &type;
mem = t->create();
t->initialize(mem);
}
template<typename A>
A access() {
return (A) mem;
}
/*template<typename T, FancyTypes::t_iterator<T> f_iterator, FancyTypes::t_access<T> f_access, FancyTypes::TypeInfo &typeinfo>
operator FancyTypes::TypeAccess<T, f_iterator, f_access, typeinfo>() {
return (FancyTypes::TypeAccess<T, f_iterator, f_access, typeinfo>) mem;
}*/
};
void TB::typeinfo() {
using namespace FancyTypes;
#if 0
FancierNode node(int_i);
int_t myint = node;
myint = 5;
cout << "myint: " << myint << "\n";
auto myotherint = (int_t) node;
cout << "myotherint: " << myotherint << "\n";
myotherint = 7;
cout << "myint: " << myint << "\n";
#endif
FancierNode node(uninfo_i);
string_t st = string("hello");
cout << st << "\n";
uninfo_t info = node.mem;
info = {"Bernadette", 4, 1, 3};
uninfo_t info2 = {"Bernadette", 2, 1, 3};
uninfo_t info3 = *info + *info2;
vector<float> myfile(1000);
for (int i = 0; i < 1000; i++)
myfile[i] = i / 3.0f;
for (int y = 0; y < 10; y++)
for (int x = 0; x < 10; x++)
cout << myfile[y * 10 + x] << " ";
cout << "\n";
iterator dim2(myfile, 10, 10, 3);
for (int y = 0; y < 10; y++)
for (int x = 0; x < 10; x++)
cout << dim2(1, y, x) << " ";
/*auto l = I(info).length;
cout << info->length << " = " << l << "\n";*/
cout << info.toString() << "\n";
cout << info3.toString() << "\n";
cout << "glm tests \n";
vec3_t a({1.0, 0.5, 0.5});
vec3_t b({1.0, 0.5, 1.33});
vec3_t c = *a + *b;
cout << c;
cout << "\nDone.";
}
// Oh the lag..
/*
#define EVAL0(...) __VA_ARGS__
#define EVAL1(...) EVAL0(EVAL0(EVAL0(__VA_ARGS__)))
#define EVAL2(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))
#define EVAL3(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))
#define EVAL4(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))
#define EVAL(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))
#define MAP_END(...)
#define MAP_OUT
#define MAP_COMMA ,
#define MAP_GET_END2() 0, MAP_END
#define MAP_GET_END1(...) MAP_GET_END2
#define MAP_GET_END(...) MAP_GET_END1
#define MAP_NEXT0(test, next, ...) next MAP_OUT
#define MAP_NEXT1(test, next) MAP_NEXT0(test, next, 0)
#define MAP_NEXT(test, next) MAP_NEXT1(MAP_GET_END test, next)
#define MAP0(f, x, peek, ...) f(x) MAP_NEXT(peek, MAP1)(f, peek, __VA_ARGS__)
#define MAP1(f, x, peek, ...) f(x) MAP_NEXT(peek, MAP0)(f, peek, __VA_ARGS__)
#define MAP_LIST_NEXT1(test, next) MAP_NEXT0(test, MAP_COMMA next, 0)
#define MAP_LIST_NEXT(test, next) MAP_LIST_NEXT1(MAP_GET_END test, next)
#define MAP_LIST0(f, x, peek, ...) f(x) MAP_LIST_NEXT(peek, MAP_LIST1)(f, peek, __VA_ARGS__)
#define MAP_LIST1(f, x, peek, ...) f(x) MAP_LIST_NEXT(peek, MAP_LIST0)(f, peek, __VA_ARGS__)
#define MAP_2P0(f, x, y, peek, ...) f(x, y) MAP_NEXT(peek, MAP_2P1)(f, peek, __VA_ARGS__)
#define MAP_2P1(f, x, y, peek, ...) f(x, y) MAP_NEXT(peek, MAP_2P0)(f, peek, __VA_ARGS__)
#define MAP_2P_LIST0(f, x, y, peek, ...) f(x, y) MAP_LIST_NEXT(peek, MAP_2P_LIST1)(f, peek, __VA_ARGS__)
#define MAP_2P_LIST1(f, x, y, peek, ...) f(x, y) MAP_LIST_NEXT(peek, MAP_2P_LIST0)(f, peek, __VA_ARGS__)
#define MAP_2P(f, ...) EVAL(MAP_2P1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define MAP_2P_LIST(f, ...) EVAL(MAP_2P_LIST1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define MAP(f, ...) EVAL(MAP1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define MAP_LIST(f, ...) EVAL(MAP_LIST1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define STRINGIFY(x) #x
#define CALL(x, y) printf(STRINGIFY(x))
*/
void TB::macro_parenthesis() {
//MAP_2P_LIST(CALL, a, b, c, d);
}
template<typename T, template<typename...> typename Template>
struct is_specialization : std::false_type {
};
template<template<typename...> typename Template, typename... Args>
struct is_specialization<Template<Args...>, Template> : std::true_type {
};
//template <typename T, template <typename...> typename Template>
//using is_specialization_v = typename is_specialization<T, Template>::value;
template<int N, typename... Args>
struct nth_arg;
template<typename Head, typename... Rest>
struct nth_arg<0, Head, Rest...> {
typedef Head type;
};
template<int N, typename Head, typename... Rest>
struct nth_arg<N, Head, Rest...> {
typedef typename nth_arg<N - 1, Rest...>::type type;
};
template<typename S, template<typename...> typename T>
struct argument_extractor;
template<template<typename...> typename C, typename... Args>
struct argument_extractor<C<Args...>, C> {
template<int N>
using nth_arg = typename nth_arg<N, Args...>::type;
};
/*
inline typename std::enable_if<(not std::is_same<T, int>::value)
and (not std::is_same<T, float>::value), void>::type
*/
/*
template <template <typename> typename C, typename T>
constexpr inline typename std::enable_if<std::is_pointer<C<T>>::value, int>::type
gimme_info(){
auto content = gimme_info<std::remove_pointer_t<C<T>>>();
return 200 + content;
}
template <template <typename> typename C, typename T>
constexpr inline typename std::enable_if<not std::is_pointer<C<T>>::value, int>::type
gimme_info(){}
*/
template<typename, typename Condition=void>
struct gimme_info;
template<>
struct gimme_info<int> {
static constexpr int value = 1;
};
template<>
struct gimme_info<float> {
static constexpr int value = 2;
};
template<typename A, typename B, typename C>
struct mycomplexthing {
};
//std::enable_if_t<std::is_pointer<T>::value, int> = 0
template<typename T>
struct gimme_info<T, typename std::enable_if_t<std::is_pointer_v<T>>> {
static constexpr int value = 10 * gimme_info<std::remove_pointer_t<T>>::value;
};
template<typename C>
struct gimme_info<C, typename std::enable_if_t<is_specialization<C, std::vector>::value>> {
static constexpr int value =
5 + 10 * gimme_info<typename argument_extractor<C, std::vector>::template nth_arg<0>>::value;
};
template<typename C>
struct gimme_info<C, typename std::enable_if_t<is_specialization<C, mycomplexthing>::value>> {
static constexpr int value =
(((gimme_info<typename argument_extractor<C, mycomplexthing>::template nth_arg<0>>::value) * 10
+ gimme_info<typename argument_extractor<C, mycomplexthing>::template nth_arg<1>>::value) * 10
+ gimme_info<typename argument_extractor<C, mycomplexthing>::template nth_arg<2>>::value) * 10 + 6;
};
/*
// Value of <T>
template <typename T>
constexpr inline typename std::enable_if<not std::is_pointer<T>::value, int>::type
gimme_info();
template <>
constexpr int gimme_info<int>(){
return 1;
}
template <>
constexpr int gimme_info<float>(){
return 2;
}
// Value of <T*>
template <typename T>
constexpr inline typename std::enable_if<std::is_pointer<T>::value, int>::type
gimme_info(){
auto content = gimme_info<std::remove_pointer_t<T>>();
return 10 + content;
}
*/
// Value of <C<T>>
//template <typename C, typename T>
//constexpr inline typename std::enable_if<not std::is_pointer<C<T>>::value, int>::type
//constexpr inline int
//gimme_info();
/*
template <template <typename...> typename C, typename T>
constexpr inline typename std::enable_if<(not std::is_pointer<C<T>>::value) and std::is_same<C<T>, vector<T>>::value, int>::type
gimme_info(){
//auto content = gimme_info<T>();
return 100;// + content;
}
*/
/*
template <typename C>
constexpr inline typename std::enable_if_t<is_specialization<C, std::vector>::value, int>
gimme_info(){
auto content = gimme_info<argument_extractor<C, std::vector>::template nth_arg<1>>();
return 100 + content;
}
*/
/*
template<typename T>
struct banana{
template <typename C>
banana(){
}
}
*/
//template<typename C>
//using extract_args = argument_extractor<C>;
/*
template <template <typename> typename C, typename T>
constexpr inline typename std::enable_if<(not std::is_pointer<C<T>>::value) and std::is_same<C<T>, vector<T>>::value, int>::type
gimme_info(){
auto content = gimme_info<T>();
return 10 + content;
}
*/
void TB::templating() {
using boost::format;
cout << format("1 = %1%\n") % gimme_info<int>::value;
cout << format("2 = %1%\n") % gimme_info<float>::value;
cout << format("10 = %1%\n") % gimme_info<int *>::value;
cout << format("10 = %1%\n") % gimme_info<float *>::value;
//cout << format("err = %1%\n") % gimme_info<double>::value;
//cout << format("err = %1%\n") % gimme_info<double*>::value;
cout << format("15 = %1%\n") % gimme_info<vector<int>>::value;
cout << format("25 = %1%\n") % gimme_info<vector<float>>::value;
cout << format("105 = %1%\n") % gimme_info<vector<int *>>::value;
cout << format("205 = %1%\n") % gimme_info<vector<float *>>::value;
cout << format("150 = %1%\n") % gimme_info<vector<int> *>::value;
cout << format("250 = %1%\n") % gimme_info<vector<float> *>::value;
cout << format("1050 = %1%\n") % gimme_info<vector<int *> *>::value;
cout << format("2050 = %1%\n") % gimme_info<vector<float *> *>::value;
cout << format("115265 = %1%\n") % gimme_info<vector<mycomplexthing<int, vector<int>, float>>>::value;
}
void TB::birthday() {
using namespace std;
using boost::format;
long double k = 3.141592653589793238462643383279502884L;
long double best_error = k;
uint64_t start = 7;
for (uint64_t i = 1; i < 1000000; i++) {
long double cn = k * i;
long double err = 0.5L - abs(cn - floor(cn) - 0.5L);
if (err < best_error) {
best_error = err;
cout << i << " " << err << "\n";
cout << (i - 2) % 113 << "\n";
}
}
glm::vec3(0, 0, 0);
}
void fun(int *&myptr) {
cout << "Hello from &\n";
}
void fun(int *&&myptr) {
cout << "Hello from &&\n";
}
void TB::movingpointers() {
int *p = new int(5);
fun(p);
fun(std::move(p));
fun(new int(5));
fun(std::move(new int(5)));
//I love successful tests
}
#define _A(k, a, b) k::a + k::b
#define _B(k, a, b) k::a * k::b
#define MCAT(a, b, c) a ## b ## C
#define A(a, b) MCAT(k, ::, a) + MCAT(k, ::, b)
#define C(k, m) m
struct mystruct_macro_order {
constexpr static int k1 = 1;
constexpr static int k2 = 2;
};
void TB::mystruct_macro_order() {
//cout<<C(mystruct, C(mystruct, A(k1,k2)));
}
struct structuring_vector_struct {
int a;
int b;
int c;
int d;
int e;
};
void TB::structuring_vector() {
vector<int> v = {1, 2, 3, 4, 5};
auto &s = *(structuring_vector_struct *) v.data();
cout << s.a << s.b << s.c << s.d << s.e;
}
void isit(int *&lvalue) {
cout << "nope\n";
}
void isit(int *&&rvalue) {
cout << "yep\n";
}
template<typename T>
void isit_ref(T &&lr_ref) {
// static_assert(std::is_same_v<std::remove_reference_t<T>, int *>,
// "This function does not support the specified type.");
isit(std::forward<T>(lr_ref));
}
void TB::isRValue() {
int *k = new int(3);
isit(new int(5));
isit(k);
isit_ref(new int(10));
isit_ref(k);
//isit_ref(5);
}
struct scope_node {
vector<void *> inputs;
vector<void *> outputs;
};
struct scope_escape {
typedef scope_escape this_t;
scope_node *value;
void link(size_t *what, scope_node *to, size_t where) {
}
enum class Inputs : size_t {
a = 2, b, c
};
typedef struct {
typedef size_t a;
typedef int b;
typedef double c;
} Inputs_t;
enum class Outputs : size_t {
a = 2, b, c
};
typedef struct {
typedef size_t a;
typedef int b;
typedef double c;
} Outputs_t;
};
#define link_scope(dest, dest_where, src, src_where) \
dest.value->inputs[(size_t) decltype(dest)::Inputs::dest_where] = \
src.value->outputs[(size_t) decltype(src)::Outputs::src_where]
void TB::scope_escape_tb() {
typedef int myint;
scope_escape::this_t::this_t::Inputs_t::a a = (size_t) scope_escape::Inputs::a;
cout << (myint) a;
scope_escape n1, n2;
typedef decltype(n1)::Inputs n1_ii;
typedef decltype(n1)::Outputs n1_oi;
typedef decltype(n2)::Inputs n2_ii;
typedef decltype(n2)::Outputs n2_oi;
auto x = new scope_escape::Outputs_t::b();
//n1.value->inputs[n1.Inputs.a] = n2.value->outputs[n2.Outputs.b];
//n1.value->inputs[(size_t) decltype(n1)::input_indexes::a] =
// n2.value->outputs[(size_t) decltype(n2)::input_indexes::b];
link_scope(n1, a, n2, b);
}
struct SynSugar {
int a;
enum class idx : std::size_t {
a, b, c, __end
};
int r[(size_t) idx::__end] = {1, 2, 3};
SynSugar(int x) {
a = x;
}
void operator()() {
cout << "Hello world! " << (size_t) idx::a;
}
};
void TB::pointy_parant() {
SynSugar *a = new SynSugar(1);
(*a)();
SynSugar &b = *a;
b();
}
template<size_t index, size_t... values>
struct ct_lut;
template<size_t cur, size_t... values>
struct ct_lut<0, cur, values...> {
static constexpr size_t value = cur;
};
template<size_t index, size_t cur, size_t... values>
struct ct_lut<index, cur, values...> {
static constexpr size_t value = ct_lut<index - 1, values...>::value;
};
struct abstract_banana {
virtual void do_the_flop() = 0;
};
struct banana2 : abstract_banana {
int k = 0;
template<size_t N>
static constexpr size_t lut = ct_lut<N, 1, 2, 3, 4, 5>::value;
static constexpr size_t arr[5] = {1, 2, 3, 4, 5};
static const size_t *arr2[3];
static void print_bananas(bool &var) {
cout << arr[0];
var = false;
}
void do_the_flop() {
cout << "|_";
}
banana2 &do_the_self_flop() {
cout << "k: " << k << "\n";
k++;
return *this;
}
typedef struct {
typedef float z;
typedef int start;
typedef int end;
} Inputs_t;
};
typedef banana2 banana2;
void TB::lut() {
bool IamTRUE = true;
banana2::print_bananas(IamTRUE);
cout << "I am false: " << IamTRUE;
abstract_banana **arr = new abstract_banana *[2];
arr[0] = new banana2();
arr[0]->do_the_flop();
banana2().do_the_self_flop().do_the_self_flop().do_the_self_flop();
banana2::Inputs_t::end a = 2;
}
typedef void (*bad_lambda_func)(vector<int *> &inputs, vector<int *> &outputs, bool &return_control_flow);
bad_lambda_func gimme_good_func() {
return [](vector<int *> &inputs, vector<int *> &outputs, bool &return_control_flow) {
static int data = 5;
cout << "Hello func!\n";
cout << data++ << "\n";
return_control_flow = true;
};
}
void TB::bad_lambda() {
bad_lambda_func func1 = gimme_good_func();
bad_lambda_func func2 = gimme_good_func();
bool ok = false;
vector<int *> ins = {new int(2)};
vector<int *> outs = {new int(3)};
func1(ins, outs, ok);
func2(ins, outs, ok);
func1(ins, outs, ok);
func2(ins, outs, ok);
cout << "ok: " << ok << "\n";
};
template<typename T>
struct pika {
T data;
pika(const T &val) : data(val) {
cout << "is it l? " << std::is_lvalue_reference_v<T> << "\n";
cout << "is it r? " << std::is_rvalue_reference_v<T> << "\n";
// cout << "ref\n";
if (std::is_same_v<T, int>) {
cout << "spec\n";
} else {
cout << "tmp\n";
}
}
pika(const int *val) : data(val) {
cout << "int*ss\n";
}
operator int *() {
return new int(5);
}
int &gimme_data() &{
return *new int(7);
}
int &&gimme_data() &&{
return std::move(*new int(7));
}
};
template<typename T>
void lr_info(T &data) {
cout << "data is lvalue\n";
}
template<typename T>
void lr_info(T &&data) {
cout << "data is rvalue\n";
}
void TB::pikapika() {
auto grr = pika(string("a"));
string x = "Hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\n";
auto grrr = pika(x);
cout << x;
auto nyaa = pika(5);
auto nya = pika(new int(5));
cout << *(int *) nya;
lr_info(x);
lr_info(new int(5));
cout << "member tests:\n";
lr_info(nya.gimme_data());
lr_info(pika(new int(5)).gimme_data());
}
void dosth_opt(std::optional<bool *> dosth = {}) {
if (dosth.has_value()) {
if (*dosth != nullptr && **dosth == true)
cout << "I received: true\n";
else if (*dosth != nullptr && **dosth == false)
cout << "I received: false\n";
else
cout << "What is this fakery\n";
} else {
cout << "Nothing mate \n";
}
}
void TB::optional() {
dosth_opt();
dosth_opt(new bool(true));
dosth_opt(new bool(false));
dosth_opt(nullptr);
}
int cr_func(int &x) {
return x + 5;
}
constexpr int cr_func(const int &x) {
return x + 1;
}
void TB::cr_test() {
cout << cr_func(5);
int k = time(nullptr) % 3;
cout << cr_func(k);
}
void TB::vector_init() {
vector<int *> myvec = vector<int *>(5);
myvec.push_back(new int(3));
cout << "inserted at: " << myvec.size() - 1 << "\n";
for (int i = 0; i < myvec.size(); i++) {
if (myvec[i] != nullptr)
cout << "[" << i << "]: " << *myvec[i] << "\n";
}
vector<int> z;
//R.I.P. last ounce of consistency
z.push_back(0);
//z.push_back({1,2,3});
z.insert(z.end(), 4);
z.insert(z.end(), {5, 6, 7});
z = {1, 2, 3};
for (auto x : z) {
cout << x << " ";
}
}
template<typename T, typename Cond = void>
struct is_const_char_array : std::false_type {
};
template<typename T>
struct is_const_char_array<T,
std::enable_if_t<std::is_array_v<std::remove_reference_t<T>> and
std::is_same_v<const char, std::remove_extent_t<std::remove_reference_t<T>>>
>> : std::true_type {
};
template<typename T>
inline constexpr bool is_const_char_array_v = is_const_char_array<T>::value;
template<typename T, int N = 3>
struct fwd_tag {
};
template<typename T, int N = 0>
struct forwarder {
typedef T type;
static const int n = N;
};
template<typename T, int N>
struct forwarder<fwd_tag<T, N>> {
typedef T type;
static const int n = N;
};
template<typename T>
using forwarder_t = typename forwarder<T>::type;
template<typename T>
inline const int forwarder_n = forwarder<T>::n;
void TB::is_T() {
const char (&var)[9] = "position";
cout << std::is_array_v<std::remove_reference_t<decltype(var)>>;
cout << std::is_lvalue_reference_v<decltype(var)>;
cout << std::is_same_v<const char, std::remove_extent_t<std::remove_reference_t<decltype(var)>>>;
cout << "\n...\n";
cout << is_const_char_array_v<const char (&)[9]>;
cout << is_const_char_array_v<const char>;
cout << is_const_char_array_v<char *>;
cout << is_const_char_array_v<char *&&>;
cout << is_const_char_array_v<const char *>;
cout << is_const_char_array_v<const char *[10]>;
cout << is_const_char_array_v<const char[10]>;
cout << is_const_char_array_v<const char[]>;
cout << is_const_char_array_v<decltype("ana")>;
cout << "\n...\n";
cout << is_const_char_array_v<forwarder_t<const char (&)[9]>>;
cout << is_const_char_array_v<forwarder_t<fwd_tag<const char (&)[9]>>>;
cout << "\n n: " << forwarder_n<fwd_tag<const char (&)[9], 7>> << "\n";
cout << "\n n: " << forwarder_n<fwd_tag<const char (&)[9]>> << "\n";
cout << "\n n: " << forwarder_n<const char (&)[9]> << "\n";
int data = 5;
int *dataptr = &data;
lr_info(&data);
lr_info(dataptr);
}
template<typename T1>
struct two_con {
bool value1, value2;
two_con() {
value1 = std::is_pointer_v<T1>;
}
template<typename _T = T1, typename std::enable_if_t<std::is_same_v<_T, int>, int> = 0>
void do_the_int_thing() {
cout << "the int thing\n";
}
};
void TB::implicit_two_con() {
vector<int> banana;
//two_con<int*>().do_the_int_thing();
}
struct jail_struct {
static constexpr char *name = "Bob";
vector<int> years_left;
};
void TB::struct_scope_escape() {
cout << jail_struct::name;
}
// my_template.h
template<typename T>
struct my_template {
static int brain_size;
my_template() {
brain_size++;
}
};
template<typename T>
int my_template<T>::brain_size = 0;
template<typename T>
struct my_templ {
// Genius logic: define it in the same file -> "must be defined out of line" -> define it in a separate file
// -> "undefined reference"
// Solution: define it the same file BUT LOWER *big brain stuff*
// Logical conclusion: The C++ Standard eats memes and sometimes they pass undigested
inline static int instance = 0;
my_templ() {
cout << "This is the most brain dead undefined reference I've ever seen: << " << instance++ << " \n";
}
};
//template<typename T>
//int my_templ<T>::instance = 0;
/*
template<typename T>
struct my_templ_macro_ready;
template<typename T>
int my_templ_macro_ready<T>::instance = 0;
template<typename T>
struct my_templ_macro_ready{
static int instance;
my_templ_macro_ready(){
cout << "This is the most brain dead undefined reference I've ever seen: << " << instance++ << " \n";
}
};
*/
void TB::template_inconsitencies() {
my_templ<int> i1;
my_templ<int> i2;
my_templ<char> c1;
my_templ<int> i3;
my_templ<char> c2;
};
size_t tunc_2p_down(size_t x) {
size_t res = x >> 1;
res |= res >> 1;
res |= res >> 2;
res |= res >> 4;
res |= res >> 8;
res |= res >> 16;
res |= res >> 32;
return x & ~res;
}
void TB::trunc_pow2() {
for (size_t i = 2; i < 2048;) {
cout << (tunc_2p_down(i) >> 1) << " < " << i << "\n";
i += tunc_2p_down(i) >> 1;
}
}
void TB::dynamic_queue() {
std::list<int> queue;
queue.push_back(1);
for (auto &cur : queue) {
if (cur < 1000)
queue.push_back(cur * 2);
cout << cur << "\n";
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//---------------------------------------------------------------------------
// Package Title ratpak
// File conv.c
// Copyright (C) 1995-97 Microsoft
// Date 01-16-95
//
//
// Description
//
// Contains conversion, input and output routines for numbers rationals
// and longs.
//
//
//
//---------------------------------------------------------------------------
#include "pch.h"
#include "ratpak.h"
using namespace std;
static constexpr int MAX_ZEROS_AFTER_DECIMAL = 2;
// digits 0..64 used by bases 2 .. 64
static constexpr wstring_view DIGITS = L"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_@";
// ratio of internal 'digits' to output 'digits'
// Calculated elsewhere as part of initialization and when base is changed
long g_ratio; // int(log(2L^BASEXPWR)/log(radix))
// Default decimal separator
wchar_t g_decimalSeparator = L'.';
// Used to strip trailing zeros, and prevent combinatorial explosions
bool stripzeroesnum(_Inout_ PNUMBER pnum, long starting);
void SetDecimalSeparator(wchar_t decimalSeparator)
{
g_decimalSeparator = decimalSeparator;
}
//
// Windows heap allocation
//
void* zmalloc(size_t a)
{
return calloc(a, sizeof(unsigned char));
}
//-----------------------------------------------------------------------------
//
// FUNCTION: _dupnum
//
// ARGUMENTS: pointer to a number, pointer to a number
//
// RETURN: None
//
// DESCRIPTION: Copies the source to the destination
//
//-----------------------------------------------------------------------------
void _dupnum(_In_ PNUMBER dest, _In_ PNUMBER src)
{
memcpy(dest, src, (int)(sizeof(NUMBER) + ((src)->cdigit)*(sizeof(MANTTYPE))));
}
//-----------------------------------------------------------------------------
//
// FUNCTION: _destroynum
//
// ARGUMENTS: pointer to a number
//
// RETURN: None
//
// DESCRIPTION: Deletes the number and associated allocation
//
//-----------------------------------------------------------------------------
void _destroynum( _In_ PNUMBER pnum )
{
if ( pnum != nullptr)
{
free( pnum );
}
}
//-----------------------------------------------------------------------------
//
// FUNCTION: _destroyrat
//
// ARGUMENTS: pointer to a rational
//
// RETURN: None
//
// DESCRIPTION: Deletes the rational and associated
// allocations.
//
//-----------------------------------------------------------------------------
void _destroyrat( _In_ PRAT prat )
{
if ( prat != nullptr)
{
destroynum( prat->pp );
destroynum( prat->pq );
free( prat );
}
}
//-----------------------------------------------------------------------------
//
// FUNCTION: _createnum
//
// ARGUMENTS: size of number in 'digits'
//
// RETURN: pointer to a number
//
// DESCRIPTION: allocates and zeros out number type.
//
//-----------------------------------------------------------------------------
PNUMBER _createnum( _In_ ULONG size )
{
PNUMBER pnumret= nullptr;
ULONG cbAlloc;
// sizeof( MANTTYPE ) is the size of a 'digit'
if (SUCCEEDED(ULongAdd(size, 1, &cbAlloc)) &&
SUCCEEDED(ULongMult(cbAlloc, sizeof(MANTTYPE), &cbAlloc)) &&
SUCCEEDED(ULongAdd(cbAlloc, sizeof(NUMBER), &cbAlloc)))
{
pnumret = (PNUMBER)zmalloc( cbAlloc );
if ( pnumret == nullptr)
{
throw( CALC_E_OUTOFMEMORY );
}
}
else
{
throw( CALC_E_INVALIDRANGE );
}
return( pnumret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: _createrat
//
// ARGUMENTS: none
//
// RETURN: pointer to a rational
//
// DESCRIPTION: allocates a rational structure but does not
// allocate the numbers that make up the rational p over q
// form. These number pointers are left pointing to null.
//
//-----------------------------------------------------------------------------
PRAT _createrat( void )
{
PRAT prat= nullptr;
prat = (PRAT)zmalloc( sizeof( RAT ) );
if ( prat == nullptr)
{
throw( CALC_E_OUTOFMEMORY );
}
prat->pp = nullptr;
prat->pq = nullptr;
return( prat );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: numtorat
//
// ARGUMENTS: pointer to a number, radix number is in.
//
// RETURN: Rational representation of number.
//
// DESCRIPTION: The rational representation of the number
// is guaranteed to be in the form p (number with internal
// base representation) over q (number with internal base
// representation) Where p and q are integers.
//
//-----------------------------------------------------------------------------
PRAT numtorat( _In_ PNUMBER pin, uint32_t radix)
{
PNUMBER pnRadixn= nullptr;
DUPNUM( pnRadixn, pin );
PNUMBER qnRadixn=longtonum( 1, radix);
// Ensure p and q start out as integers.
if ( pnRadixn->exp < 0 )
{
qnRadixn->exp -= pnRadixn->exp;
pnRadixn->exp = 0;
}
PRAT pout= nullptr;
createrat(pout);
// There is probably a better way to do this.
pout->pp = numtonRadixx(pnRadixn, radix);
pout->pq = numtonRadixx(qnRadixn, radix);
destroynum( pnRadixn );
destroynum( qnRadixn );
return( pout );
}
//----------------------------------------------------------------------------
//
// FUNCTION: nRadixxtonum
//
// ARGUMENTS: pointer to a number, base requested.
//
// RETURN: number representation in radix requested.
//
// DESCRIPTION: Does a base conversion on a number from
// internal to requested base. Assumes number being passed
// in is really in internal base form.
//
//----------------------------------------------------------------------------
PNUMBER nRadixxtonum( _In_ PNUMBER a, uint32_t radix, int32_t precision)
{
unsigned long bitmask;
unsigned long cdigits;
MANTTYPE *ptr;
PNUMBER sum = longtonum( 0, radix );
PNUMBER powofnRadix = longtonum( BASEX, radix );
// A large penalty is paid for conversion of digits no one will see anyway.
// limit the digits to the minimum of the existing precision or the
// requested precision.
cdigits = precision + 1;
if ( cdigits > (unsigned long)a->cdigit )
{
cdigits = (unsigned long)a->cdigit;
}
// scale by the internal base to the internal exponent offset of the LSD
numpowlong( &powofnRadix, a->exp + (a->cdigit - cdigits), radix, precision);
// Loop over all the relative digits from MSD to LSD
for ( ptr = &(a->mant[a->cdigit-1]); cdigits > 0;
ptr--, cdigits-- )
{
// Loop over all the bits from MSB to LSB
for ( bitmask = BASEX/2; bitmask > 0; bitmask /= 2 )
{
addnum( &sum, sum, radix );
if ( *ptr & bitmask )
{
sum->mant[0] |= 1;
}
}
}
// Scale answer by power of internal exponent.
mulnum( &sum, powofnRadix, radix );
destroynum( powofnRadix );
sum->sign = a->sign;
return( sum );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: numtonRadixx
//
// ARGUMENTS: pointer to a number, radix of that number.
//
// RETURN: number representation in internal radix.
//
// DESCRIPTION: Does a radix conversion on a number from
// specified radix to requested radix. Assumes the radix
// specified is the radix of the number passed in.
//
//-----------------------------------------------------------------------------
PNUMBER numtonRadixx(_In_ PNUMBER a, uint32_t radix)
{
PNUMBER pnumret = longtonum(0, BASEX); // pnumret is the number in internal form.
PNUMBER num_radix = longtonum(radix, BASEX);
MANTTYPE *ptrdigit = a->mant; // pointer to digit being worked on.
// Digits are in reverse order, back over them LSD first.
ptrdigit += a->cdigit-1;
PNUMBER thisdigit = nullptr; // thisdigit holds the current digit of a
// being summed into result.
long idigit; // idigit is the iterate of digits in a.
for ( idigit = 0; idigit < a->cdigit; idigit++ )
{
mulnumx( &pnumret, num_radix);
// WARNING:
// This should just smack in each digit into a 'special' thisdigit.
// and not do the overhead of recreating the number type each time.
thisdigit = longtonum( *ptrdigit--, BASEX );
addnum( &pnumret, thisdigit, BASEX );
destroynum( thisdigit );
}
// Calculate the exponent of the external base for scaling.
numpowlongx( &num_radix, a->exp );
// ... and scale the result.
mulnumx( &pnumret, num_radix);
destroynum(num_radix);
// And propagate the sign.
pnumret->sign = a->sign;
return( pnumret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: StringToRat
//
// ARGUMENTS:
// mantissaIsNegative true if mantissa is less than zero
// mantissa a string representation of a number
// exponentIsNegative true if exponent is less than zero
// exponent a string representation of a number
// radix is the number base used in the source string
//
// RETURN: PRAT representation of string input.
// Or nullptr if no number scanned.
//
// EXPLANATION: This is for calc.
//
//
//-----------------------------------------------------------------------------
PRAT StringToRat(bool mantissaIsNegative, wstring_view mantissa, bool exponentIsNegative, wstring_view exponent, uint32_t radix, int32_t precision)
{
PRAT resultRat = nullptr; // holds exponent in rational form.
// Deal with mantissa
if (mantissa.empty())
{
// Preset value if no mantissa
if (exponent.empty())
{
// Exponent not specified, preset value to zero
DUPRAT(resultRat, rat_zero);
}
else
{
// Exponent specified, preset value to one
DUPRAT(resultRat, rat_one);
}
}
else
{
// Mantissa specified, convert to number form.
PNUMBER pnummant = StringToNumber(mantissa, radix, precision);
if (pnummant == nullptr)
{
return nullptr;
}
resultRat = numtorat(pnummant, radix);
// convert to rational form, and cleanup.
destroynum(pnummant);
}
// Deal with exponent
long expt = 0;
if (!exponent.empty())
{
// Exponent specified, convert to number form.
// Don't use native stuff, as it is restricted in the bases it can
// handle.
PNUMBER numExp = StringToNumber(exponent, radix, precision);
if (numExp == nullptr)
{
return nullptr;
}
// Convert exponent number form to native integral form, and cleanup.
expt = numtolong(numExp, radix);
destroynum(numExp);
}
// Convert native integral exponent form to rational multiplier form.
PNUMBER pnumexp = longtonum(radix, BASEX);
numpowlongx(&pnumexp, abs(expt));
PRAT pratexp = nullptr;
createrat(pratexp);
DUPNUM(pratexp->pp, pnumexp);
pratexp->pq = longtonum(1, BASEX);
destroynum(pnumexp);
if (exponentIsNegative)
{
// multiplier is less than 1, this means divide.
divrat(&resultRat, pratexp, precision);
}
else if (expt > 0)
{
// multiplier is greater than 1, this means multiply.
mulrat(&resultRat, pratexp, precision);
}
// multiplier can be 1, in which case it'd be a waste of time to multiply.
destroyrat(pratexp);
if (mantissaIsNegative)
{
// A negative number was used, adjust the sign.
resultRat->pp->sign *= -1;
}
return resultRat;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: StringToNumber
//
// ARGUMENTS:
// wstring_view numberString
// int radix
// int32_t precision
//
// RETURN: pnumber representation of string input.
// Or nullptr if no number scanned.
//
// EXPLANATION: This is a state machine,
//
// State Description Example, ^shows just read position.
// which caused the transition
//
// START Start state ^1.0
// MANTS Mantissa sign -^1.0
// LZ Leading Zero 0^1.0
// LZDP Post LZ dec. pt. 000.^1
// LD Leading digit 1^.0
// DZ Post LZDP Zero 000.0^1
// DD Post Decimal digit .01^2
// DDP Leading Digit dec. pt. 1.^2
// EXPB Exponent Begins 1.0e^2
// EXPS Exponent sign 1.0e+^5
// EXPD Exponent digit 1.0e1^2 or even 1.0e0^1
// EXPBZ Exponent begin post 0 0.000e^+1
// EXPSZ Exponent sign post 0 0.000e+^1
// EXPDZ Exponent digit post 0 0.000e+1^2
// ERR Error case 0.0.^
//
// Terminal Description
//
// DP '.'
// ZR '0'
// NZ '1'..'9' 'A'..'Z' 'a'..'z' '@' '_'
// SG '+' '-'
// EX 'e' '^' e is used for radix 10, ^ for all other radixes.
//
//-----------------------------------------------------------------------------
static constexpr uint8_t DP = 0;
static constexpr uint8_t ZR = 1;
static constexpr uint8_t NZ = 2;
static constexpr uint8_t SG = 3;
static constexpr uint8_t EX = 4;
static constexpr uint8_t START = 0;
static constexpr uint8_t MANTS = 1;
static constexpr uint8_t LZ = 2;
static constexpr uint8_t LZDP = 3;
static constexpr uint8_t LD = 4;
static constexpr uint8_t DZ = 5;
static constexpr uint8_t DD = 6;
static constexpr uint8_t DDP = 7;
static constexpr uint8_t EXPB = 8;
static constexpr uint8_t EXPS = 9;
static constexpr uint8_t EXPD = 10;
static constexpr uint8_t EXPBZ = 11;
static constexpr uint8_t EXPSZ = 12;
static constexpr uint8_t EXPDZ = 13;
static constexpr uint8_t ERR = 14;
#if defined( DEBUG )
char *statestr[] = {
"START",
"MANTS",
"LZ",
"LZDP",
"LD",
"DZ",
"DD",
"DDP",
"EXPB",
"EXPS",
"EXPD",
"EXPBZ",
"EXPSZ",
"EXPDZ",
"ERR",
};
#endif
// New state is machine[state][terminal]
static constexpr uint8_t machine[ERR+1][EX+1]= {
// DP, ZR, NZ, SG, EX
// START
{ LZDP, LZ, LD, MANTS, ERR },
// MANTS
{ LZDP, LZ, LD, ERR, ERR },
// LZ
{ LZDP, LZ, LD, ERR, EXPBZ },
// LZDP
{ ERR, DZ, DD, ERR, EXPB },
// LD
{ DDP, LD, LD, ERR, EXPB },
// DZ
{ ERR, DZ, DD, ERR, EXPBZ },
// DD
{ ERR, DD, DD, ERR, EXPB },
// DDP
{ ERR, DD, DD, ERR, EXPB },
// EXPB
{ ERR, EXPD, EXPD, EXPS, ERR },
// EXPS
{ ERR, EXPD, EXPD, ERR, ERR },
// EXPD
{ ERR, EXPD, EXPD, ERR, ERR },
// EXPBZ
{ ERR, EXPDZ, EXPDZ, EXPSZ, ERR },
// EXPSZ
{ ERR, EXPDZ, EXPDZ, ERR, ERR },
// EXPDZ
{ ERR, EXPDZ, EXPDZ, ERR, ERR },
// ERR
{ ERR, ERR, ERR, ERR, ERR }
};
wchar_t NormalizeCharDigit(wchar_t c, uint32_t radix)
{
// Allow upper and lower case letters as equivalent, base
// is in the range where this is not ambiguous.
if (size_t{ radix } >= DIGITS.find(L'A') && size_t { radix } <= DIGITS.find(L'Z'))
{
return toupper(c);
}
return c;
}
PNUMBER StringToNumber(wstring_view numberString, uint32_t radix, int32_t precision)
{
long expSign = 1L; // expSign is exponent sign ( +/- 1 )
long expValue = 0L; // expValue is exponent mantissa, should be unsigned
PNUMBER pnumret = nullptr;
createnum(pnumret, static_cast<ULONG>(numberString.length()));
pnumret->sign = 1L;
pnumret->cdigit = 0;
pnumret->exp = 0;
MANTTYPE *pmant = pnumret->mant + numberString.length() - 1;
uint8_t state = START; // state is the state of the input state machine.
wchar_t curChar;
for (const auto& c : numberString)
{
// If the character is the decimal separator, use L'.' for the purposes of the state machine.
curChar = (c == g_decimalSeparator ? L'.' : c);
// Switch states based on the character we encountered
switch (curChar)
{
case L'-':
case L'+':
state = machine[state][SG];
break;
case L'.':
state = machine[state][DP];
break;
case L'0':
state = machine[state][ZR];
break;
case L'^':
case L'e':
if (curChar == L'^' || radix == 10)
{
state = machine[state][EX];
break;
}
// Drop through in the 'e'-as-a-digit case
default:
state = machine[state][NZ];
break;
}
// Now update our result value based on the state we are in
switch (state)
{
case MANTS:
pnumret->sign = (curChar == L'-') ? -1 : 1;
break;
case EXPSZ:
case EXPS:
expSign = (curChar == L'-') ? -1 : 1;
break;
case EXPDZ:
case EXPD:
{
curChar = NormalizeCharDigit(curChar, radix);
size_t pos = DIGITS.find(curChar);
if (pos != wstring_view::npos)
{
expValue *= radix;
expValue += static_cast<long>(pos);
}
else
{
state = ERR;
}
}
break;
case LD:
pnumret->exp++;
// Fall through
case DD:
{
curChar = NormalizeCharDigit(curChar, radix);
size_t pos = DIGITS.find(curChar);
if (pos != wstring_view::npos && pos < static_cast<size_t>(radix))
{
*pmant-- = static_cast<MANTTYPE>(pos);
pnumret->exp--;
pnumret->cdigit++;
}
else
{
state = ERR;
}
}
break;
case DZ:
pnumret->exp--;
break;
case LZ:
case LZDP:
case DDP:
break;
}
}
if (state == DZ || state == EXPDZ)
{
pnumret->cdigit = 1;
pnumret->exp = 0;
pnumret->sign = 1;
}
else
{
while (pnumret->cdigit < static_cast<long>(numberString.length()))
{
pnumret->cdigit++;
pnumret->exp--;
}
pnumret->exp += expSign * expValue;
}
// If we don't have a number, clear our result.
if (pnumret->cdigit == 0)
{
destroynum(pnumret);
pnumret = nullptr;
}
stripzeroesnum(pnumret, precision);
return pnumret;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: longtorat
//
// ARGUMENTS: long
//
// RETURN: Rational representation of long input.
//
// DESCRIPTION: Converts long input to rational (p over q)
// form, where q is 1 and p is the long.
//
//-----------------------------------------------------------------------------
PRAT longtorat( _In_ long inlong )
{
PRAT pratret= nullptr;
createrat( pratret );
pratret->pp = longtonum(inlong, BASEX );
pratret->pq = longtonum(1L, BASEX );
return( pratret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: Ulongtorat
//
// ARGUMENTS: ulong
//
// RETURN: Rational representation of unsigned long input.
//
// DESCRIPTION: Converts unsigned long input to rational (p over q)
// form, where q is 1 and p is the unsigned long. Being unsigned cant take negative
// numbers, but the full range of unsigned numbers
//
//-----------------------------------------------------------------------------
PRAT Ulongtorat( _In_ unsigned long inulong )
{
PRAT pratret= nullptr;
createrat( pratret );
pratret->pp = Ulongtonum(inulong, BASEX );
pratret->pq = longtonum(1L, BASEX );
return( pratret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: longtonum
//
// ARGUMENTS: long input and radix requested.
//
// RETURN: number
//
// DESCRIPTION: Returns a number representation in the
// base requested of the long value passed in.
//
//-----------------------------------------------------------------------------
PNUMBER longtonum( long inlong, uint32_t radix)
{
MANTTYPE *pmant;
PNUMBER pnumret= nullptr;
createnum( pnumret, MAX_LONG_SIZE );
pmant = pnumret->mant;
pnumret->cdigit = 0;
pnumret->exp = 0;
if ( inlong < 0 )
{
pnumret->sign = -1;
inlong *= -1;
}
else
{
pnumret->sign = 1;
}
do {
*pmant++ = (MANTTYPE)(inlong % radix);
inlong /= radix;
pnumret->cdigit++;
} while ( inlong );
return( pnumret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: Ulongtonum
//
// ARGUMENTS: ULONG input and radix requested.
//
// RETURN: number
//
// DESCRIPTION: Returns a number representation in the
// base requested of the unsigned long value passed in. Being unsigned number it has no
// negative number and takes the full range of unsigned number
//
//-----------------------------------------------------------------------------
PNUMBER Ulongtonum(unsigned long inlong, uint32_t radix)
{
MANTTYPE *pmant;
PNUMBER pnumret= nullptr;
createnum( pnumret, MAX_LONG_SIZE );
pmant = pnumret->mant;
pnumret->cdigit = 0;
pnumret->exp = 0;
pnumret->sign = 1;
do {
*pmant++ = (MANTTYPE)(inlong % radix);
inlong /= radix;
pnumret->cdigit++;
} while ( inlong );
return( pnumret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: rattolong
//
// ARGUMENTS: rational number in internal base, integer radix and int32_t precision.
//
// RETURN: long
//
// DESCRIPTION: returns the long representation of the
// number input. Assumes that the number is in the internal
// base.
//
//-----------------------------------------------------------------------------
long rattolong( _In_ PRAT prat , uint32_t radix, int32_t precision)
{
if ( rat_gt( prat, rat_max_long, precision) || rat_lt( prat, rat_min_long, precision) )
{
// Don't attempt rattolong of anything too big or small
throw( CALC_E_DOMAIN );
}
PRAT pint = nullptr;
DUPRAT(pint,prat);
intrat( &pint, radix, precision);
divnumx( &(pint->pp), pint->pq, precision);
DUPNUM( pint->pq, num_one );
long lret = numtolong( pint->pp, BASEX );
destroyrat(pint);
return( lret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: rattoUlong
//
// ARGUMENTS: rational number in internal base, integer radix and int32_t precision.
//
// RETURN: Ulong
//
// DESCRIPTION: returns the Ulong representation of the
// number input. Assumes that the number is in the internal
// base.
//
//-----------------------------------------------------------------------------
unsigned long rattoUlong( _In_ PRAT prat, uint32_t radix, int32_t precision)
{
if ( rat_gt( prat, rat_dword, precision) || rat_lt( prat, rat_zero, precision) )
{
// Don't attempt rattoulong of anything too big or small
throw( CALC_E_DOMAIN );
}
PRAT pint = nullptr;
DUPRAT(pint,prat);
intrat( &pint, radix, precision);
divnumx( &(pint->pp), pint->pq, precision);
DUPNUM( pint->pq, num_one );
unsigned long lret = numtolong( pint->pp, BASEX ); // This happens to work even if it is only signed
destroyrat(pint);
return( lret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: rattoUlonglong
//
// ARGUMENTS: rational number in internal base, integer radix and int32_t precision
//
// RETURN: Ulonglong
//
// DESCRIPTION: returns the 64 bit (irrespective of which processor this is running in) representation of the
// number input. Assumes that the number is in the internal
// base. Can throw exception if the number exceeds 2^64
// Implementation by getting the HI & LO 32 bit words and concatenating them, as the
// internal base chosen happens to be 2^32, this is easier.
//-----------------------------------------------------------------------------
ULONGLONG rattoUlonglong( _In_ PRAT prat, uint32_t radix, int32_t precision)
{
PRAT pint = nullptr;
// first get the LO 32 bit word
DUPRAT(pint, prat);
andrat(&pint, rat_dword, radix, precision); // & 0xFFFFFFFF (2 ^ 32 -1)
unsigned long lo = rattoUlong(pint, radix, precision); // wont throw exception because already hi-dword chopped off
DUPRAT(pint, prat); // previous pint will get freed by this as well
PRAT prat32 = longtorat(32);
rshrat(&pint, prat32, radix, precision);
intrat( &pint, radix, precision);
andrat(&pint, rat_dword, radix, precision); // & 0xFFFFFFFF (2 ^ 32 -1)
unsigned long hi = rattoUlong(pint, radix, precision);
destroyrat(prat32);
destroyrat(pint);
return (((ULONGLONG)hi << 32) | lo);
}
//-----------------------------------------------------------------------------
//
// FUNCTION: numtolong
//
// ARGUMENTS: number input and base of that number.
//
// RETURN: long
//
// DESCRIPTION: returns the long representation of the
// number input. Assumes that the number is really in the
// base claimed.
//
//-----------------------------------------------------------------------------
long numtolong( _In_ PNUMBER pnum, uint32_t radix )
{
long lret = 0;
MANTTYPE *pmant = pnum->mant;
pmant += pnum->cdigit - 1;
long expt = pnum->exp;
for (long length = pnum->cdigit; length > 0 && length + expt > 0; length--)
{
lret *= radix;
lret += *(pmant--);
}
while (expt-- > 0)
{
lret *= radix;
}
lret *= pnum->sign;
return lret;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: bool stripzeroesnum
//
// ARGUMENTS: a number representation
//
// RETURN: true if stripping done, modifies number in place.
//
// DESCRIPTION: Strips off trailing zeros.
//
//-----------------------------------------------------------------------------
bool stripzeroesnum(_Inout_ PNUMBER pnum, long starting)
{
MANTTYPE *pmant;
long cdigits;
bool fstrip = false;
// point pmant to the LeastCalculatedDigit
pmant=pnum->mant;
cdigits=pnum->cdigit;
// point pmant to the LSD
if ( cdigits > starting )
{
pmant += cdigits - starting;
cdigits = starting;
}
// Check we haven't gone too far, and we are still looking at zeros.
while ( ( cdigits > 0 ) && !(*pmant) )
{
// move to next significant digit and keep track of digits we can
// ignore later.
pmant++;
cdigits--;
fstrip = true;
}
// If there are zeros to remove.
if ( fstrip )
{
// Remove them.
memmove( pnum->mant, pmant, (int)(cdigits*sizeof(MANTTYPE)) );
// And adjust exponent and digit count accordingly.
pnum->exp += ( pnum->cdigit - cdigits );
pnum->cdigit = cdigits;
}
return( fstrip );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: NumberToString
//
// ARGUMENTS: number representation
// fmt, one of FMT_FLOAT FMT_SCIENTIFIC or
// FMT_ENGINEERING
// integer radix and int32_t precision value
//
// RETURN: String representation of number.
//
// DESCRIPTION: Converts a number to it's string
// representation.
//
//-----------------------------------------------------------------------------
wstring NumberToString(_Inout_ PNUMBER& pnum, int format, uint32_t radix, int32_t precision)
{
stripzeroesnum(pnum, precision + 2);
long length = pnum->cdigit;
long exponent = pnum->exp + length; // Actual number of digits to the left of decimal
long oldFormat = format;
if (exponent > precision && format == FMT_FLOAT)
{
// Force scientific mode to prevent user from assuming 33rd digit is exact.
format = FMT_SCIENTIFIC;
}
// Make length small enough to fit in pret.
if (length > precision)
{
length = precision;
}
// 2 for signs, 1 for 'e'(or leading zero), 1 for dp, 1 for null and
// 10 for maximum exponent size.
int cchNum = (precision + 16);
// If there is a chance a round has to occur, round.
// - if number is zero no rounding
// - if number of digits is less than the maximum output no rounding
PNUMBER round = nullptr;
if (!zernum(pnum) && (pnum->cdigit >= precision || (length - exponent > precision && exponent >= -MAX_ZEROS_AFTER_DECIMAL)))
{
// Otherwise round.
round = longtonum(radix, radix);
divnum(&round, num_two, radix, precision);
// Make round number exponent one below the LSD for the number.
if (exponent > 0 || format == FMT_FLOAT)
{
round->exp = pnum->exp + pnum->cdigit - round->cdigit - precision;
}
else
{
round->exp = pnum->exp + pnum->cdigit - round->cdigit - precision - exponent;
length = precision + exponent;
}
round->sign = pnum->sign;
}
if (format == FMT_FLOAT)
{
// Figure out if the exponent will fill more space than the non-exponent field.
if ((length - exponent > precision) || (exponent > precision + 3))
{
if (exponent >= -MAX_ZEROS_AFTER_DECIMAL)
{
round->exp -= exponent;
length = precision + exponent;
}
else
{
// Case where too many zeros are to the right or left of the
// decimal pt. And we are forced to switch to scientific form.
format = FMT_SCIENTIFIC;
}
}
else if (length + abs(exponent) < precision && round)
{
// Minimum loss of precision occurs with listing leading zeros
// if we need to make room for zeros sacrifice some digits.
round->exp -= exponent;
}
}
if (round != nullptr)
{
addnum(&pnum, round, radix);
long offset = (pnum->cdigit + pnum->exp) - (round->cdigit + round->exp);
destroynum(round);
if (stripzeroesnum(pnum, offset))
{
// WARNING: nesting/recursion, too much has been changed, need to
// re-figure format.
return NumberToString(pnum, oldFormat, radix, precision);
}
}
else
{
stripzeroesnum(pnum, precision);
}
// Set up all the post rounding stuff.
bool useSciForm = false;
long eout = exponent - 1; // Displayed exponent.
MANTTYPE *pmant = pnum->mant + pnum->cdigit - 1;
// Case where too many digits are to the left of the decimal or
// FMT_SCIENTIFIC or FMT_ENGINEERING was specified.
if ((format == FMT_SCIENTIFIC) || (format == FMT_ENGINEERING))
{
useSciForm = true;
if (eout != 0)
{
if (format == FMT_ENGINEERING)
{
exponent = (eout % 3);
eout -= exponent;
exponent++;
// Fix the case where 0.02e-3 should really be 2.e-6 etc.
if (exponent < 0)
{
exponent += 3;
eout -= 3;
}
}
else
{
exponent = 1;
}
}
}
else
{
eout = 0;
}
// Begin building the result string
wstringstream resultStream{};
// Make sure negative zeros aren't allowed.
if ((pnum->sign == -1) && (length > 0))
{
resultStream << L'-';
}
if (exponent <= 0 && !useSciForm)
{
resultStream << L'0';
resultStream << g_decimalSeparator;
// Used up a digit unaccounted for.
}
while (exponent < 0)
{
resultStream << L'0';
exponent++;
}
while (length > 0)
{
exponent--;
resultStream << DIGITS[*pmant--];
length--;
// Be more regular in using a decimal point.
if (exponent == 0)
{
resultStream << g_decimalSeparator;
}
}
while (exponent > 0)
{
resultStream << L'0';
exponent--;
// Be more regular in using a decimal point.
if (exponent == 0)
{
resultStream << g_decimalSeparator;
}
}
if (useSciForm)
{
resultStream << (radix == 10 ? L'e' : L'^');
resultStream << (eout < 0 ? L'-' : L'+');
eout = abs(eout);
wstringstream exponentStream{};
do
{
exponentStream << DIGITS[eout % radix];
eout /= radix;
} while (eout > 0);
auto expString = exponentStream.str();
for (auto ritr = expString.rbegin(); ritr != expString.rend(); ritr++)
{
resultStream << *ritr;
}
}
// Remove trailing decimal
auto resultString = resultStream.str();
if (!resultString.empty() && resultString.back() == g_decimalSeparator)
{
resultString.pop_back();
}
return resultString;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: RatToString
//
// ARGUMENTS:
// PRAT *representation of a number.
// long representation of base to dump to screen.
// fmt, one of FMT_FLOAT FMT_SCIENTIFIC or FMT_ENGINEERING
// precision uint32_t
//
// RETURN: string
//
// DESCRIPTION: returns a string representation of rational number passed
// in, at least to the precision digits.
//
// NOTE: It may be that doing a GCD() could shorten the rational form
// And it may eventually be worthwhile to keep the result. That is
// why a pointer to the rational is passed in.
//
//-----------------------------------------------------------------------------
wstring RatToString(_Inout_ PRAT& prat, int format, uint32_t radix, int32_t precision)
{
PNUMBER p = RatToNumber(prat, radix, precision);
wstring result = NumberToString(p, format, radix, precision);
destroynum(p);
return result;
}
PNUMBER RatToNumber(_In_ PRAT prat, uint32_t radix, int32_t precision)
{
PRAT temprat = nullptr;
DUPRAT(temprat, prat);
// Convert p and q of rational form from internal base to requested base.
// Scale by largest power of BASEX possible.
long scaleby = min(temprat->pp->exp, temprat->pq->exp);
scaleby = max(scaleby, 0);
temprat->pp->exp -= scaleby;
temprat->pq->exp -= scaleby;
PNUMBER p = nRadixxtonum(temprat->pp, radix, precision);
PNUMBER q = nRadixxtonum(temprat->pq, radix, precision);
destroyrat(temprat);
// finally take the time hit to actually divide.
divnum(&p, q, radix, precision);
destroynum(q);
return p;
}
// Converts a PRAT to a PNUMBER and back to a PRAT, flattening/simplifying the rational in the process
void flatrat(_Inout_ PRAT& prat, uint32_t radix, int32_t precision)
{
PNUMBER pnum = RatToNumber(prat, radix, precision);
destroyrat(prat);
prat = numtorat(pnum, radix);
destroynum(pnum);
}
//-----------------------------------------------------------------------------
//
// FUNCTION: gcd
//
// ARGUMENTS:
// PNUMBER representation of a number.
// PNUMBER representation of a number.
// int for Radix
//
// RETURN: Greatest common divisor in internal BASEX PNUMBER form.
//
// DESCRIPTION: gcd uses remainders to find the greatest common divisor.
//
// ASSUMPTIONS: gcd assumes inputs are integers.
//
// NOTE: Before it was found that the TRIM macro actually kept the
// size down cheaper than GCD, this routine was used extensively.
// now it is not used but might be later.
//
//-----------------------------------------------------------------------------
PNUMBER gcd( _In_ PNUMBER a, _In_ PNUMBER b)
{
PNUMBER r= nullptr;
PNUMBER larger= nullptr;
PNUMBER smaller= nullptr;
if (zernum(a))
{
return b;
}
else if(zernum(b))
{
return a;
}
if (lessnum(a, b))
{
DUPNUM(larger, b);
DUPNUM(smaller, a);
}
else
{
DUPNUM(larger, a);
DUPNUM(smaller, b);
}
while (!zernum(smaller))
{
remnum(&larger, smaller, BASEX);
// swap larger and smaller
r = larger;
larger = smaller;
smaller = r;
}
destroynum(smaller);
return larger;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: longfactnum
//
// ARGUMENTS:
// long integer to factorialize.
// long integer representing base of answer.
// unsigned long integer for radix
//
// RETURN: Factorial of input in radix PNUMBER form.
//
// NOTE: Not currently used.
//
//-----------------------------------------------------------------------------
PNUMBER longfactnum(long inlong, uint32_t radix)
{
PNUMBER lret= nullptr;
PNUMBER tmp= nullptr;
lret = longtonum( 1, radix);
while ( inlong > 0 )
{
tmp = longtonum( inlong--, radix);
mulnum( &lret, tmp, radix);
destroynum( tmp );
}
return( lret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: longprodnum
//
// ARGUMENTS:
// long integer to factorialize.
// long integer representing base of answer.
// unsigned long integer for radix
//
// RETURN: Factorial of input in base PNUMBER form.
//
//-----------------------------------------------------------------------------
PNUMBER longprodnum(long start, long stop, uint32_t radix)
{
PNUMBER lret= nullptr;
PNUMBER tmp= nullptr;
lret = longtonum( 1, radix);
while ( start <= stop )
{
if ( start )
{
tmp = longtonum( start, radix);
mulnum( &lret, tmp, radix);
destroynum( tmp );
}
start++;
}
return( lret );
}
//-----------------------------------------------------------------------------
//
// FUNCTION: numpowlong
//
// ARGUMENTS: root as number power as long and radix of
// number along with the precision value in long.
//
// RETURN: None root is changed.
//
// DESCRIPTION: changes numeric representation of root to
// root ** power. Assumes radix is the radix of root.
//
//-----------------------------------------------------------------------------
void numpowlong( _Inout_ PNUMBER *proot, long power, uint32_t radix, int32_t precision)
{
PNUMBER lret = longtonum( 1, radix );
while ( power > 0 )
{
if ( power & 1 )
{
mulnum( &lret, *proot, radix );
}
mulnum( proot, *proot, radix );
TRIMNUM(*proot, precision);
power >>= 1;
}
destroynum( *proot );
*proot=lret;
}
//-----------------------------------------------------------------------------
//
// FUNCTION: ratpowlong
//
// ARGUMENTS: root as rational, power as long and precision as uint32_t.
//
// RETURN: None root is changed.
//
// DESCRIPTION: changes rational representation of root to
// root ** power.
//
//-----------------------------------------------------------------------------
void ratpowlong( _Inout_ PRAT *proot, long power, int32_t precision)
{
if ( power < 0 )
{
// Take the positive power and invert answer.
PNUMBER pnumtemp = nullptr;
ratpowlong( proot, -power, precision);
pnumtemp = (*proot)->pp;
(*proot)->pp = (*proot)->pq;
(*proot)->pq = pnumtemp;
}
else
{
PRAT lret= nullptr;
lret = longtorat( 1 );
while ( power > 0 )
{
if ( power & 1 )
{
mulnumx( &(lret->pp), (*proot)->pp );
mulnumx( &(lret->pq), (*proot)->pq );
}
mulrat( proot, *proot, precision);
trimit(&lret, precision);
trimit(proot, precision);
power >>= 1;
}
destroyrat( *proot );
*proot=lret;
}
}
|
//
// AnimationCache.cpp
// libraries/animation/src/
//
// Created by Andrzej Kapolka on 4/14/14.
// Copyright (c) 2014 High Fidelity, Inc. All rights reserved.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AnimationCache.h"
#include <QRunnable>
#include <QThreadPool>
#include <shared/QtHelpers.h>
#include <Trace.h>
#include <StatTracker.h>
#include <Profile.h>
#include "AnimationLogging.h"
#include <FBXSerializer.h>
int animationPointerMetaTypeId = qRegisterMetaType<AnimationPointer>();
AnimationCache::AnimationCache(QObject* parent) :
ResourceCache(parent)
{
const qint64 ANIMATION_DEFAULT_UNUSED_MAX_SIZE = 50 * BYTES_PER_MEGABYTES;
setUnusedResourceCacheSize(ANIMATION_DEFAULT_UNUSED_MAX_SIZE);
setObjectName("AnimationCache");
}
AnimationPointer AnimationCache::getAnimation(const QUrl& url) {
return getResource(url).staticCast<Animation>();
}
QSharedPointer<Resource> AnimationCache::createResource(const QUrl& url) {
return QSharedPointer<Animation>(new Animation(url), &Resource::deleter);
}
QSharedPointer<Resource> AnimationCache::createResourceCopy(const QSharedPointer<Resource>& resource) {
return QSharedPointer<Animation>(new Animation(*resource.staticCast<Animation>()), &Resource::deleter);
}
AnimationReader::AnimationReader(const QUrl& url, const QByteArray& data) :
_url(url),
_data(data) {
DependencyManager::get<StatTracker>()->incrementStat("PendingProcessing");
}
void AnimationReader::run() {
DependencyManager::get<StatTracker>()->decrementStat("PendingProcessing");
CounterStat counter("Processing");
PROFILE_RANGE_EX(resource_parse, __FUNCTION__, 0xFF00FF00, 0, { { "url", _url.toString() } });
auto originalPriority = QThread::currentThread()->priority();
if (originalPriority == QThread::InheritPriority) {
originalPriority = QThread::NormalPriority;
}
QThread::currentThread()->setPriority(QThread::LowPriority);
try {
if (_data.isEmpty()) {
throw QString("Reply is NULL ?!");
}
QString urlname = _url.path().toLower();
bool urlValid = true;
urlValid &= !urlname.isEmpty();
urlValid &= !_url.path().isEmpty();
if (urlValid) {
// Parse the FBX directly from the QNetworkReply
HFMModel::Pointer hfmModel;
if (_url.path().toLower().endsWith(".fbx")) {
hfmModel = FBXSerializer().read(_data, QVariantHash(), _url.path());
} else {
QString errorStr("usupported format");
emit onError(299, errorStr);
}
emit onSuccess(hfmModel);
} else {
throw QString("url is invalid");
}
} catch (const QString& error) {
emit onError(299, error);
}
QThread::currentThread()->setPriority(originalPriority);
}
bool Animation::isLoaded() const {
return _loaded && _hfmModel;
}
QStringList Animation::getJointNames() const {
if (QThread::currentThread() != thread()) {
QStringList result;
BLOCKING_INVOKE_METHOD(const_cast<Animation*>(this), "getJointNames",
Q_RETURN_ARG(QStringList, result));
return result;
}
QStringList names;
if (_hfmModel) {
foreach (const HFMJoint& joint, _hfmModel->joints) {
names.append(joint.name);
}
}
return names;
}
QVector<HFMAnimationFrame> Animation::getFrames() const {
if (QThread::currentThread() != thread()) {
QVector<HFMAnimationFrame> result;
BLOCKING_INVOKE_METHOD(const_cast<Animation*>(this), "getFrames",
Q_RETURN_ARG(QVector<HFMAnimationFrame>, result));
return result;
}
if (_hfmModel) {
return _hfmModel->animationFrames;
} else {
return QVector<HFMAnimationFrame>();
}
}
const QVector<HFMAnimationFrame>& Animation::getFramesReference() const {
return _hfmModel->animationFrames;
}
void Animation::downloadFinished(const QByteArray& data) {
// parse the animation/fbx file on a background thread.
AnimationReader* animationReader = new AnimationReader(_url, data);
connect(animationReader, SIGNAL(onSuccess(HFMModel::Pointer)), SLOT(animationParseSuccess(HFMModel::Pointer)));
connect(animationReader, SIGNAL(onError(int, QString)), SLOT(animationParseError(int, QString)));
QThreadPool::globalInstance()->start(animationReader);
}
void Animation::animationParseSuccess(HFMModel::Pointer hfmModel) {
_hfmModel = hfmModel;
finishedLoading(true);
}
void Animation::animationParseError(int error, QString str) {
qCCritical(animation) << "Animation parse error, code =" << error << str;
emit failed(QNetworkReply::UnknownContentError);
finishedLoading(false);
}
|
#include "ros/ros.h"
#include "rplidar_ros_blocking/new_rplidar.h"
void msgCallback(const rplidar_ros_blocking::new_rplidar::ConstPtr& msg){
int count = msg->count;
for(int i=0; i<count; i++)
ROS_INFO("new info : [%f, %f]", msg->degree[i], msg->distance[i]);
}
int main(int argc, char **argv){
ros::init(argc, argv, "new_info");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("new_scan", 1000, msgCallback);
ros::spin();
return 0;
}
|
// -------------------------------------------------------------------------------------------------
// Copyright 2016 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
/// bench for functor dec in simd mode for double type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/dec.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_BENCH_MAIN()
{
using T = bs::pack<double>;
run<T>(bs::dec, nsbg::rand<T>(-10, 10));
}
|
/* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.1 $
// $Date: 2006-01-17 21:12:56 $
// $Source: /usr/local/cvs/OpenSees/SRC/element/forceBeamColumn/LegendreBeamIntegration.cpp,v $
#include <LegendreBeamIntegration.h>
#include <elementAPI.h>
#include <ID.h>
void* OPS_LegendreBeamIntegration(int& integrationTag, ID& secTags)
{
if(OPS_GetNumRemainingInputArgs() < 3) {
opserr<<"insufficient arguments:integrationTag,secTag,N\n";
return 0;
}
// inputs: integrationTag,secTag,N
int iData[3];
int numData = 3;
if(OPS_GetIntInput(&numData,&iData[0]) < 0) return 0;
integrationTag = iData[0];
if(iData[2] > 0) {
secTags.resize(iData[2]);
} else {
secTags = ID();
}
for(int i=0; i<secTags.Size(); i++) {
secTags(i) = iData[1];
}
return new LegendreBeamIntegration;
}
LegendreBeamIntegration::LegendreBeamIntegration():
BeamIntegration(BEAM_INTEGRATION_TAG_Legendre)
{
// Nothing to do
}
LegendreBeamIntegration::~LegendreBeamIntegration()
{
// Nothing to do
}
BeamIntegration*
LegendreBeamIntegration::getCopy(void)
{
return new LegendreBeamIntegration();
}
void
LegendreBeamIntegration::getSectionLocations(int numSections,
double L,
double *xi)
{
switch(numSections) {
case 1:
xi[0] = 0.0;
break;
case 2:
xi[0] = -0.577350269189626;
xi[1] = 0.577350269189626;
break;
case 3:
xi[0] = -0.774596669241483;
xi[1] = 0.0;
xi[2] = 0.774596669241483;
break;
case 4:
xi[0] = -0.861136311594053;
xi[1] = -0.339981043584856;
xi[2] = 0.339981043584856;
xi[3] = 0.861136311594053;
break;
case 5:
xi[0] = -0.906179845938664;
xi[1] = -0.538469310105683;
xi[2] = 0.0;
xi[3] = 0.538469310105683;
xi[4] = 0.906179845938664;
break;
case 6:
xi[0] = -0.932469514203152;
xi[1] = -0.661209386466265;
xi[2] = -0.238619186083197;
xi[3] = 0.238619186083197;
xi[4] = 0.661209386466265;
xi[5] = 0.932469514203152;
break;
case 7:
xi[0] = -0.949107912342759;
xi[1] = -0.741531185599394;
xi[2] = -0.405845151377397;
xi[3] = 0.0;
xi[4] = 0.405845151377397;
xi[5] = 0.741531185599394;
xi[6] = 0.949107912342759;
break;
case 8:
xi[0] = -0.960289856497536;
xi[1] = -0.796666477413627;
xi[2] = -0.525532409916329;
xi[3] = -0.183434642495650;
xi[4] = 0.183434642495650;
xi[5] = 0.525532409916329;
xi[6] = 0.796666477413627;
xi[7] = 0.960289856497536;
break;
case 9:
xi[0] = -0.968160239507626;
xi[1] = -0.836031107326636;
xi[2] = -0.613371432700590;
xi[3] = -0.324253423403809;
xi[4] = 0.0;
xi[5] = 0.324253423403809;
xi[6] = 0.613371432700590;
xi[7] = 0.836031107326636;
xi[8] = 0.968160239507626;
break;
case 10:
xi[0] = -0.973906528517172;
xi[1] = -0.865063366688985;
xi[2] = -0.679409568299024;
xi[3] = -0.433395394129247;
xi[4] = -0.148874338981631;
xi[5] = 0.148874338981631;
xi[6] = 0.433395394129247;
xi[7] = 0.679409568299024;
xi[8] = 0.865063366688985;
xi[9] = 0.973906528517172;
break;
default:
opserr << "LegendreBeamIntegration -- max # integration points is 10\n";
break;
}
for (int i = 0; i < numSections; i++)
xi[i] = 0.5*(xi[i] + 1.0);
}
void
LegendreBeamIntegration::getSectionWeights(int numSections, double L,
double *wt)
{
switch (numSections) {
case 1:
wt[0] = 2.0;
break;
case 2:
wt[0] = 1.0;
wt[1] = 1.0;
break;
case 3:
wt[0] = 0.555555555555556;
wt[1] = 0.888888888888889;
wt[2] = 0.555555555555556;
break;
case 4:
wt[0] = 0.347854845137454;
wt[1] = 0.652145154862546;
wt[2] = 0.652145154862546;
wt[3] = 0.347854845137454;
break;
case 5:
wt[0] = 0.236926885056189;
wt[1] = 0.478628670499366;
wt[2] = 0.568888888888889;
wt[3] = 0.478628670499366;
wt[4] = 0.236926885056189;
break;
case 6:
wt[0] = 0.171324492379170;
wt[1] = 0.360761573048139;
wt[2] = 0.467913934572691;
wt[3] = 0.467913934572691;
wt[4] = 0.360761573048139;
wt[5] = 0.171324492379170;
break;
case 7:
wt[0] = 0.129484966168870;
wt[1] = 0.279705391489277;
wt[2] = 0.381830050505119;
wt[3] = 0.417959183673469;
wt[4] = 0.381830050505119;
wt[5] = 0.279705391489277;
wt[6] = 0.129484966168870;
break;
case 8:
wt[0] = 0.101228536290376;
wt[1] = 0.222381034453374;
wt[2] = 0.313706645877887;
wt[3] = 0.362683783378362;
wt[4] = 0.362683783378362;
wt[5] = 0.313706645877887;
wt[6] = 0.222381034453374;
wt[7] = 0.101228536290376;
break;
case 9:
wt[0] = 0.081274388361574;
wt[1] = 0.180648160694857;
wt[2] = 0.260610696402935;
wt[3] = 0.312347077040003;
wt[4] = 0.330239355001260;
wt[5] = 0.312347077040003;
wt[6] = 0.260610696402935;
wt[7] = 0.180648160694857;
wt[8] = 0.081274388361574;
break;
case 10:
wt[0] = 0.066671344308688;
wt[1] = 0.149451349150581;
wt[2] = 0.219086362515982;
wt[3] = 0.269266719309996;
wt[4] = 0.295524224714753;
wt[5] = 0.295524224714753;
wt[6] = 0.269266719309996;
wt[7] = 0.219086362515982;
wt[8] = 0.149451349150581;
wt[9] = 0.066671344308688;
break;
default:
opserr << "LegendreBeamIntegration -- max # integration points is 10\n";
break;
}
for (int i = 0; i < numSections; i++)
wt[i] *= 0.5;
}
void
LegendreBeamIntegration::Print(OPS_Stream &s, int flag)
{
if (flag == OPS_PRINT_PRINTMODEL_JSON) {
s << "{\"type\": \"Legendre\"}";
}
else {
s << "Legendre" << endln;
}
}
|
// Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include "muduo/net/EventLoop.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/Channel.h"
#include "muduo/net/Poller.h"
#include "muduo/net/SocketsOps.h"
#include "muduo/net/TimerQueue.h"
#include <algorithm>
#include <signal.h>
#include <sys/eventfd.h>
#include <unistd.h>
using namespace muduo;
using namespace muduo::net;
//应用编程(直接使用c c++ 以及网络库代码,不使用系统调用)
//系统编程 (c c++ 系统调用)
namespace //匿名的命名空间,建议在cpp文件中使用
{ //当前线程eventloop对象指针
//线程局部存储
__thread EventLoop *t_loopInThisThread = 0; //初始化是空指针
const int kPollTimeMs = 10000;
int createEventfd() //初始化weakupfd用于唤醒线程
{
int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); //重点
if (evtfd < 0)
{
LOG_SYSERR << "Failed in eventfd";
abort();
}
return evtfd;
}
#pragma GCC diagnostic ignored "-Wold-style-cast"
class IgnoreSigPipe
{
public:
IgnoreSigPipe() //程序的构造函数
{
::signal(SIGPIPE, SIG_IGN); //忽略信号SIGPIPE,我们的服务器不能因为一个客户端不正常退出而挂掉
// LOG_TRACE << "Ignore SIGPIPE";
}
};
#pragma GCC diagnostic error "-Wold-style-cast"
IgnoreSigPipe initObj; //这个类在构造的时候就调用了signal(SIGPIPE, SIG_IGN);
} // namespace
EventLoop *EventLoop::getEventLoopOfCurrentThread()
{
return t_loopInThisThread;
}
EventLoop::EventLoop() //调用构造函数创建对象
: looping_(false),
quit_(false),
eventHandling_(false),
callingPendingFunctors_(false),
iteration_(0),
threadId_(CurrentThread::tid()),
poller_(Poller::newDefaultPoller(this)), //构造了一个Poller实体对象,是ppoller或者epoller,通过newdefaultpoller函数来判断
timerQueue_(new TimerQueue(this)),
wakeupFd_(createEventfd()), //创建一个eventfd
wakeupChannel_(new Channel(this, wakeupFd_)),
currentActiveChannel_(NULL)
{
LOG_DEBUG << "EventLoop created " << this << " in thread " << threadId_; //没个线程最多有一个eventloop对象
if (t_loopInThisThread)
{ //如果当前线程已经创建了eventloop对象,终止log_fatal
LOG_FATAL << "Another EventLoop " << t_loopInThisThread
<< " exists in this thread " << threadId_;
}
else
{
t_loopInThisThread = this; //否则将刚创建的线程付给指针
}
wakeupChannel_->setReadCallback(
std::bind(&EventLoop::handleRead, this)); //注册wakeup的回调函数
// we are always reading the wakeupfd
wakeupChannel_->enableReading(); //在这里纳入到poller管理,以便于唤醒
}
EventLoop::~EventLoop() //析构函数变量滞空
{
LOG_DEBUG << "EventLoop " << this << " of thread " << threadId_
<< " destructs in thread " << CurrentThread::tid();
wakeupChannel_->disableAll();
wakeupChannel_->remove();
::close(wakeupFd_);
t_loopInThisThread = NULL;
}
//这个函数中,首先调用I/O复用,等待着有激活事件的发生,将所有的被激活的事件存放到activeChannels中,
//然后调用每个Channel的handleEvent函数(还记得这个函数的威力么,在这个函数内,来辨别这个套接字上的
//可读可写事件,然后调用readCallback_ writeCallback_closeCallback_等一系列的函数,这些函数是
//Acceptor和TcpConnection中的handleReadhandleWrite handleClose函数,而这些函数中调用了用户层
//定义的通过TcpServer传递渗透到TcpConnection中的消息处理函数)
void EventLoop::loop() //io线程
{ //事件循环,该函数不能跨线程调用,只能在创建该对象的线程中调用
assert(!looping_); //断言处于创建该线程对象中
assertInLoopThread();
looping_ = true;
quit_ = false; // FIXME: what if someone calls quit() before loop() ?
LOG_TRACE << "EventLoop " << this << " start looping";
while (!quit_)
{
activeChannels_.clear();
pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_); //kPolltimems是超时时间,这个超时时间默认给的10s,相当于一直没有时间10s之后返回一次
++iteration_;
if (Logger::logLevel() <= Logger::TRACE)
{
printActiveChannels(); //日志处理
}
// TODO sort channel by priority
eventHandling_ = true;
for (Channel *channel : activeChannels_)
{
currentActiveChannel_ = channel; //当前遍历的通道
currentActiveChannel_->handleEvent(pollReturnTime_); //处理事件,一般一些io操作
}
currentActiveChannel_ = NULL; //全部处理完
eventHandling_ = false;
doPendingFunctors(); //让io线程除了io操作,也能执行一些任务,可以添加一些计算任务比较小的,来让他们执行,
//还有就是主线程accept新连接的的套接字传下来,注册到该eventloop的读事件
}
LOG_TRACE << "EventLoop " << this << " stop looping";
looping_ = false;
}
void EventLoop::quit() //该函数可以跨线程调用,不一定总是在io线程调用
{
quit_ = true; //quit置为true,上面eventloop中的loop直接就退出了
// There is a chance that loop() just executes while(!quit_) and exists,
// then EventLoop destructs, then we are accessing an invalid object.
// Can be fixed using mutex_ in both places.
if (!isInLoopThread()) //如果不是io线程,先wakeup唤醒
{
wakeup(); //因为如果不是在io线程调用,现在需要quit的io线程很可能还是poll的阻塞状态或者是在处理事件,所以需要先weekup
//需要一个唤醒通道,需要管道,eventfd
}
}
// 在io线程中执行某个回调函数,该函数可以保证不用锁的情况下可以跨线程调用
void EventLoop::runInLoop(Functor cb) //因为有了runinloop这个函数,我们就可以添加部分任务让io线程执行,
//如果是当前io线程,就直接执行,不是当前io线程,则添加到queueinloop
{
if (isInLoopThread())
{
cb(); //如果当前是io线程调用runinloop,则同步调用cb
}
else
{
queueInLoop(std::move(cb)); //如果是其他线程调用runinloop,则异步的将cb添加到队列
}
}
void EventLoop::queueInLoop(Functor cb) //将任务添加到队列中
{
{
MutexLockGuard lock(mutex_);
pendingFunctors_.push_back(std::move(cb)); //将任务添加到队列中
}
//调用queuelnloop的线程不是当前io线程,为了让任务执行,需要唤醒那个io线程,不然任务很可能因此阻塞
//或者调用queuelnloop的线程是当前io线程,并且此时正在调用pending functor,需要唤醒
//只有当前io线程的事件回调中调用queueinloop才不需要唤醒
if (!isInLoopThread() || callingPendingFunctors_)
{
wakeup();
}
}
size_t EventLoop::queueSize() const
{
MutexLockGuard lock(mutex_);
return pendingFunctors_.size();
}
TimerId EventLoop::runAt(const Timestamp &time, TimerCallback cb)
{ //在某个时间运行定时器任务
return timerQueue_->addTimer(std::move(cb), time, 0.0); //把cb添加
}
TimerId EventLoop::runAfter(double delay, TimerCallback cb)
{ //在过多久之后运行定时器任务
Timestamp time(addTime(Timestamp::now(), delay));
return runAt(time, std::move(cb));
}
TimerId EventLoop::runEvery(double interval, TimerCallback cb)
{ //每过多久就运行一次定时器事件
Timestamp time(addTime(Timestamp::now(), interval)); //间隔时间传递进去
return timerQueue_->addTimer(std::move(cb), time, interval);
}
void EventLoop::cancel(TimerId timerId)
{
return timerQueue_->cancel(timerId);
}
void EventLoop::updateChannel(Channel *channel)
{
assert(channel->ownerLoop() == this); //channel是属于本对象的才可以用
assertInLoopThread();
poller_->updateChannel(channel); //调用了poller的update
}
//调用这个函数前确保调用了disableAll
void EventLoop::removeChannel(Channel *channel)
{
assert(channel->ownerLoop() == this);
assertInLoopThread();
if (eventHandling_)
{
assert(currentActiveChannel_ == channel ||
std::find(activeChannels_.begin(), activeChannels_.end(), channel) == activeChannels_.end());
}
poller_->removeChannel(channel);
}
bool EventLoop::hasChannel(Channel *channel)
{
assert(channel->ownerLoop() == this);
assertInLoopThread();
return poller_->hasChannel(channel);
}
void EventLoop::abortNotInLoopThread()
{ //如果不在此线程调用,则直接退出
LOG_FATAL << "EventLoop::abortNotInLoopThread - EventLoop " << this
<< " was created in threadId_ = " << threadId_
<< ", current thread id = " << CurrentThread::tid();
}
void EventLoop::wakeup() //一个线程可以唤醒另一个io线程
{
uint64_t one = 1;
ssize_t n = sockets::write(wakeupFd_, &one, sizeof one); //写入,给wakeupfd写入数据,一定就唤醒了
if (n != sizeof one)
{
LOG_ERROR << "EventLoop::wakeup() writes " << n << " bytes instead of 8";
}
}
void EventLoop::handleRead() //weakup操作
{
uint64_t one = 1; //象征性的读一些数据
ssize_t n = sockets::read(wakeupFd_, &one, sizeof one); //调用read函数
if (n != sizeof one)
{
LOG_ERROR << "EventLoop::handleRead() reads " << n << " bytes instead of 8";
}
}
void EventLoop::doPendingFunctors()
{
std::vector<Functor> functors;
callingPendingFunctors_ = true; //现在状态处于PendingFunctors_
{
MutexLockGuard lock(mutex_); //保护临界区
functors.swap(pendingFunctors_); //进行交换,避免了死锁出现
//这样一方面减小了临界区的长度(意味着不会阻塞其他线程的queueinloop()),
//另一方面,也避免了死锁,(因为functor可能会在次调用queueinloop())
}
for (const Functor &functor : functors)
{
functor(); //遍历函数列表,不需要加锁了
//由于dopendingfunctors()调用的functor可能会再次调用queueinloop(cb),这时
//queueinloop()就必须wakeup(),否则新增的cb可能就不能及时调用了
}
callingPendingFunctors_ = false;
//没有反复调用dopendingfunctor()直到pendingfunctors为空,这是有意的,否则
//io线程可能会陷入死循环,无法处理io事件
}
void EventLoop::printActiveChannels() const
{
for (const Channel *channel : activeChannels_)
{
LOG_TRACE << "{" << channel->reventsToString() << "} ";
}
}
|
/*
* DIPlib 3.0
* This file contains definitions for look-up tables and related functionality
*
* (c)2017, Cris Luengo.
* Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
*
* 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.
*/
#include "diplib.h"
#include "diplib/lookup_table.h"
#include "diplib/framework.h"
#include "diplib/pixel_table.h"
#include "diplib/overload.h"
namespace dip {
namespace {
template< typename TPI >
inline void FillPixel( TPI* out, dip::uint length, dip::sint stride, TPI value ) {
for( dip::uint ii = 0; ii < length; ++ii ) {
*out = value;
out += stride;
}
}
template< typename TPI >
inline void CopyPixel( TPI const* in, TPI* out, dip::uint length, dip::sint inStride, dip::sint outStride ) {
for( dip::uint ii = 0; ii < length; ++ii ) {
*out = *in;
in += inStride;
out += outStride;
}
}
template< typename TPI >
inline void CopyPixelWithInterpolation( TPI const* in, TPI* out,
dip::uint length, dip::sint inStride, dip::sint outStride,
dfloat fraction, dip::sint interpStride ) {
for( dip::uint ii = 0; ii < length; ++ii ) {
*out = static_cast< TPI >( static_cast< dfloat >( *in ) * ( 1 - fraction ) + static_cast< dfloat >( *( in + interpStride )) * fraction );
in += inStride;
out += outStride;
}
}
template< typename TPI >
inline void CopyPixelWithInterpolation( std::complex< TPI > const* in, std::complex< TPI >* out,
dip::uint length, dip::sint inStride, dip::sint outStride,
dfloat fraction, dip::sint interpStride ) {
for( dip::uint ii = 0; ii < length; ++ii ) {
*out = *in * static_cast< TPI >( 1 - fraction ) + *( in + interpStride ) * static_cast< TPI >( fraction );
in += inStride;
out += outStride;
}
}
template< typename TPI >
class dip__DirectLUT_Integer : public Framework::ScanLineFilter {
// Applies the LUT with data type TPI, and no index, to an input image of type uint64.
public:
virtual dip::uint GetNumberOfOperations( dip::uint, dip::uint, dip::uint ) override { return 3; }
virtual void Filter( Framework::ScanLineFilterParameters const& params ) override {
uint64 const* in = static_cast< uint64 const* >( params.inBuffer[ 0 ].buffer );
auto bufferLength = params.bufferLength;
auto inStride = params.inBuffer[ 0 ].stride;
TPI* out = static_cast< TPI* >( params.outBuffer[ 0 ].buffer );
auto outStride = params.outBuffer[ 0 ].stride;
auto tensorLength = params.outBuffer[ 0 ].tensorLength;
auto outTensorStride = params.outBuffer[ 0 ].tensorStride;
TPI const* values = static_cast< TPI const* >( values_.Origin() );
auto valuesStride = values_.Stride( 0 );
auto valuesTensorStride = values_.TensorStride();
DIP_ASSERT( values_.DataType() == DataType( TPI( 0 )));
DIP_ASSERT( values_.TensorElements() == tensorLength );
dip::uint maxIndex = values_.Size( 0 ) - 1;
for( dip::uint ii = 0; ii < bufferLength; ++ii ) {
dip::uint index = *in;
if( index > maxIndex ) {
switch( outOfBoundsMode_ ) {
case LookupTable::OutOfBoundsMode::USE_OUT_OF_BOUNDS_VALUE:
FillPixel( out, tensorLength, outTensorStride, outOfBoundsUpperValue_ );
break;
case LookupTable::OutOfBoundsMode::KEEP_INPUT_VALUE:
FillPixel( out, tensorLength, outTensorStride, clamp_cast< TPI >( index ) );
break;
//case LookupTable::OutOfBoundsMode::CLAMP_TO_RANGE:
default:
CopyPixel( values + static_cast< dip::sint >( maxIndex ) * valuesStride, out, tensorLength, valuesTensorStride, outTensorStride );
break;
}
} else {
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength, valuesTensorStride, outTensorStride );
}
in += inStride;
out += outStride;
}
}
dip__DirectLUT_Integer( Image const& values, LookupTable::OutOfBoundsMode outOfBoundsMode, dfloat outOfBoundsLowerValue, dfloat outOfBoundsUpperValue )
: values_( values ), outOfBoundsMode_( outOfBoundsMode ), outOfBoundsLowerValue_( clamp_cast< TPI >( outOfBoundsLowerValue )),
outOfBoundsUpperValue_( clamp_cast< TPI >( outOfBoundsUpperValue )) {}
private:
Image const& values_;
LookupTable::OutOfBoundsMode outOfBoundsMode_;
TPI outOfBoundsLowerValue_;
TPI outOfBoundsUpperValue_;
};
template< typename TPI >
class dip__DirectLUT_Float : public Framework::ScanLineFilter {
// Applies the LUT with data type TPI, and no index, to an input image of type dfloat.
public:
virtual dip::uint GetNumberOfOperations( dip::uint, dip::uint, dip::uint ) override {
return interpolation_ == LookupTable::InterpolationMode::LINEAR ? 9 : 3;
}
virtual void Filter( Framework::ScanLineFilterParameters const& params ) override {
dfloat const* in = static_cast< dfloat const* >( params.inBuffer[ 0 ].buffer );
auto bufferLength = params.bufferLength;
auto inStride = params.inBuffer[ 0 ].stride;
TPI* out = static_cast< TPI* >( params.outBuffer[ 0 ].buffer );
auto outStride = params.outBuffer[ 0 ].stride;
auto tensorLength = params.outBuffer[ 0 ].tensorLength;
auto outTensorStride = params.outBuffer[ 0 ].tensorStride;
TPI const* values = static_cast< TPI const* >( values_.Origin() );
auto valuesStride = values_.Stride( 0 );
auto valuesTensorStride = values_.TensorStride();
DIP_ASSERT( values_.DataType() == DataType( TPI( 0 )));
DIP_ASSERT( values_.TensorElements() == tensorLength );
dip::uint maxIndex = values_.Size( 0 ) - 1;
for( dip::uint ii = 0; ii < bufferLength; ++ii ) {
if(( *in < 0 ) || ( *in > static_cast< dfloat >( maxIndex ))) {
switch( outOfBoundsMode_ ) {
case LookupTable::OutOfBoundsMode::USE_OUT_OF_BOUNDS_VALUE:
FillPixel( out, tensorLength, outTensorStride, *in < 0 ? outOfBoundsLowerValue_ : outOfBoundsUpperValue_ );
break;
case LookupTable::OutOfBoundsMode::KEEP_INPUT_VALUE:
FillPixel( out, tensorLength, outTensorStride, clamp_cast< TPI >( *in ) );
break;
//case LookupTable::OutOfBoundsMode::CLAMP_TO_RANGE:
default:
TPI const* tval = values + ( *in < 0.0 ? 0 : static_cast< dip::sint >( maxIndex )) * valuesStride;
CopyPixel( tval, out, tensorLength, valuesTensorStride, outTensorStride );
break;
}
} else {
switch( interpolation_ ) {
case LookupTable::InterpolationMode::LINEAR: {
dip::uint index = static_cast< dip::uint >( *in );
dfloat fraction = *in - static_cast< dfloat >( index );
if( fraction == 0.0 ) {
// not just to avoid the extra computation, it especially avoids out-of-bounds indexing if in points at the last LUT element.
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength,
valuesTensorStride, outTensorStride );
} else {
CopyPixelWithInterpolation( values + static_cast< dip::sint >( index ) * valuesStride,
out, tensorLength, valuesTensorStride, outTensorStride,
fraction, valuesStride );
}
break;
}
case LookupTable::InterpolationMode::NEAREST_NEIGHBOR: {
dip::uint index = static_cast< dip::uint >( *in + 0.5 );
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength,
valuesTensorStride, outTensorStride );
break;
}
case LookupTable::InterpolationMode::ZERO_ORDER_HOLD: {
dip::uint index = static_cast< dip::uint >( *in );
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength,
valuesTensorStride, outTensorStride );
break;
}
}
}
in += inStride;
out += outStride;
}
}
dip__DirectLUT_Float( Image const& values, LookupTable::OutOfBoundsMode outOfBoundsMode, dfloat outOfBoundsLowerValue,
dfloat outOfBoundsUpperValue, LookupTable::InterpolationMode interpolation )
: values_( values ), outOfBoundsMode_( outOfBoundsMode ), outOfBoundsLowerValue_( clamp_cast< TPI >( outOfBoundsLowerValue )),
outOfBoundsUpperValue_( clamp_cast< TPI >( outOfBoundsUpperValue )), interpolation_( interpolation ) {}
private:
Image const& values_;
LookupTable::OutOfBoundsMode outOfBoundsMode_;
TPI outOfBoundsLowerValue_;
TPI outOfBoundsUpperValue_;
LookupTable::InterpolationMode interpolation_;
};
template< typename TPI >
class dip__IndexedLUT_Float : public Framework::ScanLineFilter {
// Applies the LUT with data type TPI, and an index, to an input image of type dfloat.
public:
virtual dip::uint GetNumberOfOperations( dip::uint, dip::uint, dip::uint ) override {
return interpolation_ == LookupTable::InterpolationMode::LINEAR ? 9 : 3;
}
virtual void Filter( Framework::ScanLineFilterParameters const& params ) override {
dfloat const* in = static_cast< dfloat const* >( params.inBuffer[ 0 ].buffer );
auto bufferLength = params.bufferLength;
auto inStride = params.inBuffer[ 0 ].stride;
TPI* out = static_cast< TPI* >( params.outBuffer[ 0 ].buffer );
auto outStride = params.outBuffer[ 0 ].stride;
auto tensorLength = params.outBuffer[ 0 ].tensorLength;
auto outTensorStride = params.outBuffer[ 0 ].tensorStride;
TPI const* values = static_cast< TPI const* >( values_.Origin() );
auto valuesStride = values_.Stride( 0 );
auto valuesTensorStride = values_.TensorStride();
DIP_ASSERT( values_.DataType() == DataType( TPI( 0 )));
DIP_ASSERT( values_.TensorElements() == tensorLength );
dip::uint maxIndex = values_.Size( 0 ) - 1;
for( dip::uint ii = 0; ii < bufferLength; ++ii ) {
if(( *in < index_.front() ) || ( *in > index_.back() )) {
switch( outOfBoundsMode_ ) {
case LookupTable::OutOfBoundsMode::USE_OUT_OF_BOUNDS_VALUE:
FillPixel( out, tensorLength, outTensorStride, *in < index_.front() ? outOfBoundsLowerValue_ : outOfBoundsUpperValue_ );
break;
case LookupTable::OutOfBoundsMode::KEEP_INPUT_VALUE:
FillPixel( out, tensorLength, outTensorStride, clamp_cast< TPI >( *in ) );
break;
//case LookupTable::OutOfBoundsMode::CLAMP_TO_RANGE:
default:
TPI const* tval = values + ( *in < index_.front() ? 0 : static_cast< dip::sint >( maxIndex )) * valuesStride;
CopyPixel( tval, out, tensorLength, valuesTensorStride, outTensorStride );
break;
}
} else {
auto upper = std::upper_bound( index_.begin(), index_.end(), *in ); // index_[upper] > *in
dip::uint index = static_cast< dip::uint >( std::distance( index_.begin(), upper )) - 1; // index_[index] <= *in
// Because *in >= index_.front(), we can always subtract 1 from the distance.
switch( interpolation_ ) {
case LookupTable::InterpolationMode::LINEAR:
if( *in == index_[ index ] ) {
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength,
valuesTensorStride, outTensorStride );
} else {
dfloat fraction = ( *in - index_[ index ] ) / ( index_[ index + 1 ] - index_[ index ] );
CopyPixelWithInterpolation( values + static_cast< dip::sint >( index ) * valuesStride,
out, tensorLength, valuesTensorStride, outTensorStride,
fraction, valuesStride );
}
break;
case LookupTable::InterpolationMode::NEAREST_NEIGHBOR:
if(( *in != index_[ index ] ) && (( *in - index_[ index ] ) > ( index_[ index + 1 ] - *in ))) {
// (the `!=` test above is to avoid out-of-bounds indexing with `index+1`)
++index;
}
// fallthrough
case LookupTable::InterpolationMode::ZERO_ORDER_HOLD:
CopyPixel( values + static_cast< dip::sint >( index ) * valuesStride, out, tensorLength,
valuesTensorStride, outTensorStride );
break;
}
}
in += inStride;
out += outStride;
}
}
dip__IndexedLUT_Float( Image const& values, FloatArray const& index, LookupTable::OutOfBoundsMode outOfBoundsMode,
dfloat outOfBoundsLowerValue, dfloat outOfBoundsUpperValue, LookupTable::InterpolationMode interpolation )
: values_( values ), index_( index ), outOfBoundsMode_( outOfBoundsMode ), outOfBoundsLowerValue_( clamp_cast< TPI >( outOfBoundsLowerValue )),
outOfBoundsUpperValue_( clamp_cast< TPI >( outOfBoundsUpperValue )), interpolation_( interpolation ) {}
private:
Image const& values_;
FloatArray const& index_;
LookupTable::OutOfBoundsMode outOfBoundsMode_;
TPI outOfBoundsLowerValue_;
TPI outOfBoundsUpperValue_;
LookupTable::InterpolationMode interpolation_;
};
template< typename TPI >
class dip__IndexedArrayLUT_Float : public Framework::ScanLineFilter {
// Applies the LUT consisting of an array of value images with data type TPI, and an index, to an input image of type dfloat.
public:
virtual dip::uint GetNumberOfOperations( dip::uint, dip::uint, dip::uint ) override {
return interpolation_ == LookupTable::InterpolationMode::LINEAR ? 9 : 3;
}
virtual void Filter( Framework::ScanLineFilterParameters const& params ) override {
// inBuffer[0] is the input image; the remaining inBuffer elements contain the value images
Framework::ScanBuffer const& inBuffer = params.inBuffer[ 0 ];
Framework::ScanBuffer const& firstValueBuffer = params.inBuffer[ 1 ];
dfloat const* in = static_cast< dfloat const* >( inBuffer.buffer );
std::vector< TPI > values( 2 * inBuffer.tensorLength ); // Contains two pixels
dip::uint numValueImages = params.inBuffer.size() - 1;
auto bufferLength = params.bufferLength;
auto inStride = inBuffer.stride;
TPI* out = static_cast< TPI* >( params.outBuffer[ 0 ].buffer );
auto outStride = params.outBuffer[ 0 ].stride;
auto tensorLength = params.outBuffer[ 0 ].tensorLength;
auto outTensorStride = params.outBuffer[ 0 ].tensorStride;
auto valuesStride = firstValueBuffer.stride;
dip::sint valueImageOffset = 0;
auto valuesTensorStride = firstValueBuffer.tensorStride;
DIP_ASSERT( firstValueBuffer.tensorLength == tensorLength );
dip::uint maxIndex = numValueImages - 1;
for( dip::uint ii = 0; ii < bufferLength; ++ii ) {
if(( *in < index_.front() ) || ( *in > index_.back() )) {
switch( outOfBoundsMode_ ) {
case LookupTable::OutOfBoundsMode::USE_OUT_OF_BOUNDS_VALUE:
FillPixel( out, tensorLength, outTensorStride, *in < index_.front() ? outOfBoundsLowerValue_ : outOfBoundsUpperValue_ );
break;
case LookupTable::OutOfBoundsMode::KEEP_INPUT_VALUE:
FillPixel( out, tensorLength, outTensorStride, clamp_cast< TPI >( *in ));
break;
//case LookupTable::OutOfBoundsMode::CLAMP_TO_RANGE:
default:
dip::uint index = ( *in < index_.front() ? 0 : maxIndex );
FetchValues( params.inBuffer, values, index, valueImageOffset, tensorLength, valuesTensorStride );
CopyPixel( values.data(), out, tensorLength, valuesTensorStride, outTensorStride );
break;
}
} else {
auto upper = std::upper_bound( index_.begin(), index_.end(), *in ); // index_[upper] > *in
dip::uint index = static_cast< dip::uint >(std::distance( index_.begin(), upper )) - 1; // index_[index] <= *in
// Because *in >= index_.front(), we can always subtract 1 from the distance.
switch( interpolation_ ) {
case LookupTable::InterpolationMode::LINEAR:
if( *in == index_[ index ] ) {
FetchValues( params.inBuffer, values, index, valueImageOffset, tensorLength, valuesTensorStride );
CopyPixel( values.data(), out, tensorLength, valuesTensorStride, outTensorStride );
} else {
dfloat fraction = ( *in - index_[ index ] ) / ( index_[ index + 1 ] - index_[ index ] );
FetchValuesForInterpolation( params.inBuffer, values, index, valueImageOffset, tensorLength, valuesTensorStride );
CopyPixelWithInterpolation( values.data(), out, tensorLength, valuesTensorStride,
outTensorStride, fraction, valuesStride );
}
break;
case LookupTable::InterpolationMode::NEAREST_NEIGHBOR:
if(( *in != index_[ index ] ) && (( *in - index_[ index ] ) > ( index_[ index + 1 ] - *in ))) {
// (the `!=` test above is to avoid out-of-bounds indexing with `index+1`)
++index;
}
// fallthrough
case LookupTable::InterpolationMode::ZERO_ORDER_HOLD:
FetchValues( params.inBuffer, values, index, valueImageOffset, tensorLength, valuesTensorStride );
CopyPixel( values.data(), out, tensorLength, valuesTensorStride, outTensorStride );
break;
}
}
in += inStride;
out += outStride;
valueImageOffset += valuesStride;
}
}
dip__IndexedArrayLUT_Float(
FloatArray const& index, LookupTable::OutOfBoundsMode outOfBoundsMode,
dfloat outOfBoundsLowerValue, dfloat outOfBoundsUpperValue, LookupTable::InterpolationMode interpolation
) : index_( index ), outOfBoundsMode_( outOfBoundsMode ), outOfBoundsLowerValue_( clamp_cast< TPI >( outOfBoundsLowerValue )),
outOfBoundsUpperValue_( clamp_cast< TPI >( outOfBoundsUpperValue )), interpolation_( interpolation ) {}
private:
FloatArray const& index_;
LookupTable::OutOfBoundsMode outOfBoundsMode_;
TPI outOfBoundsLowerValue_;
TPI outOfBoundsUpperValue_;
LookupTable::InterpolationMode interpolation_;
void FetchValues( std::vector< Framework::ScanBuffer > const& valueImages, std::vector< TPI >& values,
dip::uint valueImageIndex, dip::sint valueImageOffset, dip::uint tensorLength, dip::sint tensorStride, dip::uint localValueIndex = 0 ) {
dip::uint scanBufferIndex = valueImageIndex + 1; // The first image is the in-image; all others are value images
TPI const* valuePtr = static_cast< TPI const* >( valueImages[ scanBufferIndex ].buffer ) + valueImageOffset;
dip::uint valIndex = localValueIndex * tensorLength;
for( dip::uint iT = 0; iT < tensorLength; ++iT ) {
values[ valIndex ] = *valuePtr;
++valIndex;
valuePtr += tensorStride;
}
}
void FetchValuesForInterpolation( std::vector< Framework::ScanBuffer > const& valueImages, std::vector< TPI >& values,
dip::uint valueImageIndex, dip::sint valueImageOffset, dip::uint tensorLength, dip::sint tensorStride ) {
FetchValues( valueImages, values, valueImageIndex, valueImageOffset, tensorLength, tensorStride, 0 );
FetchValues( valueImages, values, valueImageIndex + 1, valueImageOffset, tensorLength, tensorStride, 1 );
}
};
}
void LookupTable::Apply( Image const& in, Image& out, InterpolationMode interpolation ) const {
DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED );
DIP_THROW_IF( !in.IsScalar(), E::IMAGE_NOT_SCALAR );
DIP_THROW_IF( !in.DataType().IsReal(), E::DATA_TYPE_NOT_SUPPORTED );
if( valueImages_.empty() ) {
std::unique_ptr< Framework::ScanLineFilter >scanLineFilter;
dip::DataType inBufType;
if( HasIndex() ) {
DIP_OVL_NEW_ALL( scanLineFilter, dip__IndexedLUT_Float, (values_, index_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_, interpolation), values_.DataType() );
inBufType = DT_DFLOAT;
} else {
if( in.DataType().IsUnsigned() ) {
DIP_OVL_NEW_ALL( scanLineFilter, dip__DirectLUT_Integer, (values_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_), values_.DataType() );
inBufType = DT_UINT64;
} else {
DIP_OVL_NEW_ALL( scanLineFilter, dip__DirectLUT_Float, (values_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_, interpolation), values_.DataType() );
inBufType = DT_DFLOAT;
}
}
ImageRefArray outar{ out };
DIP_STACK_TRACE_THIS( Scan( { in }, outar, { inBufType }, { values_.DataType() }, { values_.DataType() }, { values_.TensorElements() }, *scanLineFilter ) );
} else {
// Input images: [ in, valueImages_... ]
dip::DataType valuesDataType = valueImages_.front().get().DataType();
ImageConstRefArray inRefs = valueImages_;
inRefs.insert( inRefs.begin(), in );
// Input buffer data types: [ DFLOAT, valsDataType... ]
// The input buffer type for `in` is chosen as DFLOAT so that these values can be easily looked up in the bins array
DataTypeArray inBufferTypes( valueImages_.size(), valuesDataType );
inBufferTypes.insert( 0, DT_DFLOAT );
//inBufferTypes.insert( 0, in.DataType() );
// Obtain output data type that can hold interpolated values between vals
dip::DataType outDataType = DataType::SuggestFlex( valuesDataType );
DataTypeArray outBufferTypes( { outDataType } );
ImageRefArray outRefs{ out };
// Call Scan framework
std::unique_ptr< Framework::ScanLineFilter > scanLineFilter;
DIP_OVL_NEW_ALL( scanLineFilter, dip__IndexedArrayLUT_Float, ( index_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_, interpolation ), outDataType );
DIP_STACK_TRACE_THIS( Scan( inRefs, outRefs, inBufferTypes, outBufferTypes, { outDataType }, { valueImages_.front().get().TensorElements() }, *scanLineFilter, Framework::ScanOption::TensorAsSpatialDim ));
}
out.ReshapeTensor( values_.Tensor() );
out.SetColorSpace( values_.ColorSpace() );
}
Image::Pixel LookupTable::Apply( dfloat value, InterpolationMode interpolation ) const {
DIP_ASSERT( valueImages_.empty() );
std::unique_ptr< Framework::ScanLineFilter >scanLineFilter;
if( HasIndex() ) {
DIP_OVL_NEW_ALL( scanLineFilter, dip__IndexedLUT_Float, ( values_, index_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_, interpolation ), values_.DataType() );
} else {
DIP_OVL_NEW_ALL( scanLineFilter, dip__DirectLUT_Float, ( values_, outOfBoundsMode_, outOfBoundsLowerValue_, outOfBoundsUpperValue_, interpolation ), values_.DataType() );
}
Image::Pixel out( values_.DataType(), values_.TensorElements() );
out.ReshapeTensor( values_.Tensor() );
std::vector< Framework::ScanBuffer > inBuffers( 1 );
inBuffers[ 0 ] = { &value, 1, 1, 1 };
std::vector< Framework::ScanBuffer > outBuffers( 1 );
outBuffers[ 0 ] = { out.Origin(), 1, out.TensorStride(), out.TensorElements() };
Framework::ScanLineFilterParameters params{ inBuffers, outBuffers, 1 /* bufferLength = 1 pixel */, 0, {}, false, 0 };
scanLineFilter->Filter( params );
return out;
}
} // namespace dip
#ifdef DIP__ENABLE_DOCTEST
#include "doctest.h"
#include "diplib/iterators.h"
DOCTEST_TEST_CASE( "[DIPlib] testing dip::LookupTable" ) {
// LUT without index
dip::Image lutIm( { 10 }, 3, dip::DT_SFLOAT );
dip::ImageIterator< dip::sfloat > lutIt( lutIm );
dip::sfloat v = 10;
do {
*lutIt = v;
++v;
} while( ++lutIt );
dip::LookupTable lut1( lutIm );
lut1.SetOutOfBoundsValue( 255 );
DOCTEST_CHECK( !lut1.HasIndex() );
DOCTEST_CHECK( lut1.DataType() == dip::DT_SFLOAT );
// Case 1: uint image
dip::Image img1( { 5, 3 }, 1, dip::DT_UINT16 );
dip::ImageIterator< dip::uint16 > imgIt1( img1 );
dip::uint16 ii = 0;
do {
*imgIt1 = ii;
++ii;
} while( ++imgIt1 );
dip::Image out1 = lut1.Apply( img1 );
DOCTEST_REQUIRE( out1.DataType() == dip::DT_SFLOAT );
DOCTEST_REQUIRE( out1.TensorElements() == 3 );
DOCTEST_REQUIRE( out1.Sizes() == img1.Sizes() );
dip::ImageIterator< dip::sfloat > outIt1( out1 );
ii = 0;
do {
if( ii <= 9 ) {
DOCTEST_CHECK( *outIt1 == static_cast< dip::sfloat >( ii + 10 ));
} else {
DOCTEST_CHECK( *outIt1 == 255.0f );
}
++ii;
} while( ++outIt1 );
// Case 2: float image
dip::Image img2( { 5, 3 }, 1, dip::DT_DFLOAT );
dip::ImageIterator< dip::dfloat > imgIt2( img2 );
dip::dfloat d = 2.3;
do {
*imgIt2 = d;
d += 0.8;
} while( ++imgIt2 );
dip::Image out2 = lut1.Apply( img2 );
DOCTEST_REQUIRE( out2.DataType() == dip::DT_SFLOAT );
DOCTEST_REQUIRE( out2.TensorElements() == 3 );
DOCTEST_REQUIRE( out2.Sizes() == img2.Sizes() );
dip::ImageIterator< dip::sfloat > outIt2( out2 );
d = 2.3;
do {
if( d <= 9.0 ) {
DOCTEST_CHECK( *outIt2 == static_cast< dip::sfloat >( d + 10.0 ));
} else {
DOCTEST_CHECK( *outIt2 == 255.0f );
}
d += 0.8;
} while( ++outIt2 );
// LUT with index
dip::FloatArray index( lutIm.Size( 0 ), 0 );
d = 8.0;
for( auto& ind : index ) {
ind = d;
d += 0.5;
}
dip::SampleIterator< dip::sfloat > lutImIt( static_cast< dip::sfloat* >( lutIm.Origin() ), lutIm.Stride( 0 ));
dip::LookupTable lut2( lutImIt, lutImIt + lutIm.Size( 0 ), index );
lut2.SetOutOfBoundsValue( 255 );
DOCTEST_CHECK( lut2.HasIndex() );
DOCTEST_CHECK( lut2.DataType() == dip::DT_SFLOAT );
// Case 3: float image with index
dip::Image out3 = lut2.Apply( img2 );
DOCTEST_REQUIRE( out3.DataType() == dip::DT_SFLOAT );
DOCTEST_REQUIRE( out3.TensorElements() == 1 );
DOCTEST_REQUIRE( out3.Sizes() == img2.Sizes() );
dip::ImageIterator< dip::sfloat > outIt3( out3 );
d = 2.3;
do {
if(( d >= 8.0 ) && ( d <= 12.5 )) {
DOCTEST_CHECK( *outIt3 == static_cast< dip::sfloat >(( d - 8.0 ) * 2.0 + 10.0 ));
} else {
DOCTEST_CHECK( *outIt3 == 255.0f );
}
d += 0.8;
} while( ++outIt3 );
}
#endif // DIP__ENABLE_DOCTEST
|
// Copyright 2018 Google LLC
//
// 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.
#include "google/cloud/storage/internal/hash_validator.h"
#include "google/cloud/internal/make_unique.h"
#include "google/cloud/storage/object_metadata.h"
#include "google/cloud/status.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
namespace {
using ::testing::HasSubstr;
// These values were obtained using:
// echo -n '' > foo.txt && gsutil hash foo.txt
const std::string EMPTY_STRING_CRC32C_CHECKSUM = "AAAAAA==";
const std::string EMPTY_STRING_MD5_HASH = "1B2M2Y8AsgTpgAmY7PhCfg==";
// /bin/echo -n 'The quick brown fox jumps over the lazy dog' > foo.txt
// gsutil hash foo.txt
const std::string QUICK_FOX_CRC32C_CHECKSUM = "ImIEBA==";
const std::string QUICK_FOX_MD5_HASH = "nhB9nTcrtoJr2B01QqQZ1g==";
TEST(NullHashValidatorTest, Simple) {
NullHashValidator validator;
validator.ProcessHeader("x-goog-hash", "md5=<placeholder-for-test>");
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
auto result = std::move(validator).Finish();
EXPECT_TRUE(result.computed.empty());
EXPECT_TRUE(result.received.empty());
}
TEST(MD5HashValidator, Empty) {
MD5HashValidator validator;
validator.ProcessHeader("x-goog-hash", "md5=" + EMPTY_STRING_MD5_HASH);
auto result = std::move(validator).Finish();
EXPECT_EQ(result.computed, result.received);
EXPECT_EQ(EMPTY_STRING_MD5_HASH, result.computed);
EXPECT_FALSE(result.is_mismatch);
}
TEST(MD5HashValidator, Simple) {
MD5HashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash", "md5=<invalid-value-for-test>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_MD5_HASH, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(MD5HashValidator, MultipleHashesMd5AtEnd) {
MD5HashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader(
"x-goog-hash", "crc32c=<should-be-ignored>,md5=<invalid-value-for-test>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_MD5_HASH, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(MD5HashValidator, MultipleHashes) {
MD5HashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader(
"x-goog-hash", "md5=<invalid-value-for-test>,crc32c=<should-be-ignored>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_MD5_HASH, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(Crc32cHashValidator, Empty) {
Crc32cHashValidator validator;
validator.ProcessHeader("x-goog-hash",
"crc32c=" + EMPTY_STRING_CRC32C_CHECKSUM);
validator.ProcessHeader("x-goog-hash", "md5=<invalid-should-be-ignored>");
auto result = std::move(validator).Finish();
EXPECT_EQ(result.computed, result.received);
EXPECT_EQ(EMPTY_STRING_CRC32C_CHECKSUM, result.computed);
EXPECT_FALSE(result.is_mismatch);
}
TEST(Crc32cHashValidator, Simple) {
Crc32cHashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash", "crc32c=<invalid-value-for-test>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_CRC32C_CHECKSUM, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(Crc32cHashValidator, MultipleHashesCrc32cAtEnd) {
Crc32cHashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash",
"md5=<ignored>,crc32c=<invalid-value-for-test>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_CRC32C_CHECKSUM, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(Crc32cHashValidator, MultipleHashes) {
Crc32cHashValidator validator;
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash",
"crc32c=<invalid-value-for-test>,md5=<ignored>");
auto result = std::move(validator).Finish();
EXPECT_EQ("<invalid-value-for-test>", result.received);
EXPECT_EQ(QUICK_FOX_CRC32C_CHECKSUM, result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(CompositeHashValidator, Empty) {
CompositeValidator validator(
google::cloud::internal::make_unique<Crc32cHashValidator>(),
google::cloud::internal::make_unique<MD5HashValidator>());
validator.ProcessHeader("x-goog-hash",
"crc32c=" + EMPTY_STRING_CRC32C_CHECKSUM);
validator.ProcessHeader("x-goog-hash", "md5=" + EMPTY_STRING_MD5_HASH);
auto result = std::move(validator).Finish();
EXPECT_EQ(result.computed, result.received);
EXPECT_EQ("crc32c=" + EMPTY_STRING_CRC32C_CHECKSUM +
",md5=" + EMPTY_STRING_MD5_HASH,
result.computed);
EXPECT_FALSE(result.is_mismatch);
}
TEST(CompositeHashValidator, Simple) {
CompositeValidator validator(
google::cloud::internal::make_unique<Crc32cHashValidator>(),
google::cloud::internal::make_unique<MD5HashValidator>());
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash", "crc32c=<invalid-crc32c-for-test>");
validator.ProcessHeader("x-goog-hash", "md5=<invalid-md5-for-test>");
auto result = std::move(validator).Finish();
EXPECT_EQ("crc32c=<invalid-crc32c-for-test>,md5=<invalid-md5-for-test>",
result.received);
EXPECT_EQ(
"crc32c=" + QUICK_FOX_CRC32C_CHECKSUM + ",md5=" + QUICK_FOX_MD5_HASH,
result.computed);
EXPECT_TRUE(result.is_mismatch);
}
TEST(CompositeHashValidator, ProcessMetadata) {
CompositeValidator validator(
google::cloud::internal::make_unique<Crc32cHashValidator>(),
google::cloud::internal::make_unique<MD5HashValidator>());
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
auto object_metadata = ObjectMetadata::ParseFromJson(internal::nl::json{
{"crc32c", QUICK_FOX_CRC32C_CHECKSUM},
{"md5Hash", QUICK_FOX_MD5_HASH},
}).value();
validator.ProcessMetadata(object_metadata);
auto result = std::move(validator).Finish();
EXPECT_EQ(
"crc32c=" + QUICK_FOX_CRC32C_CHECKSUM + ",md5=" + QUICK_FOX_MD5_HASH,
result.computed);
EXPECT_EQ(
"crc32c=" + QUICK_FOX_CRC32C_CHECKSUM + ",md5=" + QUICK_FOX_MD5_HASH,
result.received);
EXPECT_FALSE(result.is_mismatch);
}
TEST(CompositeHashValidator, Missing) {
CompositeValidator validator(
google::cloud::internal::make_unique<Crc32cHashValidator>(),
google::cloud::internal::make_unique<MD5HashValidator>());
validator.Update("The quick");
validator.Update(" brown");
validator.Update(" fox jumps over the lazy dog");
validator.ProcessHeader("x-goog-hash", "crc32c=" + QUICK_FOX_CRC32C_CHECKSUM);
auto result = std::move(validator).Finish();
EXPECT_EQ("crc32c=" + QUICK_FOX_CRC32C_CHECKSUM + ",md5=",
result.received);
EXPECT_EQ(
"crc32c=" + QUICK_FOX_CRC32C_CHECKSUM + ",md5=" + QUICK_FOX_MD5_HASH,
result.computed);
EXPECT_FALSE(result.is_mismatch);
}
} // namespace
} // namespace internal
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
|
/*
* Copyright (C) 2016 Open Source Robotics Foundation
*
* 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.
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include <ignition/math/Helpers.hh>
#include <ignition/math/SphericalCoordinates.hh>
#include "gtest/gtest.h"
#include "manifold/test_config.h"
#include "manifold/rndf/Lane.hh"
#include "manifold/rndf/Perimeter.hh"
#include "manifold/rndf/RNDF.hh"
#include "manifold/rndf/RNDFNode.hh"
#include "manifold/rndf/Segment.hh"
#include "manifold/rndf/UniqueId.hh"
#include "manifold/rndf/Waypoint.hh"
#include "manifold/rndf/Zone.hh"
using namespace manifold;
using namespace rndf;
// The fixture for testing the RNDF class.
class RNDFTest : public testing::FileParserUtils
{
};
//////////////////////////////////////////////////
/// \brief Check RNDF name.
TEST(RNDF, Name)
{
RNDF rndf;
EXPECT_TRUE(rndf.Name().empty());
std::string name = "test.rndf";
rndf.SetName(name);
EXPECT_EQ(rndf.Name(), name);
}
//////////////////////////////////////////////////
/// \brief Check segments-related functions.
TEST(RNDF, segments)
{
RNDF rndf;
EXPECT_EQ(rndf.NumSegments(), 0u);
int id = 1;
Segment segment;
// Check an inexistent segment id.
EXPECT_FALSE(rndf.Segment(id, segment));
// Try to remove an inexistent segment id.
EXPECT_FALSE(rndf.RemoveSegment(id));
// Try to add a segment with an invalid Id.
EXPECT_FALSE(rndf.AddSegment(segment));
// Create a valid waypoint.
ignition::math::SphericalCoordinates::SurfaceType st =
ignition::math::SphericalCoordinates::EARTH_WGS84;
ignition::math::Angle lat(0.3), lon(-1.2), heading(0.5);
double elev = 354.1;
ignition::math::SphericalCoordinates sc(st, lat, lon, elev, heading);
int waypointId = 1;
Waypoint wp;
wp.SetId(waypointId);
wp.Location() = sc;
// Create a valid lane.
Lane lane(id);
EXPECT_TRUE(lane.AddWaypoint(wp));
EXPECT_EQ(lane.NumWaypoints(), 1u);
// Add the lane to the segment.
segment.SetId(id);
EXPECT_TRUE(segment.AddLane(lane));
EXPECT_EQ(segment.NumLanes(), 1u);
// Add the segment to the RNDF.
EXPECT_TRUE(rndf.AddSegment(segment));
EXPECT_EQ(rndf.NumSegments(), 1u);
// Try to add an existent segment.
EXPECT_FALSE(rndf.AddSegment(segment));
EXPECT_EQ(rndf.NumSegments(), 1u);
// Get the segment.
Segment segment2;
EXPECT_TRUE(rndf.Segment(segment.Id(), segment2));
EXPECT_EQ(segment, segment2);
// Update a segment.
segment2.SetName("segment2");
EXPECT_TRUE(rndf.UpdateSegment(segment2));
Segment segment3;
EXPECT_TRUE(rndf.Segment(segment2.Id(), segment3));
EXPECT_EQ(segment3, segment2);
// Get a mutable reference to all segments.
std::vector<Segment> &segments = rndf.Segments();
ASSERT_EQ(segments.size(), 1u);
// Modify a segment.
Segment &aSegment = segments.at(0);
aSegment.SetName("updated_name");
EXPECT_TRUE(rndf.Segment(segment2.Id(), segment3));
EXPECT_EQ(segment3.Name(), "updated_name");
for (auto const &s : rndf.Segments())
EXPECT_TRUE(s.Valid());
// Remove a segment.
EXPECT_TRUE(rndf.RemoveSegment(segment2.Id()));
EXPECT_EQ(rndf.NumSegments(), 0u);
}
//////////////////////////////////////////////////
/// \brief Check zones-related functions.
TEST(RNDF, zones)
{
RNDF rndf;
EXPECT_EQ(rndf.NumZones(), 0u);
int id = 1;
Zone zone;
// Check an inexistent zone id.
EXPECT_FALSE(rndf.Zone(id, zone));
// Try to remove an inexistent zone id.
EXPECT_FALSE(rndf.RemoveZone(id));
// Try to add a zone with an invalid Id.
EXPECT_FALSE(rndf.AddZone(zone));
// Add a perimeter point.
ignition::math::SphericalCoordinates::SurfaceType st =
ignition::math::SphericalCoordinates::EARTH_WGS84;
ignition::math::Angle lat(0.3), lon(-1.2), heading(0.5);
double elev = 354.1;
ignition::math::SphericalCoordinates sc(st, lat, lon, elev, heading);
int waypointId = 1;
Waypoint wp;
wp.SetId(waypointId);
wp.Location() = sc;
EXPECT_TRUE(zone.Perimeter().AddPoint(wp));
// Add the zone to the RNDF.
zone.SetId(id);
EXPECT_TRUE(rndf.AddZone(zone));
EXPECT_EQ(rndf.NumZones(), 1u);
// Try to add an existent zone.
EXPECT_FALSE(rndf.AddZone(zone));
EXPECT_EQ(rndf.NumZones(), 1u);
// Get the zone.
Zone zone2;
EXPECT_TRUE(rndf.Zone(zone.Id(), zone2));
EXPECT_EQ(zone, zone2);
// Update a zone.
zone2.SetName("segment2");
EXPECT_TRUE(rndf.UpdateZone(zone2));
Zone zone3;
EXPECT_TRUE(rndf.Zone(zone2.Id(), zone3));
EXPECT_EQ(zone3, zone2);
// Get a mutable reference to all zones.
std::vector<Zone> &zones = rndf.Zones();
ASSERT_EQ(zones.size(), 1u);
// Modify a zone.
Zone &aZone = zones.at(0);
aZone.SetName("updated_name");
EXPECT_TRUE(rndf.Zone(zone2.Id(), zone3));
EXPECT_EQ(zone3.Name(), "updated_name");
for (auto const &z : rndf.Zones())
EXPECT_TRUE(z.Valid());
// Remove a zone.
EXPECT_TRUE(rndf.RemoveZone(zone2.Id()));
EXPECT_EQ(rndf.NumZones(), 0u);
}
//////////////////////////////////////////////////
/// \brief Check RNDF date.
TEST(RNDF, Date)
{
RNDF rndf;
EXPECT_TRUE(rndf.Date().empty());
std::string date = "2016.11.06";
rndf.SetDate(date);
EXPECT_EQ(rndf.Date(), date);
}
//////////////////////////////////////////////////
/// \brief Check RNDF version.
TEST(RNDF, Version)
{
RNDF rndf;
EXPECT_TRUE(rndf.Version().empty());
std::string version = "2.3.6";
rndf.SetVersion(version);
EXPECT_EQ(rndf.Version(), version);
}
//////////////////////////////////////////////////
/// \brief Check RNDF validation.
TEST(RNDF, Validation)
{
RNDF rndf;
EXPECT_FALSE(rndf.Valid());
// Create a valid waypoint.
ignition::math::SphericalCoordinates::SurfaceType st =
ignition::math::SphericalCoordinates::EARTH_WGS84;
ignition::math::Angle lat(0.3), lon(-1.2), heading(0.5);
double elev = 354.1;
ignition::math::SphericalCoordinates sc(st, lat, lon, elev, heading);
int waypointId = 1;
Waypoint wp;
wp.SetId(waypointId);
wp.Location() = sc;
// Create a valid lane.
int id = 1;
Lane lane(id);
EXPECT_TRUE(lane.AddWaypoint(wp));
EXPECT_EQ(lane.NumWaypoints(), 1u);
// Add the lane to the segment.
Segment segment;
EXPECT_TRUE(segment.AddLane(lane));
EXPECT_EQ(segment.NumLanes(), 1u);
// Add the segment to the RNDF.
segment.SetId(id);
EXPECT_TRUE(rndf.AddSegment(segment));
// The segment is not valid (missing Id).
EXPECT_FALSE(rndf.Valid());
}
//////////////////////////////////////////////////
/// \brief Check loading an RNDF from an inexistent file.
TEST(RNDF, loadInexistentFiles)
{
{
RNDF rndf("__inexistentFile___.rndf");
EXPECT_FALSE(rndf.Valid());
}
{
RNDF rndf;
rndf.Load("__inexistentFile___.rndf");
EXPECT_FALSE(rndf.Valid());
}
}
//////////////////////////////////////////////////
/// \brief Check loading real RNDF files.
TEST(RNDF, loadSamples)
{
std::string dirPath(std::string(PROJECT_SOURCE_PATH));
{
RNDF rndf(dirPath + "/test/rndf/sample1.rndf");
EXPECT_TRUE(rndf.Valid());
rndf::UniqueId id(1, 1, 1);
RNDFNode *nodeInfo = rndf.Info(id);
ASSERT_TRUE(nodeInfo != nullptr);
ASSERT_TRUE(nodeInfo->Segment() != nullptr);
ASSERT_EQ(nodeInfo->Segment()->Id(), 1);
ASSERT_TRUE(nodeInfo->Lane() != nullptr);
ASSERT_EQ(nodeInfo->Lane()->Id(), 1);
ASSERT_TRUE(nodeInfo->Zone() == nullptr);
}
{
RNDF rndf(dirPath + "/test/rndf/sample2.rndf");
EXPECT_TRUE(rndf.Valid());
rndf::UniqueId id(68, 0, 20);
RNDFNode *nodeInfo = rndf.Info(id);
ASSERT_TRUE(nodeInfo != nullptr);
ASSERT_TRUE(nodeInfo->Segment() == nullptr);
ASSERT_TRUE(nodeInfo->Lane() == nullptr);
ASSERT_TRUE(nodeInfo->Zone() != nullptr);
EXPECT_EQ(nodeInfo->Zone()->Id(), 68);
rndf::UniqueId spotId(61, 2, 2);
RNDFNode *spotInfo = rndf.Info(spotId);
ASSERT_TRUE(spotInfo != nullptr);
ASSERT_TRUE(spotInfo->Segment() == nullptr);
ASSERT_TRUE(spotInfo->Lane() == nullptr);
ASSERT_TRUE(spotInfo->Zone() != nullptr);
EXPECT_EQ(spotInfo->Zone()->Id(), 61);
}
}
//////////////////////////////////////////////////
/// \brief Check loading specific RNDF blocks from files.
TEST_F(RNDFTest, load)
{
// The first element is the content to be parsed.
// The second element is the expected return value.
// The third element is the test Id.
std::vector<std::tuple<std::string, bool, int>> testCases =
{
std::make_tuple("" , false, 0),
std::make_tuple("\n\n" , false, 0),
// Missing RNDF_name.
std::make_tuple(
"roadA /*A comment */\n"
"\n"
, false, 0),
// Invalid RNDF_name.
std::make_tuple(
"xxx roadA /*A comment */\n"
"\n"
, false, 0),
// Missing RNDF_name value.
std::make_tuple(
"\n\n"
"RNDF_name /* A comment */\n"
"num_segments 2\n"
, false, 0),
// Missing num_segments.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
, false, 0),
// Missing num_segments.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"1\n"
"num_zones 1\n"
, false, 0),
// Missing num_segments value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments \n"
"num_zones 1\n"
, false, 0),
// Invalid num_segments value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments xxx\n"
"num_zones 1\n"
, false, 0),
// Invalid num_segments value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments -1\n"
"num_zones 1\n"
, false, 0),
// Invalid num_segments value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 0\n"
"num_zones 1\n"
, false, 0),
// Missing num_zones.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"format_version 1.2.2\n"
, false, 0),
// Missing num_zones.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"1\n"
"format_version 1.2.2\n"
, false, 0),
// Missing num_zones value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones \n"
"format_version 1.2.2\n"
, false, 0),
// Invalid num_zones value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones xxx\n"
"format_version 1.2.2\n"
, false, 0),
// Invalid num_zones value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones -1\n"
"format_version 1.2.2\n"
, false, 0),
// Missing format_version.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"1.2.2\n"
"segment 1\n"
, false, 0),
// Missing format_version value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"format_version /* comment */\n"
"segment 1\n"
, false, 0),
// Repeated format_version value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"format_version 1.2.2/* comment */\n"
"format_version 1.2.2/* comment */\n"
"segment 1\n"
, false, 0),
// Missing creation_date.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"3-Nov-07\n"
"segment 1\n"
, false, 0),
// Missing format_version value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"creation_date /* comment */\n"
"segment 1\n"
, false, 0),
// Repeated format_version value.
std::make_tuple(
"\n\n"
"RNDF_name roadA /* A comment */\n"
"num_segments 2\n"
"num_zones 1\n"
"creation_date 3-Nov-07\n"
"creation_date 3-Nov-07\n"
"segment 1\n"
, false, 0),
// Missing one segment.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"num_segments 2\n"
"num_zones 0\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"end_file\n"
, false, 0),
// Extra segment found.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"num_segments 1\n"
"num_zones 0\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"end_file\n"
, false, 0),
// Two non-consecutive segments.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"num_segments 2\n"
"num_zones 0\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 3\n"
"num_lanes 1\n"
"lane 3.1\n"
"num_waypoints 8\n"
"3.1.1 30.3902771 -97.7266013\n"
"3.1.2 30.3897954 -97.7268091\n"
"3.1.3 30.3894485 -97.7269254\n"
"3.1.4 30.3891929 -97.7269262\n"
"3.1.5 30.3889129 -97.7269210\n"
"3.1.6 30.3886607 -97.7269929\n"
"3.1.7 30.3883870 -97.7271055\n"
"3.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"end_file\n"
, false, 0),
// Missing one zone.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 1\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"end_file\n"
, false, 0),
// Extra zone found.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 0\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 3 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 3.0\n"
"num_perimeterpoints 3\n"
"exit 3.0.1 2.1.1 /*out of zone 3*/\n"
"3.0.1 38.872271 -77.203339\n"
"3.0.2 38.872258 -77.202804\n"
"3.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 3.1\n"
"spot_width 16\n"
"checkpoint 3.1.2 1\n"
"3.1.1 38.872151 -77.202972\n"
"3.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, false, 0),
// The first zone Id should be equal to the last segment Id + 1.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 1\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 4 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 4.0\n"
"num_perimeterpoints 3\n"
"exit 4.0.1 2.1.1 /*out of zone 3*/\n"
"4.0.1 38.872271 -77.203339\n"
"4.0.2 38.872258 -77.202804\n"
"4.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 4.1\n"
"spot_width 16\n"
"checkpoint 4.1.2 1\n"
"4.1.1 38.872151 -77.202972\n"
"4.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, false, 0),
// Non-consecutive zones.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 2\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 3 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 3.0\n"
"num_perimeterpoints 3\n"
"exit 3.0.1 2.1.1 /*out of zone 3*/\n"
"3.0.1 38.872271 -77.203339\n"
"3.0.2 38.872258 -77.202804\n"
"3.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 3.1\n"
"spot_width 16\n"
"checkpoint 3.1.2 1\n"
"3.1.1 38.872151 -77.202972\n"
"3.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"zone 5 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 5.0\n"
"num_perimeterpoints 3\n"
"exit 5.0.1 2.1.1 /*out of zone 3*/\n"
"5.0.1 38.872271 -77.203339\n"
"5.0.2 38.872258 -77.202804\n"
"5.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 5.1\n"
"spot_width 16\n"
"checkpoint 5.1.2 1\n"
"5.1.1 38.872151 -77.202972\n"
"5.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, false, 0),
// Missing terminator.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"num_segments 2\n"
"num_zones 0\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"\n"
, false, 0),
// No options.
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 1\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 3 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 3.0\n"
"num_perimeterpoints 3\n"
"exit 3.0.1 2.1.1 /*out of zone 3*/\n"
"3.0.1 38.872271 -77.203339\n"
"3.0.2 38.872258 -77.202804\n"
"3.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 3.1\n"
"spot_width 16\n"
"checkpoint 3.1.2 1\n"
"3.1.1 38.872151 -77.202972\n"
"3.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, true, 1),
// One option (format_version).
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 1\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 3 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 3.0\n"
"num_perimeterpoints 3\n"
"exit 3.0.1 2.1.1 /*out of zone 3*/\n"
"3.0.1 38.872271 -77.203339\n"
"3.0.2 38.872258 -77.202804\n"
"3.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 3.1\n"
"spot_width 16\n"
"checkpoint 3.1.2 1\n"
"3.1.1 38.872151 -77.202972\n"
"3.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, true, 2),
// Two options (format_version and creation_date).
std::make_tuple(
"RNDF_name roadA /*A comment */\n"
"\n"
" /* Ignore */\n"
"\n"
"num_segments 2\n"
"num_zones 1\n"
"creation_date 29-Mar-07\n"
"format_version 1.2.2\n"
"segment 1\n"
"num_lanes 1\n"
"lane 1.1\n"
"num_waypoints 9\n"
"1.1.1 30.3870130 -97.7276181\n"
"1.1.2 30.3876366 -97.7273710\n"
"1.1.3 30.3881655 -97.7271432\n"
"1.1.4 30.3885908 -97.7269603\n"
"1.1.5 30.3888965 -97.7268688\n"
"1.1.6 30.3891127 -97.7268779\n"
"1.1.7 30.3893659 -97.7268964\n"
"1.1.8 30.3896061 -97.7268374\n"
"1.1.9 30.3900594 -97.7266452\n"
"end_lane\n"
"end_segment\n"
"segment 2\n"
"num_lanes 1\n"
"lane 2.1\n"
"num_waypoints 8\n"
"2.1.1 30.3902771 -97.7266013\n"
"2.1.2 30.3897954 -97.7268091\n"
"2.1.3 30.3894485 -97.7269254\n"
"2.1.4 30.3891929 -97.7269262\n"
"2.1.5 30.3889129 -97.7269210\n"
"2.1.6 30.3886607 -97.7269929\n"
"2.1.7 30.3883870 -97.7271055\n"
"2.1.8 30.3880462 -97.7272477\n"
"end_lane\n"
"end_segment\n"
"zone 3 /*zones & segments have unique identifiers.*/\n"
"num_spots 1\n"
"zone_name Central_Parking_Lot\n"
"perimeter 3.0\n"
"num_perimeterpoints 3\n"
"exit 3.0.1 2.1.1 /*out of zone 3*/\n"
"3.0.1 38.872271 -77.203339\n"
"3.0.2 38.872258 -77.202804\n"
"3.0.3 38.872264 -77.202315\n"
"end_perimeter\n"
"spot 3.1\n"
"spot_width 16\n"
"checkpoint 3.1.2 1\n"
"3.1.1 38.872151 -77.202972\n"
"3.1.2 38.872103 -77.202971\n"
"end_spot\n"
"end_zone\n"
"end_file\n"
, true, 3),
};
for (auto const &testCase : testCases)
{
std::string content = std::get<0>(testCase);
int testId = std::get<2>(testCase);
// Expectations.
bool expectedResult = std::get<1>(testCase);
// Write the content of this test case into the test file.
this->PopulateFile(content);
// Leave this comment for knowing wich test case failed if needed.
std::cout << "Testing [" << content << "]" << std::endl;
// Check expectations.
RNDF rndf;
bool res;
EXPECT_EQ(res = rndf.Load(this->fileName), expectedResult);
EXPECT_EQ(rndf.Valid(), res);
if (res)
{
switch (testId)
{
case 1:
{
EXPECT_EQ(rndf.Name(), "roadA");
EXPECT_EQ(rndf.NumSegments(), 2u);
EXPECT_EQ(rndf.NumZones(), 1u);
EXPECT_TRUE(rndf.Version().empty());
EXPECT_TRUE(rndf.Date().empty());
break;
}
case 2:
{
EXPECT_EQ(rndf.Name(), "roadA");
EXPECT_EQ(rndf.NumSegments(), 2u);
EXPECT_EQ(rndf.NumZones(), 1u);
EXPECT_EQ(rndf.Version(), "1.2.2");
EXPECT_TRUE(rndf.Date().empty());
break;
}
case 3:
{
EXPECT_EQ(rndf.Name(), "roadA");
EXPECT_EQ(rndf.NumSegments(), 2u);
EXPECT_EQ(rndf.NumZones(), 1u);
EXPECT_EQ(rndf.Version(), "1.2.2");
EXPECT_EQ(rndf.Date(), "29-Mar-07");
break;
}
default:
break;
};
}
}
}
//////////////////////////////////////////////////
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// 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.
// This file is copied from
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/exec/union-node.cc
// and modified by Doris
#include "exec/union_node.h"
#include "exprs/expr.h"
#include "exprs/expr_context.h"
#include "runtime/row_batch.h"
#include "runtime/runtime_state.h"
#include "runtime/tuple.h"
#include "runtime/tuple_row.h"
// #include "util/runtime_profile_counters.h"
#include "gen_cpp/PlanNodes_types.h"
#include "util/runtime_profile.h"
namespace doris {
UnionNode::UnionNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs)
: ExecNode(pool, tnode, descs),
_tuple_id(tnode.union_node.tuple_id),
_tuple_desc(nullptr),
_first_materialized_child_idx(tnode.union_node.first_materialized_child_idx),
_child_idx(0),
_child_batch(nullptr),
_child_row_idx(0),
_child_eos(false),
_const_expr_list_idx(0),
_to_close_child_idx(-1) {}
Status UnionNode::init(const TPlanNode& tnode, RuntimeState* state) {
// TODO(zc):
// RETURN_IF_ERROR(ExecNode::init(tnode, state));
RETURN_IF_ERROR(ExecNode::init(tnode, state));
DCHECK(tnode.__isset.union_node);
DCHECK_EQ(_conjunct_ctxs.size(), 0);
// Create const_expr_ctx_lists_ from thrift exprs.
auto& const_texpr_lists = tnode.union_node.const_expr_lists;
for (auto& texprs : const_texpr_lists) {
std::vector<ExprContext*> ctxs;
RETURN_IF_ERROR(Expr::create_expr_trees(_pool, texprs, &ctxs));
_const_expr_lists.push_back(ctxs);
}
// Create result_expr_ctx_lists_ from thrift exprs.
auto& result_texpr_lists = tnode.union_node.result_expr_lists;
for (auto& texprs : result_texpr_lists) {
std::vector<ExprContext*> ctxs;
RETURN_IF_ERROR(Expr::create_expr_trees(_pool, texprs, &ctxs));
_child_expr_lists.push_back(ctxs);
}
return Status::OK();
}
Status UnionNode::prepare(RuntimeState* state) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
RETURN_IF_ERROR(ExecNode::prepare(state));
SCOPED_SWITCH_TASK_THREAD_LOCAL_MEM_TRACKER(mem_tracker());
_tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_id);
DCHECK(_tuple_desc != nullptr);
_materialize_exprs_evaluate_timer =
ADD_TIMER(_runtime_profile, "MaterializeExprsEvaluateTimer");
_codegend_union_materialize_batch_fns.resize(_child_expr_lists.size());
// Prepare const expr lists.
for (const std::vector<ExprContext*>& exprs : _const_expr_lists) {
RETURN_IF_ERROR(Expr::prepare(exprs, state, row_desc(), expr_mem_tracker()));
// TODO(zc)
// AddExprCtxsToFree(exprs);
DCHECK_EQ(exprs.size(), _tuple_desc->slots().size());
}
// Prepare result expr lists.
for (int i = 0; i < _child_expr_lists.size(); ++i) {
RETURN_IF_ERROR(Expr::prepare(_child_expr_lists[i], state, child(i)->row_desc(),
expr_mem_tracker()));
// TODO(zc)
// AddExprCtxsToFree(_child_expr_lists[i]);
DCHECK_EQ(_child_expr_lists[i].size(), _tuple_desc->slots().size());
}
return Status::OK();
}
Status UnionNode::open(RuntimeState* state) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
SCOPED_SWITCH_TASK_THREAD_LOCAL_MEM_TRACKER(mem_tracker());
RETURN_IF_ERROR(ExecNode::open(state));
// open const expr lists.
for (const std::vector<ExprContext*>& exprs : _const_expr_lists) {
RETURN_IF_ERROR(Expr::open(exprs, state));
}
// open result expr lists.
for (const std::vector<ExprContext*>& exprs : _child_expr_lists) {
RETURN_IF_ERROR(Expr::open(exprs, state));
}
// Ensures that rows are available for clients to fetch after this open() has
// succeeded.
if (!_children.empty()) RETURN_IF_ERROR(child(_child_idx)->open(state));
return Status::OK();
}
Status UnionNode::get_next_pass_through(RuntimeState* state, RowBatch* row_batch) {
DCHECK(!reached_limit());
DCHECK(!is_in_subplan());
DCHECK_LT(_child_idx, _children.size());
DCHECK(is_child_passthrough(_child_idx));
// TODO(zc)
// DCHECK(child(_child_idx)->row_desc().LayoutEquals(row_batch->row_desc()));
if (_child_eos) {
RETURN_IF_ERROR(child(_child_idx)->open(state));
_child_eos = false;
}
DCHECK_EQ(row_batch->num_rows(), 0);
RETURN_IF_ERROR(child(_child_idx)->get_next(state, row_batch, &_child_eos));
if (_child_eos) {
// Even though the child is at eos, it's not OK to close() it here. Once we close
// the child, the row batches that it produced are invalid. Marking the batch as
// needing a deep copy let's us safely close the child in the next get_next() call.
// TODO: Remove this as part of IMPALA-4179.
row_batch->mark_needs_deep_copy();
_to_close_child_idx = _child_idx;
++_child_idx;
}
return Status::OK();
}
Status UnionNode::get_next_materialized(RuntimeState* state, RowBatch* row_batch) {
// Fetch from children, evaluate corresponding exprs and materialize.
DCHECK(!reached_limit());
DCHECK_LT(_child_idx, _children.size());
int64_t tuple_buf_size;
uint8_t* tuple_buf;
RETURN_IF_ERROR(
row_batch->resize_and_allocate_tuple_buffer(state, &tuple_buf_size, &tuple_buf));
memset(tuple_buf, 0, tuple_buf_size);
while (has_more_materialized() && !row_batch->at_capacity()) {
// The loop runs until we are either done iterating over the children that require
// materialization, or the row batch is at capacity.
DCHECK(!is_child_passthrough(_child_idx));
// Child row batch was either never set or we're moving on to a different child.
if (_child_batch.get() == nullptr) {
DCHECK_LT(_child_idx, _children.size());
_child_batch.reset(new RowBatch(child(_child_idx)->row_desc(), state->batch_size()));
_child_row_idx = 0;
// open the current child unless it's the first child, which was already opened in
// UnionNode::open().
if (_child_eos) {
RETURN_IF_ERROR(child(_child_idx)->open(state));
_child_eos = false;
}
// The first batch from each child is always fetched here.
RETURN_IF_ERROR(child(_child_idx)->get_next(state, _child_batch.get(), &_child_eos));
}
while (!row_batch->at_capacity()) {
DCHECK(_child_batch.get() != nullptr);
DCHECK_LE(_child_row_idx, _child_batch->num_rows());
if (_child_row_idx == _child_batch->num_rows()) {
// Move on to the next child if it is at eos.
if (_child_eos) break;
// Fetch more rows from the child.
_child_batch->reset();
_child_row_idx = 0;
// All batches except the first batch from each child are fetched here.
RETURN_IF_ERROR(
child(_child_idx)->get_next(state, _child_batch.get(), &_child_eos));
// If we fetched an empty batch, go back to the beginning of this while loop, and
// try again.
if (_child_batch->num_rows() == 0) continue;
}
DCHECK_EQ(_codegend_union_materialize_batch_fns.size(), _children.size());
if (_codegend_union_materialize_batch_fns[_child_idx] == nullptr) {
SCOPED_TIMER(_materialize_exprs_evaluate_timer);
materialize_batch(row_batch, &tuple_buf);
} else {
_codegend_union_materialize_batch_fns[_child_idx](this, row_batch, &tuple_buf);
}
}
// It shouldn't be the case that we reached the limit because we shouldn't have
// incremented '_num_rows_returned' yet.
DCHECK(!reached_limit());
if (_child_eos && _child_row_idx == _child_batch->num_rows()) {
// Unless we are inside a subplan expecting to call open()/get_next() on the child
// again, the child can be closed at this point.
_child_batch.reset();
if (!is_in_subplan()) child(_child_idx)->close(state);
++_child_idx;
} else {
// If we haven't finished consuming rows from the current child, we must have ended
// up here because the row batch is at capacity.
DCHECK(row_batch->at_capacity());
}
}
DCHECK_LE(_child_idx, _children.size());
return Status::OK();
}
Status UnionNode::get_next_const(RuntimeState* state, RowBatch* row_batch) {
DCHECK_EQ(state->per_fragment_instance_idx(), 0);
DCHECK_LT(_const_expr_list_idx, _const_expr_lists.size());
// Create new tuple buffer for row_batch.
int64_t tuple_buf_size;
uint8_t* tuple_buf;
RETURN_IF_ERROR(
row_batch->resize_and_allocate_tuple_buffer(state, &tuple_buf_size, &tuple_buf));
memset(tuple_buf, 0, tuple_buf_size);
while (_const_expr_list_idx < _const_expr_lists.size() && !row_batch->at_capacity()) {
materialize_exprs(_const_expr_lists[_const_expr_list_idx], nullptr, tuple_buf, row_batch);
RETURN_IF_ERROR(get_error_msg(_const_expr_lists[_const_expr_list_idx]));
tuple_buf += _tuple_desc->byte_size();
++_const_expr_list_idx;
}
return Status::OK();
}
Status UnionNode::get_next(RuntimeState* state, RowBatch* row_batch, bool* eos) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
SCOPED_SWITCH_TASK_THREAD_LOCAL_EXISTED_MEM_TRACKER(mem_tracker());
RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::GETNEXT));
RETURN_IF_CANCELLED(state);
// TODO(zc)
// RETURN_IF_ERROR(QueryMaintenance(state));
if (_to_close_child_idx != -1) {
// The previous child needs to be closed if passthrough was enabled for it. In the non
// passthrough case, the child was already closed in the previous call to get_next().
DCHECK(is_child_passthrough(_to_close_child_idx));
DCHECK(!is_in_subplan());
child(_to_close_child_idx)->close(state);
_to_close_child_idx = -1;
}
// Save the number of rows in case get_next() is called with a non-empty batch, which can
// happen in a subplan.
int num_rows_before = row_batch->num_rows();
if (has_more_passthrough()) {
RETURN_IF_ERROR(get_next_pass_through(state, row_batch));
} else if (has_more_materialized()) {
RETURN_IF_ERROR(get_next_materialized(state, row_batch));
} else if (has_more_const(state)) {
RETURN_IF_ERROR(get_next_const(state, row_batch));
}
int num_rows_added = row_batch->num_rows() - num_rows_before;
DCHECK_GE(num_rows_added, 0);
if (_limit != -1 && _num_rows_returned + num_rows_added > _limit) {
// Truncate the row batch if we went over the limit.
num_rows_added = _limit - _num_rows_returned;
row_batch->set_num_rows(num_rows_before + num_rows_added);
DCHECK_GE(num_rows_added, 0);
}
_num_rows_returned += num_rows_added;
*eos = reached_limit() ||
(!has_more_passthrough() && !has_more_materialized() && !has_more_const(state));
COUNTER_SET(_rows_returned_counter, _num_rows_returned);
return Status::OK();
}
Status UnionNode::close(RuntimeState* state) {
if (is_closed()) return Status::OK();
_child_batch.reset();
for (auto& exprs : _const_expr_lists) {
Expr::close(exprs, state);
}
for (auto& exprs : _child_expr_lists) {
Expr::close(exprs, state);
}
return ExecNode::close(state);
}
void UnionNode::debug_string(int indentation_level, std::stringstream* out) const {
*out << string(indentation_level * 2, ' ');
*out << "_union(_first_materialized_child_idx=" << _first_materialized_child_idx
<< " _row_descriptor=[" << row_desc().debug_string() << "] "
<< " _child_expr_lists=[";
for (int i = 0; i < _child_expr_lists.size(); ++i) {
*out << Expr::debug_string(_child_expr_lists[i]) << ", ";
}
*out << "] \n";
ExecNode::debug_string(indentation_level, out);
*out << ")" << std::endl;
}
void UnionNode::materialize_exprs(const std::vector<ExprContext*>& exprs, TupleRow* row,
uint8_t* tuple_buf, RowBatch* dst_batch) {
DCHECK(!dst_batch->at_capacity());
Tuple* dst_tuple = reinterpret_cast<Tuple*>(tuple_buf);
TupleRow* dst_row = dst_batch->get_row(dst_batch->add_row());
// dst_tuple->materialize_exprs<false, false>(row, *_tuple_desc, exprs,
dst_tuple->materialize_exprs<false>(row, *_tuple_desc, exprs, dst_batch->tuple_data_pool(),
nullptr, nullptr);
dst_row->set_tuple(0, dst_tuple);
dst_batch->commit_last_row();
}
void UnionNode::materialize_batch(RowBatch* dst_batch, uint8_t** tuple_buf) {
// Take all references to member variables out of the loop to reduce the number of
// loads and stores.
RowBatch* child_batch = _child_batch.get();
int tuple_byte_size = _tuple_desc->byte_size();
uint8_t* cur_tuple = *tuple_buf;
const std::vector<ExprContext*>& child_exprs = _child_expr_lists[_child_idx];
int num_rows_to_process = std::min(child_batch->num_rows() - _child_row_idx,
dst_batch->capacity() - dst_batch->num_rows());
FOREACH_ROW_LIMIT(child_batch, _child_row_idx, num_rows_to_process, batch_iter) {
TupleRow* child_row = batch_iter.get();
materialize_exprs(child_exprs, child_row, cur_tuple, dst_batch);
cur_tuple += tuple_byte_size;
}
_child_row_idx += num_rows_to_process;
*tuple_buf = cur_tuple;
}
Status UnionNode::get_error_msg(const std::vector<ExprContext*>& exprs) {
for (auto expr_ctx : exprs) {
std::string expr_error = expr_ctx->get_error_msg();
if (!expr_error.empty()) {
return Status::RuntimeError(expr_error);
}
}
return Status::OK();
}
} // namespace doris
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/scenarios/emergency/emergency_pull_over/stage_standby.h"
#include <string>
#include <vector>
#include "cyber/common/log.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/util/common.h"
#include "modules/planning/scenarios/util/util.h"
#include "modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h"
namespace apollo {
namespace planning {
namespace scenario {
namespace emergency_pull_over {
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleConfigHelper;
Stage::StageStatus EmergencyPullOverStageStandby::Process(
const TrajectoryPoint& planning_init_point, Frame* frame) {
ADEBUG << "stage: Standby";
CHECK_NOTNULL(frame);
scenario_config_.CopyFrom(GetContext()->scenario_config);
auto& reference_line_info = frame->mutable_reference_line_info()->front();
// set vehicle signal
reference_line_info.SetEmergencyLight();
// reset cruise_speed
reference_line_info.SetCruiseSpeed(FLAGS_default_cruise_speed);
// add a stop fence
const auto& pull_over_status =
PlanningContext::Instance()->planning_status().pull_over();
if (pull_over_status.has_position() && pull_over_status.position().has_x() &&
pull_over_status.position().has_y()) {
const auto& reference_line_info = frame->reference_line_info().front();
const auto& reference_line = reference_line_info.reference_line();
common::SLPoint pull_over_sl;
reference_line.XYToSL(
{pull_over_status.position().x(), pull_over_status.position().y()},
&pull_over_sl);
const double stop_distance = scenario_config_.stop_distance();
double stop_line_s =
pull_over_sl.s() + stop_distance +
VehicleConfigHelper::GetConfig().vehicle_param().front_edge_to_center();
const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
double distance = stop_line_s - adc_front_edge_s;
if (distance <= 0.0) {
// push stop fence further
stop_line_s = adc_front_edge_s + stop_distance;
}
const std::string virtual_obstacle_id = "EMERGENCY_PULL_OVER";
const std::vector<std::string> wait_for_obstacle_ids;
planning::util::BuildStopDecision(
virtual_obstacle_id, stop_line_s, stop_distance,
StopReasonCode::STOP_REASON_PULL_OVER, wait_for_obstacle_ids,
"EMERGENCY_PULL_OVER-scenario", frame,
&(frame->mutable_reference_line_info()->front()));
ADEBUG << "Build a stop fence for emergency_pull_over: id["
<< virtual_obstacle_id << "] s[" << stop_line_s << "]";
}
bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);
if (!plan_ok) {
AERROR << "EmergencyPullOverStageStandby planning error";
}
return Stage::RUNNING;
}
Stage::StageStatus EmergencyPullOverStageStandby::FinishStage() {
return FinishScenario();
}
} // namespace emergency_pull_over
} // namespace scenario
} // namespace planning
} // namespace apollo
|
#pragma once
#include "Cardia/Core/Window.hpp"
#include "Cardia/Renderer/RendererContext.hpp"
#include <GLFW/glfw3.h>
namespace Cardia
{
struct WinData
{
std::string title;
int width, height;
bool vSync;
std::function<void(Event&)> eventCallback;
};
class WindowsWin : public Window
{
public:
WindowsWin(const WinProperties& properties);
virtual ~WindowsWin();
void onUpdate() override;
inline int getWidth() const override { return m_Data.width; }
inline int getHeight() const override { return m_Data.height; }
inline std::pair<int, int> getSize() const override { return {getWidth(), getHeight()}; }
inline void setEventCallback(const std::function<void(Event&)>& callback) override { m_Data.eventCallback = callback; }
void setFullscreen(bool state) override;
bool isFullscreen() const override;
void setVSync(bool state) override;
bool isVSync() const override;
inline virtual void* getNativeWin() const override { return m_Window; }
private:
void init(const WinProperties& properties);
void quit();
static bool s_isGlfwInit; // Can only initialize glfw once.
GLFWwindow* m_Window;
WinData m_Data;
std::unique_ptr<RendererContext> m_RendererContext;
};
}
|
//=============================================================================
/**
* @file Sched_Params.cpp
*
* $Id: Sched_Params.cpp 83624 2008-11-09 11:45:59Z johnnyw $
*
* @author David Levine
*/
//=============================================================================
#include "ace/Sched_Params.h"
#if !defined (__ACE_INLINE__)
#include "ace/Sched_Params.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_HAS_PRIOCNTL) && defined (ACE_HAS_STHREADS)
# include "ace/OS_NS_string.h"
# include /**/ <sys/priocntl.h>
#endif /* ACE_HAS_PRIOCNTL && ACE_HAS_THREADS */
ACE_RCSID(ace, Sched_Params, "$Id: Sched_Params.cpp 83624 2008-11-09 11:45:59Z johnnyw $")
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
int
ACE_Sched_Params::priority_min (const Policy policy,
const int scope)
{
#if defined (ACE_HAS_PRIOCNTL) && defined (ACE_HAS_STHREADS)
ACE_UNUSED_ARG (scope);
// Assume that ACE_SCHED_OTHER indicates TS class, and that other
// policies indicate RT class.
// Call ACE_OS::priority_control only for processes (lightweight
// or otherwise). Calling ACE_OS::priority_control for thread
// priorities gives incorrect results.
if (scope == ACE_SCOPE_PROCESS || scope == ACE_SCOPE_LWP)
{
if (policy == ACE_SCHED_OTHER)
{
// Get the priority class ID and attributes.
pcinfo_t pcinfo;
// The following is just to avoid Purify warnings about unitialized
// memory reads.
ACE_OS::memset (&pcinfo, 0, sizeof pcinfo);
ACE_OS::strcpy (pcinfo.pc_clname, "TS");
if (ACE_OS::priority_control (P_ALL /* ignored */,
P_MYID /* ignored */,
PC_GETCID,
(char *) &pcinfo) == -1)
// Just hope that priority range wasn't configured from -1
// .. 1
return -1;
// OK, now we've got the class ID in pcinfo.pc_cid. In
// addition, the maximum configured time-share priority is in
// ((tsinfo_t *) pcinfo.pc_clinfo)->ts_maxupri. The minimum
// priority is just the negative of that.
return -((tsinfo_t *) pcinfo.pc_clinfo)->ts_maxupri;
}
else
return 0;
}
else
{
// Here we handle the case for ACE_SCOPE_THREAD. Calling
// ACE_OS::priority_control for thread scope gives incorrect
// results.
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_THR_PRI_FIFO_MIN;
case ACE_SCHED_RR:
return ACE_THR_PRI_RR_MIN;
case ACE_SCHED_OTHER:
default:
return ACE_THR_PRI_OTHER_MIN;
}
}
#elif defined(ACE_HAS_PTHREADS) && \
(!defined(ACE_LACKS_SETSCHED) || defined (ACE_TANDEM_T1248_PTHREADS) || \
defined (ACE_HAS_PTHREAD_SCHEDPARAM))
switch (scope)
{
case ACE_SCOPE_THREAD:
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_THR_PRI_FIFO_MIN;
case ACE_SCHED_RR:
return ACE_THR_PRI_RR_MIN;
case ACE_SCHED_OTHER:
default:
return ACE_THR_PRI_OTHER_MIN;
}
case ACE_SCOPE_PROCESS:
default:
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_PROC_PRI_FIFO_MIN;
case ACE_SCHED_RR:
return ACE_PROC_PRI_RR_MIN;
case ACE_SCHED_OTHER:
default:
return ACE_PROC_PRI_OTHER_MIN;
}
}
#elif defined (ACE_HAS_WTHREADS) && !defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
return THREAD_PRIORITY_IDLE;
#elif defined (ACE_HAS_WTHREADS) && defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
return 255;
#elif defined (ACE_VXWORKS)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
# if defined (VX_TASK_PRIORITY_MAX)
return VX_TASK_PRIORITY_MAX;
# else
return 255;
# endif
#else
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_HAS_PRIOCNTL && defined (ACE_HAS_STHREADS) */
}
int
ACE_Sched_Params::priority_max (const Policy policy,
const int scope)
{
#if defined (ACE_HAS_PRIOCNTL) && defined (ACE_HAS_STHREADS)
ACE_UNUSED_ARG (scope);
// Call ACE_OS::priority_control only for processes (lightweight
// or otherwise). Calling ACE_OS::priority_control for thread
// priorities gives incorrect results.
if (scope == ACE_SCOPE_PROCESS || scope == ACE_SCOPE_LWP)
{
// Assume that ACE_SCHED_OTHER indicates TS class, and that other
// policies indicate RT class.
// Get the priority class ID and attributes.
pcinfo_t pcinfo;
// The following is just to avoid Purify warnings about unitialized
// memory reads.
ACE_OS::memset (&pcinfo, 0, sizeof pcinfo);
ACE_OS::strcpy (pcinfo.pc_clname,
policy == ACE_SCHED_OTHER ? "TS" : "RT");
if (ACE_OS::priority_control (P_ALL /* ignored */,
P_MYID /* ignored */,
PC_GETCID,
(char *) &pcinfo) == -1)
return -1;
// OK, now we've got the class ID in pcinfo.pc_cid. In addition,
// the maximum configured real-time priority is in ((rtinfo_t *)
// pcinfo.pc_clinfo)->rt_maxpri, or similarly for the TS class.
return policy == ACE_SCHED_OTHER
? ((tsinfo_t *) pcinfo.pc_clinfo)->ts_maxupri
: ((rtinfo_t *) pcinfo.pc_clinfo)->rt_maxpri;
}
else
{
// Here we handle the case for ACE_SCOPE_THREAD. Calling
// ACE_OS::priority_control for thread scope gives incorrect
// results.
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_THR_PRI_FIFO_MAX;
case ACE_SCHED_RR:
return ACE_THR_PRI_RR_MAX;
case ACE_SCHED_OTHER:
default:
return ACE_THR_PRI_OTHER_MAX;
}
}
#elif defined(ACE_HAS_PTHREADS) && \
(!defined(ACE_LACKS_SETSCHED) || defined (ACE_TANDEM_T1248_PTHREADS) || \
defined (ACE_HAS_PTHREAD_SCHEDPARAM))
switch (scope)
{
case ACE_SCOPE_THREAD:
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_THR_PRI_FIFO_MAX;
case ACE_SCHED_RR:
return ACE_THR_PRI_RR_MAX;
case ACE_SCHED_OTHER:
default:
return ACE_THR_PRI_OTHER_MAX;
}
case ACE_SCOPE_PROCESS:
default:
switch (policy)
{
case ACE_SCHED_FIFO:
return ACE_PROC_PRI_FIFO_MAX;
case ACE_SCHED_RR:
return ACE_PROC_PRI_RR_MAX;
case ACE_SCHED_OTHER:
default:
return ACE_PROC_PRI_OTHER_MAX;
}
}
#elif defined (ACE_HAS_WTHREADS) && !defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
return THREAD_PRIORITY_TIME_CRITICAL;
#elif defined (ACE_HAS_WTHREADS) && defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
return 0;
#elif defined (ACE_VXWORKS)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
# if defined (VX_TASK_PRIORITY_MIN)
return VX_TASK_PRIORITY_MIN;
# else
return 0;
# endif
#else
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_HAS_PRIOCNTL && defined (ACE_HAS_STHREADS) */
}
int
ACE_Sched_Params::next_priority (const Policy policy,
const int priority,
const int scope)
{
#if defined (ACE_HAS_WTHREADS) && !defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
switch (priority)
{
case THREAD_PRIORITY_IDLE:
return THREAD_PRIORITY_LOWEST;
case THREAD_PRIORITY_LOWEST:
return THREAD_PRIORITY_BELOW_NORMAL;
case THREAD_PRIORITY_BELOW_NORMAL:
return THREAD_PRIORITY_NORMAL;
case THREAD_PRIORITY_NORMAL:
return THREAD_PRIORITY_ABOVE_NORMAL;
case THREAD_PRIORITY_ABOVE_NORMAL:
return THREAD_PRIORITY_HIGHEST;
case THREAD_PRIORITY_HIGHEST:
return THREAD_PRIORITY_TIME_CRITICAL;
case THREAD_PRIORITY_TIME_CRITICAL:
return THREAD_PRIORITY_TIME_CRITICAL;
default:
return priority; // unknown priority: should never get here
}
#elif defined(ACE_HAS_THREADS) && \
(!defined(ACE_LACKS_SETSCHED) || defined (ACE_TANDEM_T1248_PTHREADS) || \
defined (ACE_HAS_PTHREAD_SCHEDPARAM))
// including STHREADS, and PTHREADS
int const max = priority_max (policy, scope);
return priority < max ? priority + 1 : max;
#elif defined (ACE_VXWORKS) || defined (ACE_HAS_WINCE)
int const max = priority_max (policy, scope);
return priority > max ? priority - 1 : max;
#else
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
ACE_UNUSED_ARG (priority);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_HAS_THREADS */
}
int
ACE_Sched_Params::previous_priority (const Policy policy,
const int priority,
const int scope)
{
#if defined (ACE_HAS_WTHREADS) && !defined (ACE_HAS_WINCE)
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
switch (priority)
{
case THREAD_PRIORITY_IDLE:
return THREAD_PRIORITY_IDLE;
case THREAD_PRIORITY_LOWEST:
return THREAD_PRIORITY_IDLE;
case THREAD_PRIORITY_BELOW_NORMAL:
return THREAD_PRIORITY_LOWEST;
case THREAD_PRIORITY_NORMAL:
return THREAD_PRIORITY_BELOW_NORMAL;
case THREAD_PRIORITY_ABOVE_NORMAL:
return THREAD_PRIORITY_NORMAL;
case THREAD_PRIORITY_HIGHEST:
return THREAD_PRIORITY_ABOVE_NORMAL;
case THREAD_PRIORITY_TIME_CRITICAL:
return THREAD_PRIORITY_HIGHEST;
default:
return priority; // unknown priority: should never get here
}
#elif defined(ACE_HAS_THREADS) && \
(!defined(ACE_LACKS_SETSCHED) || defined (ACE_TANDEM_T1248_PTHREADS) || \
defined (ACE_HAS_PTHREAD_SCHEDPARAM))
// including STHREADS and PTHREADS
int const min = priority_min (policy, scope);
return priority > min ? priority - 1 : min;
#elif defined (ACE_VXWORKS) || defined (ACE_HAS_WINCE)
int const min = priority_min (policy, scope);
return priority < min ? priority + 1 : min;
#else
ACE_UNUSED_ARG (policy);
ACE_UNUSED_ARG (scope);
ACE_UNUSED_ARG (priority);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_HAS_THREADS */
}
ACE_END_VERSIONED_NAMESPACE_DECL
|
/*
* Copyright (c) 2006 - 2016 Stephen F. Booth <me@sbooth.org>
* See https://github.com/sbooth/SFBAudioEngine/blob/master/LICENSE.txt for license information
*/
#include <AudioToolbox/AudioFormat.h>
#include "WavPackDecoder.h"
#include "CFWrapper.h"
#include "CFErrorUtilities.h"
#include "Logger.h"
#define BUFFER_SIZE_FRAMES 2048
namespace {
void RegisterWavPackDecoder() __attribute__ ((constructor));
void RegisterWavPackDecoder()
{
SFB::Audio::Decoder::RegisterSubclass<SFB::Audio::WavPackDecoder>();
}
#pragma mark Callbacks
int32_t read_bytes_callback(void *id, void *data, int32_t bcount)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
return (int32_t)decoder->GetInputSource().Read(data, bcount);
}
uint32_t get_pos_callback(void *id)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
return (uint32_t)decoder->GetInputSource().GetOffset();
}
int set_pos_abs_callback(void *id, uint32_t pos)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
return !decoder->GetInputSource().SeekToOffset(pos);
}
int set_pos_rel_callback(void *id, int32_t delta, int mode)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
SFB::InputSource& inputSource = decoder->GetInputSource();
if(!inputSource.SupportsSeeking())
return -1;
// Adjust offset as required
SInt64 offset = delta;
switch(mode) {
case SEEK_SET:
// offset remains unchanged
break;
case SEEK_CUR:
offset += inputSource.GetOffset();
break;
case SEEK_END:
offset += inputSource.GetLength();
break;
}
return (!inputSource.SeekToOffset(offset));
}
// FIXME: How does one emulate ungetc when the data is non-seekable?
int push_back_byte_callback(void *id, int c)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
SFB::InputSource& inputSource = decoder->GetInputSource();
if(!inputSource.SupportsSeeking())
return EOF;
if(!inputSource.SeekToOffset(inputSource.GetOffset() - 1))
return EOF;
return c;
}
uint32_t get_length_callback(void *id)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
return (uint32_t)decoder->GetInputSource().GetLength();
}
int can_seek_callback(void *id)
{
assert(nullptr != id);
auto decoder = static_cast<SFB::Audio::WavPackDecoder *>(id);
return (int)decoder->GetInputSource().SupportsSeeking();
}
}
#pragma mark Static Methods
CFArrayRef SFB::Audio::WavPackDecoder::CreateSupportedFileExtensions()
{
CFStringRef supportedExtensions [] = { CFSTR("wv") };
return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedExtensions, 1, &kCFTypeArrayCallBacks);
}
CFArrayRef SFB::Audio::WavPackDecoder::CreateSupportedMIMETypes()
{
CFStringRef supportedMIMETypes [] = { CFSTR("audio/wavpack"), CFSTR("audio/x-wavpack") };
return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedMIMETypes, 2, &kCFTypeArrayCallBacks);
}
bool SFB::Audio::WavPackDecoder::HandlesFilesWithExtension(CFStringRef extension)
{
if(nullptr == extension)
return false;
if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("wv"), kCFCompareCaseInsensitive))
return true;
return false;
}
bool SFB::Audio::WavPackDecoder::HandlesMIMEType(CFStringRef mimeType)
{
if(nullptr == mimeType)
return false;
if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/wavpack"), kCFCompareCaseInsensitive))
return true;
if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/x-wavpack"), kCFCompareCaseInsensitive))
return true;
return false;
}
SFB::Audio::Decoder::unique_ptr SFB::Audio::WavPackDecoder::CreateDecoder(InputSource::unique_ptr inputSource)
{
return unique_ptr(new WavPackDecoder(std::move(inputSource)));
}
#pragma mark Creation and Destruction
SFB::Audio::WavPackDecoder::WavPackDecoder(InputSource::unique_ptr inputSource)
: Decoder(std::move(inputSource)), mWPC(nullptr, nullptr), mTotalFrames(0), mCurrentFrame(0)
{
memset(&mStreamReader, 0, sizeof(mStreamReader));
}
#pragma mark Functionality
bool SFB::Audio::WavPackDecoder::_Open(CFErrorRef *error)
{
mStreamReader.read_bytes = read_bytes_callback;
mStreamReader.get_pos = get_pos_callback;
mStreamReader.set_pos_abs = set_pos_abs_callback;
mStreamReader.set_pos_rel = set_pos_rel_callback;
mStreamReader.push_back_byte = push_back_byte_callback;
mStreamReader.get_length = get_length_callback;
mStreamReader.can_seek = can_seek_callback;
char errorBuf [80];
// Setup converter
mWPC = unique_WavpackContext_ptr(WavpackOpenFileInputEx(&mStreamReader, this, nullptr, errorBuf, OPEN_WVC | OPEN_NORMALIZE, 0), WavpackCloseFile);
if(!mWPC) {
if(error) {
SFB::CFString description(CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WavPack file."), ""));
SFB::CFString failureReason(CFCopyLocalizedString(CFSTR("Not a WavPack file"), ""));
SFB::CFString recoverySuggestion(CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
}
return false;
}
// Floating-point and lossy files will be handed off in the canonical Core Audio format
int mode = WavpackGetMode(mWPC.get());
if(MODE_FLOAT & mode || !(MODE_LOSSLESS & mode)) {
// Canonical Core Audio format
mFormat.mFormatID = kAudioFormatLinearPCM;
mFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
mFormat.mSampleRate = WavpackGetSampleRate(mWPC.get());
mFormat.mChannelsPerFrame = (UInt32)WavpackGetNumChannels(mWPC.get());
mFormat.mBitsPerChannel = 8 * sizeof(float);
mFormat.mBytesPerPacket = (mFormat.mBitsPerChannel / 8);
mFormat.mFramesPerPacket = 1;
mFormat.mBytesPerFrame = mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;
mFormat.mReserved = 0;
}
else {
mFormat.mFormatID = kAudioFormatLinearPCM;
mFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsNonInterleaved;
// Don't set kAudioFormatFlagIsAlignedHigh for 32-bit integer files
mFormat.mFormatFlags |= (32 == WavpackGetBitsPerSample(mWPC.get()) ? kAudioFormatFlagIsPacked : kAudioFormatFlagIsAlignedHigh);
mFormat.mSampleRate = WavpackGetSampleRate(mWPC.get());
mFormat.mChannelsPerFrame = (UInt32)WavpackGetNumChannels(mWPC.get());
mFormat.mBitsPerChannel = (UInt32)WavpackGetBitsPerSample(mWPC.get());
mFormat.mBytesPerPacket = sizeof(int32_t);
mFormat.mFramesPerPacket = 1;
mFormat.mBytesPerFrame = mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;
mFormat.mReserved = 0;
}
mTotalFrames = WavpackGetNumSamples(mWPC.get());
// Set up the source format
mSourceFormat.mFormatID = 'WVPK';
mSourceFormat.mSampleRate = WavpackGetSampleRate(mWPC.get());
mSourceFormat.mChannelsPerFrame = (UInt32)WavpackGetNumChannels(mWPC.get());
mSourceFormat.mBitsPerChannel = (UInt32)WavpackGetBitsPerSample(mWPC.get());
// Setup the channel layout
switch(mFormat.mChannelsPerFrame) {
case 1: mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Mono); break;
case 2: mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo); break;
case 4: mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Quadraphonic); break;
}
mBuffer = std::unique_ptr<int32_t []>(new int32_t [BUFFER_SIZE_FRAMES * mFormat.mChannelsPerFrame]);
if(!mBuffer) {
if(error)
*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, ENOMEM, nullptr);
return false;
}
return true;
}
bool SFB::Audio::WavPackDecoder::_Close(CFErrorRef */*error*/)
{
memset(&mStreamReader, 0, sizeof(mStreamReader));
mBuffer.reset();
mWPC.reset();
return true;
}
SFB::CFString SFB::Audio::WavPackDecoder::_GetSourceFormatDescription() const
{
return CFString(nullptr,
CFSTR("WavPack, %u channels, %u Hz"),
(unsigned int)mSourceFormat.mChannelsPerFrame,
(unsigned int)mSourceFormat.mSampleRate);
}
UInt32 SFB::Audio::WavPackDecoder::_ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
if(bufferList->mNumberBuffers != mFormat.mChannelsPerFrame) {
LOGGER_WARNING("org.sbooth.AudioEngine.Decoder.WavPack", "_ReadAudio() called with invalid parameters");
return 0;
}
// Reset output buffer data size
for(UInt32 i = 0; i < bufferList->mNumberBuffers; ++i)
bufferList->mBuffers[i].mDataByteSize = 0;
UInt32 framesRemaining = frameCount;
UInt32 totalFramesRead = 0;
while(0 < framesRemaining) {
UInt32 framesToRead = std::min(framesRemaining, (UInt32)BUFFER_SIZE_FRAMES);
// Wavpack uses "complete" samples (one sample across all channels), i.e. a Core Audio frame
uint32_t samplesRead = WavpackUnpackSamples(mWPC.get(), mBuffer.get(), framesToRead);
if(0 == samplesRead)
break;
// The samples returned are handled differently based on the file's mode
int mode = WavpackGetMode(mWPC.get());
// Floating point files require no special handling other than deinterleaving
if(MODE_FLOAT & mode) {
float *inputBuffer = (float *)mBuffer.get();
// Deinterleave the samples
for(UInt32 channel = 0; channel < mFormat.mChannelsPerFrame; ++channel) {
float *floatBuffer = (float *)bufferList->mBuffers[channel].mData;
for(UInt32 sample = channel; sample < samplesRead * mFormat.mChannelsPerFrame; sample += mFormat.mChannelsPerFrame)
*floatBuffer++ = inputBuffer[sample];
bufferList->mBuffers[channel].mNumberChannels = 1;
bufferList->mBuffers[channel].mDataByteSize = samplesRead * sizeof(float);
}
}
// Lossless files will be handed off as integers
else if(MODE_LOSSLESS & mode) {
// WavPack hands us 32-bit signed ints with the samples low-aligned; shift them to high alignment
UInt32 shift = (UInt32)(8 * (sizeof(int32_t) - (size_t)WavpackGetBytesPerSample(mWPC.get())));
// Deinterleave the 32-bit samples and shift to high-alignment
for(UInt32 channel = 0; channel < mFormat.mChannelsPerFrame; ++channel) {
int32_t *shiftedBuffer = (int32_t *)bufferList->mBuffers[channel].mData;
for(UInt32 sample = channel; sample < samplesRead * mFormat.mChannelsPerFrame; sample += mFormat.mChannelsPerFrame)
*shiftedBuffer++ = mBuffer[sample] << shift;
bufferList->mBuffers[channel].mNumberChannels = 1;
bufferList->mBuffers[channel].mDataByteSize = samplesRead * sizeof(int32_t);
}
}
// Convert lossy files to float
else {
float scaleFactor = (1 << ((WavpackGetBytesPerSample(mWPC.get()) * 8) - 1));
// Deinterleave the 32-bit samples and convert to float
for(UInt32 channel = 0; channel < mFormat.mChannelsPerFrame; ++channel) {
float *floatBuffer = (float *)bufferList->mBuffers[channel].mData;
for(UInt32 sample = channel; sample < samplesRead * mFormat.mChannelsPerFrame; sample += mFormat.mChannelsPerFrame)
*floatBuffer++ = mBuffer[sample] / scaleFactor;
bufferList->mBuffers[channel].mNumberChannels = 1;
bufferList->mBuffers[channel].mDataByteSize = samplesRead * sizeof(float);
}
}
totalFramesRead += samplesRead;
framesRemaining -= samplesRead;
}
mCurrentFrame += totalFramesRead;
return totalFramesRead;
}
SInt64 SFB::Audio::WavPackDecoder::_SeekToFrame(SInt64 frame)
{
int result = WavpackSeekSample(mWPC.get(), (uint32_t)frame);
if(result)
mCurrentFrame = frame;
return (result ? mCurrentFrame : -1);
}
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
*
* \brief Implements backend-specific functions of the update-constraints in SYCL.
*
* \author Artem Zhmurov <zhmurov@gmail.com>
*
* \ingroup module_mdlib
*/
#include "gmxpre.h"
#include "update_constrain_gpu_internal.h"
#include "gromacs/gpu_utils/devicebuffer_sycl.h"
#include "gromacs/gpu_utils/gmxsycl.h"
#include "gromacs/gpu_utils/gputraits_sycl.h"
#include "gromacs/utility/gmxassert.h"
//! \brief Class name for scaling kernel
class ScaleKernel;
namespace gmx
{
//! \brief Function returning the scaling kernel lambda.
static auto scaleKernel(cl::sycl::handler& cgh,
DeviceAccessor<Float3, cl::sycl::access::mode::read_write> a_x,
const ScalingMatrix scalingMatrix)
{
cgh.require(a_x);
return [=](cl::sycl::id<1> itemIdx) {
Float3 x = a_x[itemIdx];
x[0] = scalingMatrix.xx * x[0] + scalingMatrix.yx * x[1] + scalingMatrix.zx * x[2];
x[1] = scalingMatrix.yy * x[1] + scalingMatrix.zy * x[2];
x[2] = scalingMatrix.zz * x[2];
a_x[itemIdx] = x;
};
}
void launchScaleCoordinatesKernel(const int numAtoms,
DeviceBuffer<Float3> d_coordinates,
const ScalingMatrix& mu,
const DeviceStream& deviceStream)
{
const cl::sycl::range<1> rangeAllAtoms(numAtoms);
cl::sycl::queue queue = deviceStream.stream();
cl::sycl::event e = queue.submit([&](cl::sycl::handler& cgh) {
auto kernel = scaleKernel(cgh, d_coordinates, mu);
cgh.parallel_for<ScaleKernel>(rangeAllAtoms, kernel);
});
// TODO: Although this only happens on the pressure coupling steps, this synchronization
// can affect the performance if nstpcouple is small. See Issue #4018
e.wait_and_throw();
}
} // namespace gmx
|
// Copyright 2018 Google LLC
//
// 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.
#include <stdio.h>
#include <sys/un.h>
#include <algorithm>
#include <vector>
#include "gtest/gtest.h"
#include "gtest/gtest.h"
#include "test/syscalls/linux/socket_test_util.h"
#include "test/syscalls/linux/unix_domain_socket_test_util.h"
#include "test/util/file_descriptor.h"
#include "test/util/test_util.h"
namespace gvisor {
namespace testing {
namespace {
TEST_P(AllSocketPairTest, BoundSenderAddrCoalesced) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
ASSERT_THAT(bind(sockets->first_fd(), sockets->first_addr(),
sockets->first_addr_size()),
SyscallSucceeds());
ASSERT_THAT(listen(sockets->first_fd(), 5), SyscallSucceeds());
ASSERT_THAT(connect(sockets->second_fd(), sockets->first_addr(),
sockets->first_addr_size()),
SyscallSucceeds());
int accepted = -1;
ASSERT_THAT(accepted = accept(sockets->first_fd(), nullptr, nullptr),
SyscallSucceeds());
FileDescriptor closer(accepted);
int i = 0;
ASSERT_THAT(RetryEINTR(send)(sockets->second_fd(), &i, sizeof(i), 0),
SyscallSucceedsWithValue(sizeof(i)));
ASSERT_THAT(bind(sockets->second_fd(), sockets->second_addr(),
sockets->second_addr_size()),
SyscallSucceeds());
i = 0;
ASSERT_THAT(RetryEINTR(send)(sockets->second_fd(), &i, sizeof(i), 0),
SyscallSucceedsWithValue(sizeof(i)));
int ri[2] = {0, 0};
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
ASSERT_THAT(
RetryEINTR(recvfrom)(accepted, ri, sizeof(ri), 0,
reinterpret_cast<sockaddr*>(&addr), &addr_len),
SyscallSucceedsWithValue(sizeof(ri)));
EXPECT_EQ(addr_len, sockets->second_addr_len());
EXPECT_EQ(
memcmp(&addr, sockets->second_addr(),
std::min((size_t)addr_len, (size_t)sockets->second_addr_len())),
0);
}
INSTANTIATE_TEST_CASE_P(
AllUnixDomainSockets, AllSocketPairTest,
::testing::ValuesIn(VecCat<SocketPairKind>(
ApplyVec<SocketPairKind>(
FilesystemUnboundUnixDomainSocketPair,
AllBitwiseCombinations(List<int>{SOCK_STREAM},
List<int>{0, SOCK_NONBLOCK},
List<int>{0, SOCK_CLOEXEC})),
ApplyVec<SocketPairKind>(
AbstractUnboundUnixDomainSocketPair,
AllBitwiseCombinations(List<int>{SOCK_STREAM},
List<int>{0, SOCK_NONBLOCK},
List<int>{0, SOCK_CLOEXEC})))));
} // namespace
} // namespace testing
} // namespace gvisor
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file SymbolicBayesNet.cpp
* @date Oct 29, 2009
* @author Frank Dellaert
* @author Richard Roberts
*/
#include <gtsam/inference/FactorGraph-inst.h>
#include <gtsam/symbolic/SymbolicBayesNet.h>
namespace gtsam {
// Instantiate base class
template class FactorGraph<SymbolicConditional>;
/* ************************************************************************* */
bool SymbolicBayesNet::equals(const This& bn, double tol) const {
return Base::equals(bn, tol);
}
} // namespace gtsam
|
#include "sequence.h"
int SequenceGenerator::findChannelIndex(int hopIncrement, int channel, int start)
{
for (int i=0; i<37; i++)
if (m_sequences[hopIncrement][(start + i)%37] == channel)
return (start + i)%37;
/* -1 if not found. */
return -1;
}
int SequenceGenerator::computeDistance(int hopIncrement, int firstChannel, int secondChannel)
{
int distance;
/* Find first channel index. */
int fcIndex = findChannelIndex(hopIncrement, firstChannel, 0);
/* Find second channel index. */
int scIndex = findChannelIndex(hopIncrement, secondChannel, fcIndex);
/* Compute distance. */
if (scIndex > fcIndex)
distance = (scIndex - fcIndex);
else
distance = (scIndex - fcIndex) + 37;
return distance;
}
/**
* generateLUT
*
* Generate a lookup table based on the distance between two channels given
* all the possible hop increment values.
**/
void SequenceGenerator::generateLUT(uint8_t *lookupTable, int firstChannel, int secondChannel)
{
for (int hopinc=0; hopinc<12; hopinc++)
{
lookupTable[hopinc] = computeDistance(hopinc, firstChannel, secondChannel);
}
}
void SequenceGenerator::generateSequence(int hopIncrement, uint8_t *sequence)
{
int channel = 0;
/* Generate sequence. */
for (int i=0; i<37; i++)
{
/* Next sequence channel. */
if (m_chm[channel] == 1)
sequence[i] = channel;
else
sequence[i] = m_remapping[channel % m_nchannels];
/* Increment channel. */
channel = (channel + hopIncrement)%37;
}
}
bool SequenceGenerator::initialize(uint8_t *chm)
{
uint8_t lut[12] = {0,0,0,0,0,0,0,0,0,0,0,0};
int i,j=0,hopinc=0, channel, count, k;
bool duplicates = false;
/* Copy chm. */
for (i=0; i<37; i++)
m_chm[i] = chm[i];
/* Generate remapping. */
for (i=0; i<37; i++)
{
if (chm[i] == 1)
{
m_remapping[j++] = i;
}
}
/* Save number of used channels. */
m_nchannels = j;
/* Generate all the possible sequences. */
for (hopinc=0; hopinc<12; hopinc++)
{
/* Generate sequence with the given hop increment. */
generateSequence(hopinc+5, m_sequences[hopinc]);
}
/* Find two specific channels. */
for (channel=0; channel<37; channel++)
{
if (m_chm[channel] == 1)
{
/* Check if channel is unique across all possible sequences. */
j = 0;
for (hopinc=0; hopinc<12; hopinc++)
{
count = 0;
for (i=0; i<37; i++)
{
if (m_sequences[hopinc][i] == channel)
{
/* Exit loop if channel is found more than once. */
count++;
if (count > 1)
break;
}
}
if (count > 1)
j = 1;
}
/**
* If channel is unique, consider it as a potential first channel and look
* for a second one in order to have a working lookup table.
**/
if (j==0)
{
/* Found our first candidate channel, now check if we can find a unique second channel. */
m_firstChannel = channel;
for (j=0; j<37; j++)
{
if (m_chm[j] == 1)
{
generateLUT(lut, m_firstChannel, j);
/* Search doubles. */
duplicates = false;
for (i=0; i<11; i++)
{
for (k=i+1; k<12; k++)
{
if (lut[i] == lut[k])
{
duplicates = true;
}
}
}
if (!duplicates)
{
/* Save second channel. */
m_secondChannel = j;
/* Generate our reverse LUT. */
for (i=0; i<37; i++)
m_rlut[i] = 0;
for (i=0; i<12; i++)
m_rlut[lut[i]] = (i+5);
/* Success. */
return true;
}
}
}
}
}
}
/* We cannot recover hop increment and interval with this chm. */
return false;
}
void SequenceGenerator::updateChannelMap(uint8_t *chm)
{
int i,j;
/* Generate remapping. */
j = 0;
for (i=0; i<37; i++)
{
if (chm[i] == 1)
{
m_remapping[j++] = i;
}
}
m_nchannels = j;
/* Copy chm. */
for (i=0; i<37; i++)
m_chm[i] = chm[i];
}
int SequenceGenerator::getFirstChannel(void)
{
return m_firstChannel;
}
int SequenceGenerator::getSecondChannel(void)
{
return m_secondChannel;
}
int SequenceGenerator::getHopIncrement(int interval)
{
return m_rlut[interval];
}
void SequenceGenerator::setHopIncrement(int increment)
{
m_hopIncrement = increment;
}
void SequenceGenerator::resetConnection(void)
{
m_currentChannel = 0;
}
int SequenceGenerator::getNextChannel(void)
{
/* Compute next channel. */
m_currentChannel = (m_currentChannel + m_hopIncrement)%37;
/* Return channel number. */
if (m_chm[m_currentChannel] == 1)
return m_currentChannel;
else
return m_remapping[m_currentChannel%m_nchannels];
}
int SequenceGenerator::getCurrentChannel(void)
{
if (m_chm[m_currentChannel] == 1)
return m_currentChannel;
else
return m_remapping[m_currentChannel%m_nchannels];
}
void SequenceGenerator::prepareToFollow(void)
{
/* Switch to first channel. */
m_currentChannel = m_firstChannel;
}
/**
* SequenceGenerator
*
* Generate the initial sequence, starting from channel 0 with automatic
* remapping of unused channels.
**/
SequenceGenerator::SequenceGenerator()
{
}
|
#include "DataModelRegistry.hpp"
#include <QtCore/QFile>
#include <QtWidgets/QMessageBox>
using QtNodes::DataModelRegistry;
using QtNodes::NodeDataModel;
using QtNodes::NodeDataType;
using QtNodes::TypeConverter;
std::unique_ptr<NodeDataModel> DataModelRegistry::create(QString const &modelName)
{
auto it = _registeredItemCreators.find(modelName);
if (it != _registeredItemCreators.end())
{
return it->second();
}
return nullptr;
}
DataModelRegistry::RegisteredModelCreatorsMap const &DataModelRegistry::registeredModelCreators() const
{
return _registeredItemCreators;
}
DataModelRegistry::RegisteredModelsCategoryMap const &DataModelRegistry::registeredModelsCategoryAssociation() const
{
return _registeredModelsCategory;
}
DataModelRegistry::CategoriesSet const &DataModelRegistry::categories() const
{
return _categories;
}
TypeConverter DataModelRegistry::getTypeConverter(QtNodes::NodeDataTypeId const &d1, QtNodes::NodeDataTypeId const &d2) const
{
TypeConverterId converterId = std::make_pair(d1, d2);
auto it = _registeredTypeConverters.find(converterId);
if (it != _registeredTypeConverters.end())
{
return it->second;
}
return TypeConverter{};
}
|
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under 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)
//
// *Preprocessed* version of the main "unpack_args.hpp" header
// -- DO NOT modify by hand!
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace mpl {
namespace aux {
template< int size, typename F, typename Args >
struct unpack_args_impl;
template< typename F, typename Args >
struct unpack_args_impl< 0,F,Args >
: apply0<
F
>
{
};
template< typename F, typename Args >
struct unpack_args_impl< 1,F,Args >
: apply1<
F
, typename at_c< Args,0 >::type
>
{
};
template< typename F, typename Args >
struct unpack_args_impl< 2,F,Args >
: apply2<
F
, typename at_c< Args,0 >::type, typename at_c< Args,1 >::type
>
{
};
template< typename F, typename Args >
struct unpack_args_impl< 3,F,Args >
: apply3<
F
, typename at_c< Args,0 >::type, typename at_c< Args,1 >::type
, typename at_c< Args,2 >::type
>
{
};
template< typename F, typename Args >
struct unpack_args_impl< 4,F,Args >
: apply4<
F
, typename at_c< Args,0 >::type, typename at_c< Args,1 >::type
, typename at_c< Args,2 >::type, typename at_c< Args,3 >::type
>
{
};
template< typename F, typename Args >
struct unpack_args_impl< 5,F,Args >
: apply5<
F
, typename at_c< Args,0 >::type, typename at_c< Args,1 >::type
, typename at_c< Args,2 >::type, typename at_c< Args,3 >::type
, typename at_c< Args,4 >::type
>
{
};
}
template<
typename F
>
struct unpack_args
{
template< typename Args > struct apply
{
typedef typename aux::unpack_args_impl<
size<Args>::value
, F
, Args
>::type type;
};
};
BOOST_MPL_AUX_PASS_THROUGH_LAMBDA_SPEC(1, unpack_args)
}}
|
/*
SPDX-License-Identifier: MIT
Copyright (c) 2021 Bart Bilos
For conditions of distribution and use, see LICENSE file
*/
/** \file testArray.cpp
\brief Tests for util::atomic
Tests for util::atomic
*/
#include <MinUnit.h>
#include <stdint.h>
#include <atomic.hpp>
/** \brief util::atomic test uint16_t atomics */
MINUNIT_ADD(testAtomicUint16, NULL, NULL)
{
util::atomic<uint16_t> Dut {0u};
minUnitCheck(Dut.load() == 0u);
Dut = 1u;
minUnitCheck(Dut.load() == 1u);
Dut++;
minUnitCheck(Dut.load() == 2u);
Dut--;
minUnitCheck(Dut.load() == 1u);
Dut = Dut + 1;
minUnitCheck(Dut.load() == 2u);
Dut = Dut - 1;
minUnitCheck(Dut.load() == 1u);
Dut = 0xFF00;
Dut = Dut & 0x0FFF;
minUnitCheck(Dut.load() == 0x0F00);
Dut = Dut | 0x05F5;
minUnitCheck(Dut.load() == 0x0FF5);
Dut = Dut ^ 0x05F0;
minUnitCheck(Dut.load() == 0x0A05);
uint16_t old = Dut.exchange(0x0012);
minUnitCheck(Dut.load() == 0x0012);
minUnitCheck(old == 0x0A05);
uint16_t expected = 0x0013;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x0014) == false);
minUnitCheck(Dut.load() == 0x0012);
expected = 0x0012;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x0014) == true);
minUnitCheck(Dut.load() == 0x0014);
expected = 0x0013;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x0014) == false);
minUnitCheck(Dut.load() == 0x0014);
expected = 0x0014;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x0012) == true);
minUnitCheck(Dut.load() == 0x0012);
}
/** \brief util::atomic test int atomics */
MINUNIT_ADD(testAtomicInt, NULL, NULL)
{
util::atomic<int> Dut {0};
minUnitCheck(Dut.load() == 0);
Dut = 1;
minUnitCheck(Dut.load() == 1);
Dut++;
minUnitCheck(Dut.load() == 2);
Dut--;
minUnitCheck(Dut.load() == 1);
Dut = Dut + 1;
minUnitCheck(Dut.load() == 2);
Dut = Dut - 1;
minUnitCheck(Dut.load() == 1);
int old = Dut.exchange(5);
minUnitCheck(Dut.load() == 5);
minUnitCheck(old == 1);
int expected = 6;
minUnitCheck(Dut.compare_exchange_weak(expected, 7) == false);
minUnitCheck(Dut.load() == 5);
expected = 5;
minUnitCheck(Dut.compare_exchange_weak(expected, 7) == true);
minUnitCheck(Dut.load() == 7);
}
/** \brief util::atomic test uint8_t atomics */
MINUNIT_ADD(testAtomicUint8, NULL, NULL)
{
util::atomic<uint8_t> Dut {0u};
minUnitCheck(Dut.load() == 0u);
Dut = 1u;
minUnitCheck(Dut.load() == 1u);
Dut++;
minUnitCheck(Dut.load() == 2u);
Dut--;
minUnitCheck(Dut.load() == 1u);
Dut = Dut + 1;
minUnitCheck(Dut.load() == 2u);
Dut = Dut - 1;
minUnitCheck(Dut.load() == 1u);
Dut = 0xF0;
Dut = Dut & 0x33;
minUnitCheck(Dut.load() == 0x30);
Dut = Dut | 0xF3;
minUnitCheck(Dut.load() == 0xF3);
Dut = Dut ^ 0x37;
minUnitCheck(Dut.load() == 0xC4);
uint8_t old = Dut.exchange(0x12);
minUnitCheck(Dut.load() == 0x12);
minUnitCheck(old == 0xC4);
uint8_t expected = 0x13;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x14) == false);
minUnitCheck(Dut.load() == 0x12);
expected = 0x12;
minUnitCheck(Dut.compare_exchange_weak(expected, 0x14) == true);
minUnitCheck(Dut.load() == 0x14);
}
|
// Copyright 2021 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 "components/webapps/common/constants.h"
namespace webapps {
const size_t kMaxMetaTagAttributeLength = 2000;
const char kWebAppsMigratedPreinstalledApps[] =
"web_apps.migrated_default_apps";
} // namespace webapps
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "primitives/GTTableView.h"
#include <primitives/GTWidget.h>
#include <utils/GTThread.h>
namespace HI {
#define GT_CLASS_NAME "GTSpinBox"
#define GT_METHOD_NAME "getCellPosition"
QPoint GTTableView::getCellPosition(GUITestOpStatus &os, QTableView *table, int column, int row) {
GT_CHECK_RESULT(table, "table view is NULL", QPoint());
QPoint p(table->columnViewportPosition(column) + table->columnWidth(column) / 2,
table->rowViewportPosition(row) + table->rowHeight(row) * 1.5);
QPoint pGlob = table->mapToGlobal(p);
return pGlob;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "scrollTo"
void GTTableView::scrollTo(GUITestOpStatus &os, QTableView *table, const QModelIndex &index) {
// TODO: set index by mouse/keyboard
class MainThreadAction : public CustomScenario {
public:
MainThreadAction(QTableView *table, const QModelIndex &index)
: CustomScenario(), table(table), index(index) {
}
void run(HI::GUITestOpStatus &os) {
Q_UNUSED(os);
table->scrollTo(index);
}
QTableView *table;
QModelIndex index;
};
GTThread::runInMainThread(os, new MainThreadAction(table, index));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getCellPoint"
QPoint GTTableView::getCellPoint(GUITestOpStatus &os, QTableView *table, int row, int column) {
QModelIndex idx = table->model()->index(row, column);
scrollTo(os, table, idx);
QRect rect = table->visualRect(idx);
QWidget *content = GTWidget::findWidget(os, "qt_scrollarea_viewport", table);
return content->mapToGlobal(rect.center());
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "rowCount"
int GTTableView::rowCount(GUITestOpStatus &os, QTableView *table) {
GT_CHECK_RESULT(table != NULL, "Table view is NULL", -1);
GT_CHECK_RESULT(table->model() != NULL, "Table view model is NULL", -1);
return table->model()->rowCount(QModelIndex());
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "data"
QString GTTableView::data(GUITestOpStatus &os, QTableView *table, int row, int column) {
GT_CHECK_RESULT(NULL != table, "Table view is NULL", "");
GT_CHECK_RESULT(NULL != table->model(), "Table view model is NULL", "");
QModelIndex idx = table->model()->index(row, column);
GT_CHECK_RESULT(idx.isValid(), "Item index is invalid", "");
return table->model()->data(idx, Qt::DisplayRole).toString();
}
#undef GT_METHOD_NAME
#undef GT_CLASS_NAME
} // namespace HI
|
// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#define printf OutputDebugStringF
using namespace json_spirit;
using namespace std;
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey <BTCBITZCoinprivkey> [label] [rescan=true]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
CKeyID vchAddress = pubkey.GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
if (fRescan) {
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <BTCBITZCoinaddress>\n"
"Reveals the private key corresponding to <BTCBITZCoinaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BTCBITZCoin address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret).ToString();
}
|
//
// Created by 李晨曦 on 30/10/2017.
//
#include "Slot.hpp"
Slot::Slot(int32_t num) : num(num)
{}
Slot::Slot(Object* ref) : ref(ref)
{}
LocalVars::LocalVars(uint32_t maxLocals)
{
this->slots = std::vector<Slot *>(maxLocals);
for (uint32_t i = 0; i < maxLocals; i++)
{
this->slots[i] = new Slot(0);
}
}
OperandStack::OperandStack(uint32_t maxStack) : size(0)
{
this->slots = std::vector<Slot *>(maxStack);
for (uint32_t i = 0; i < maxStack; i++)
{
this->slots[i] = new Slot(0);
}
}
|
/**
* Copyright (C) 2020 IBM Corporation
*
* 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.
*/
#include "registration.hpp"
extern "C"
{
#include <libpdbg.h>
#include <libpdbg_sbe.h>
}
#include "extensions/phal/create_pel.hpp"
#include "extensions/phal/dump_utils.hpp"
#include <attributes_info.H>
#include <fmt/format.h>
#include <libphal.H>
#include <phal_exception.H>
#include <sys/wait.h>
#include <unistd.h>
#include <phosphor-logging/log.hpp>
#include <system_error>
#include <vector>
namespace openpower
{
namespace misc
{
/**
* @brief Calls sbe_enter_mpipl on the SBE in the provided target.
* @return void
*/
void sbeEnterMpReboot(struct pdbg_target* tgt)
{
using namespace openpower::pel;
using namespace openpower::phal;
using namespace openpower::phal::sbe;
using namespace openpower::phal::exception;
using namespace phosphor::logging;
try
{
mpiplEnter(tgt);
}
catch (const sbeError_t& sbeError)
{
if (sbeError.errType() == SBE_CHIPOP_NOT_ALLOWED)
{
// SBE is not ready to accept chip-ops,
// Skip the request, no additional error handling required.
log<level::INFO>(
fmt::format("EnterMPIPL: Skipping ({}) on proc({})",
sbeError.what(), pdbg_target_index(tgt))
.c_str());
return;
}
log<level::ERR>(fmt::format("EnterMPIPL failed({}) on proc({})",
sbeError.what(), pdbg_target_index(tgt))
.c_str());
std::string event;
bool dumpIsRequired = false;
if (sbeError.errType() == SBE_CMD_TIMEOUT)
{
event = "org.open_power.Processor.Error.SbeChipOpTimeout";
dumpIsRequired = true;
}
else
{
event = "org.open_power.Processor.Error.SbeChipOpFailure";
}
// SRC6 : [0:15] chip position [16:23] command class, [24:31] Type
uint32_t index = pdbg_target_index(tgt);
// TODO Replace these consts with pdbg defines once it is exported.
// Ref : pdbg/libsbefifo/sbefifo_private.h
constexpr auto SBEFIFO_CMD_CLASS_MPIPL = 0xA900;
constexpr auto SBEFIFO_CMD_ENTER_MPIPL = 0x01;
uint32_t cmd = SBEFIFO_CMD_CLASS_MPIPL | SBEFIFO_CMD_ENTER_MPIPL;
// To store additional data about ffdc.
FFDCData pelAdditionalData;
pelAdditionalData.emplace_back("SRC6",
std::to_string((index << 16) | cmd));
auto logId = createSbeErrorPEL(event, sbeError, pelAdditionalData);
if (dumpIsRequired)
{
// Request SBE Dump
using namespace openpower::phal::dump;
DumpParameters dumpParameters = {logId, index, SBE_DUMP_TIMEOUT,
DumpType::SBE};
requestDump(dumpParameters);
}
throw;
}
// Capture genaral libphal error
catch (const phalError_t& phalError)
{
// Failure reported
log<level::ERR>(fmt::format("captureFFDC: Exception({}) on proc({})",
phalError.what(), pdbg_target_index(tgt))
.c_str());
openpower::pel::createPEL(
"org.open_power.Processor.Error.SbeChipOpFailure");
throw;
}
log<level::INFO>(
fmt::format("Enter MPIPL completed on proc({})", pdbg_target_index(tgt))
.c_str());
}
/**
* @brief initiate memory preserving reboot on each SBE.
* @return void
*/
void enterMpReboot()
{
using namespace phosphor::logging;
struct pdbg_target* target;
std::vector<pid_t> pidList;
bool failed = false;
pdbg_targets_init(NULL);
ATTR_HWAS_STATE_Type hwasState;
log<level::INFO>("Starting memory preserving reboot");
pdbg_for_each_class_target("proc", target)
{
if (DT_GET_PROP(ATTR_HWAS_STATE, target, hwasState))
{
log<level::ERR>("Could not read HWAS_STATE attribute");
}
if (!hwasState.functional)
{
continue;
}
pid_t pid = fork();
if (pid < 0)
{
log<level::ERR>("Fork failed while starting mp reboot");
failed = true;
}
else if (pid == 0)
{
sbeEnterMpReboot(target);
std::exit(EXIT_SUCCESS);
}
else
{
pidList.push_back(std::move(pid));
}
}
for (auto& p : pidList)
{
int status = 0;
waitpid(p, &status, 0);
if (WEXITSTATUS(status))
{
log<level::ERR>("Memory preserving reboot failed");
failed = true;
}
}
if (failed)
{
std::exit(EXIT_FAILURE);
}
}
REGISTER_PROCEDURE("enterMpReboot", enterMpReboot)
} // namespace misc
} // namespace openpower
|
/* $Id: seqsrc_unit_test.cpp 199874 2010-08-03 17:21:21Z camacho $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Ilya Dondoshansky
*
* File Description:
* Unit test module for sequence source functionality
*
* ===========================================================================
*/
#include <ncbi_pch.hpp>
#include <corelib/test_boost.hpp>
#include <serial/iterator.hpp>
#include <objmgr/util/sequence.hpp>
#include <objects/seq/Bioseq.hpp>
#include <objects/seqloc/Seq_loc.hpp>
#include <objmgr/object_manager.hpp>
#include <objmgr/scope.hpp>
#include <algo/blast/api/seqsrc_multiseq.hpp>
#include <algo/blast/api/seqsrc_seqdb.hpp>
#include <algo/blast/core/blast_util.h>
#include "blast_objmgr_priv.hpp"
#ifdef KAPPA_PRINT_DIAGNOSTICS
/* C toolkit ! */
#include <algo/blast/api/seqsrc_readdb.h>
#endif /* KAPPA_PRINT_DIAGNOSTICS */
#include <objtools/blast/seqdb_reader/seqdb.hpp>
#include <objects/seqloc/Seq_id.hpp>
#include <corelib/ncbithr.hpp>
#include "test_objmgr.hpp"
using namespace std;
USING_NCBI_SCOPE;
USING_SCOPE(objects);
USING_SCOPE(blast);
// Retrieves a vector of sequences from a file
static TSeqLocVector s_getSequences()
{
const int kNumSeqs = 70;
const int kGiList[kNumSeqs] =
{ 1786181, 1786192, 2367095, 1786217, 1786230, 1786240, 1786250,
1786262, 1786283, 1786298, 1786306, 1786315, 1786327, 1786339,
1786348, 1786358, 1786370, 1786383, 1786395, 1786402, 1786415,
2367098, 2367099, 1786454, 1786465, 2367103, 2367108, 1786501,
1786510, 1786520, 1786532, 1786542, 1786554, 1786568, 1786580,
1786596, 1786603, 1786614, 1786628, 1786639, 1786649, 1786660,
1786671, 1786683, 1786692, 1786705, 1786716, 1786728, 1786739,
1786751, 1786766, 1786782, 1786790, 1786800, 1786808, 1786819,
1786836, 1786849, 1786862, 1786875, 1786888, 1786896, 1786910,
1786920, 1786934, 1786947, 1786955, 1786967, 1786978, 1786988 };
TSeqLocVector retval;
char id_buffer[16];
int index;
for (index = 0; index < kNumSeqs; ++index) {
sprintf(id_buffer, "gi|%d", kGiList[index]);
CSeq_id id(id_buffer);
auto_ptr<SSeqLoc> sl(
CTestObjMgr::Instance().
CreateSSeqLoc(id, eNa_strand_both));
retval.push_back(*sl);
}
return retval;
}
BOOST_AUTO_TEST_SUITE(seqsrc)
#ifdef KAPPA_PRINT_DIAGNOSTICS
static void
s_TestGetGis(BlastSeqSrc* seqsrc, const pair<string, bool>& dbinfo) {
const int gis[] = { 68737, 129295 };
CSeqDB seqdb(dbinfo.first, dbinfo.second
? CSeqDB::eProtein : CSeqDB::eNucleotide);
int oid = -1;
seqdb.GiToOid(gis[0], oid);
BOOST_REQUIRE(oid != -1);
Blast_GiList* gilist = BlastSeqSrcGetGis(seqsrc, (void*)&oid);
sort(&gilist->data[0], &gilist->data[gilist->num_used]);
for (size_t i = 0; i < gilist->num_used; i++) {
BOOST_REQUIRE_EQUAL(gilist->data[i], gis[i]);
}
gilist = Blast_GiListFree(gilist);
}
BOOST_AUTO_TEST_CASE(testGetGisSeqDb) {
const pair<string, bool> kDbInfo("nr", true);
BlastSeqSrc* seq_src = SeqDbBlastSeqSrcInit(kDbInfo.first,
kDbInfo.second);
char* error_str = BlastSeqSrcGetInitError(seq_src);
BOOST_REQUIRE(error_str == NULL);
s_TestGetGis(seq_src, kDbInfo);
BlastSeqSrcFree(seq_src);
}
BOOST_AUTO_TEST_CASE(testGetGisReaddb) {
const pair<string, bool> kDbInfo("nr", true);
BlastSeqSrc* seq_src = ReaddbBlastSeqSrcInit(kDbInfo.first.c_str(),
kDbInfo.second, 0, 0);
char* error_str = BlastSeqSrcGetInitError(seq_src);
BOOST_REQUIRE(error_str == NULL);
s_TestGetGis(seq_src, kDbInfo);
BlastSeqSrcFree(seq_src);
}
#endif /* KAPPA_PRINT_DIAGNOSTICS */
BOOST_AUTO_TEST_CASE(testMultiSeqSrc_FailureToInitialize) {
TSeqLocVector sequences = s_getSequences();
// sequences contains nucleotide sequences, thus initialization should
// fail
BlastSeqSrc* seq_src =
MultiSeqBlastSeqSrcInit(sequences, eBlastTypeBlastp);
char* error_str = BlastSeqSrcGetInitError(seq_src);
BOOST_REQUIRE(error_str != NULL);
sfree(error_str);
BlastSeqSrcFree(seq_src);
}
BOOST_AUTO_TEST_CASE(testMultiSeqSrc) {
const int kNumBytes = 4;
const int kSeqIndex = 40;
const Uint1 kNcbi2naSeqBytes[kNumBytes] = { 48, 215, 159, 129 };
const Uint1 kBlastnaSeqBytes[kNumBytes] = { 0, 3, 0, 0 };
TSeqLocVector sequences = s_getSequences();
const int kNumSeqs = (int) sequences.size();
BlastSeqSrc* seq_src =
MultiSeqBlastSeqSrcInit(sequences, eBlastTypeBlastn);
BOOST_REQUIRE_EQUAL(kNumSeqs, (int)BlastSeqSrcGetNumSeqs(seq_src));
BOOST_REQUIRE_EQUAL(0, (int) BlastSeqSrcGetTotLen(seq_src));
BOOST_REQUIRE(BlastSeqSrcGetIsProt(seq_src) == false);
BOOST_REQUIRE(strcmp(BlastSeqSrcGetName(seq_src), NcbiEmptyCStr) == 0);
BlastSeqSrcIterator* itr = BlastSeqSrcIteratorNew();
int index, last_index=0;
Uint4 length, max_len=0, avg_len=0;
while ((index = BlastSeqSrcIteratorNext(seq_src, itr))
!= BLAST_SEQSRC_EOF) {
++last_index;
length = BlastSeqSrcGetSeqLen(seq_src, (void*)&index);
BOOST_REQUIRE_EQUAL(sequence::GetLength(*sequences[index].seqloc, sequences[index].scope), length);
avg_len += length;
max_len = MAX(max_len, length);
}
itr = BlastSeqSrcIteratorFree(itr);
BOOST_REQUIRE_EQUAL(kNumSeqs, last_index);
avg_len /= kNumSeqs;
BOOST_REQUIRE_EQUAL((int)max_len, BlastSeqSrcGetMaxSeqLen(seq_src));
BOOST_REQUIRE_EQUAL((int)avg_len, BlastSeqSrcGetAvgSeqLen(seq_src));
BlastSeqSrcGetSeqArg* seq_arg = (BlastSeqSrcGetSeqArg*) calloc(1, sizeof(BlastSeqSrcGetSeqArg));
seq_arg->oid = kSeqIndex;
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src, seq_arg) >= 0);
// Sequence length
BOOST_REQUIRE_EQUAL((int)sequence::GetLength(*sequences[kSeqIndex].seqloc,
sequences[kSeqIndex].scope),
seq_arg->seq->length);
// Check first few bytes of a compressed sequence
for (index = 0; index < kNumBytes; ++index) {
BOOST_REQUIRE_EQUAL(kNcbi2naSeqBytes[index],
seq_arg->seq->sequence[index]);
}
BlastSequenceBlkClean(seq_arg->seq);
// Now check the uncompressed sequence retrieval
seq_arg->encoding = eBlastEncodingNucleotide;
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src, seq_arg) >= 0);
for (index = 0; index < kNumBytes; ++index) {
BOOST_REQUIRE_EQUAL(kBlastnaSeqBytes[index],
seq_arg->seq->sequence[index]);
}
BlastSequenceBlkFree(seq_arg->seq);
sfree(seq_arg);
BlastSeqSrcFree(seq_src);
}
BOOST_AUTO_TEST_CASE(testSeqDBSrc_FailureToInitialize_NullDb) {
string null_db("");
BlastSeqSrc* seq_src = SeqDbBlastSeqSrcInit(null_db, true);
char* error_str = BlastSeqSrcGetInitError(seq_src);
BOOST_REQUIRE(error_str != NULL);
sfree(error_str);
BlastSeqSrcFree(seq_src);
}
BOOST_AUTO_TEST_CASE(testSeqDBSrc_FailureToInitialize_NonExistentDb) {
BlastSeqSrc* seq_src = SeqDbBlastSeqSrcInit("junk", false);
char* error_str = BlastSeqSrcGetInitError(seq_src);
BOOST_REQUIRE(error_str != NULL);
sfree(error_str);
BlastSeqSrcFree(seq_src);
}
static void
s_checkDbSeqSrcFunctions(BlastSeqSrc* seq_src, const char* dbname)
{
const int kNumSeqs = 2004;
const int kRealNumSeqs = 1000;
const int kMaxLen = 875;
const int kMaxLenRange = 839;
const int kTotLen = 943942;
const int kTotLenRange = 478404;
const int kAvgLen = 471;
const int kSeqIndex = 1500;
const int kSeqLength = 715;
const int kNumBytes_2na = 4;
const int kNumBytes_4na = 5;
const int kNcbi2naSeqBytes[kNumBytes_2na] = { 159, 145, 213, 43 };
const int kBlastnaSeqBytes[kNumBytes_4na] = { 15, 2, 1, 3, 3 };
BOOST_REQUIRE(BlastSeqSrcGetIsProt(seq_src) == false);
BOOST_REQUIRE_EQUAL(kNumSeqs, BlastSeqSrcGetNumSeqs(seq_src));
BOOST_REQUIRE_EQUAL(kTotLen, (int) BlastSeqSrcGetTotLen(seq_src));
BOOST_REQUIRE_EQUAL(kMaxLen, BlastSeqSrcGetMaxSeqLen(seq_src));
BOOST_REQUIRE_EQUAL(kAvgLen, BlastSeqSrcGetAvgSeqLen(seq_src));
BOOST_REQUIRE(!strcmp(dbname, BlastSeqSrcGetName(seq_src)));
BlastSeqSrcIterator* itr = BlastSeqSrcIteratorNew();
int index, last_index=0;
Int8 total_length = 0;
Int4 max_length = 0;
Int4 length = 0;
// Test the iterator
while ((index = BlastSeqSrcIteratorNext(seq_src, itr))
!= BLAST_SEQSRC_EOF) {
++last_index;
length = BlastSeqSrcGetSeqLen(seq_src, (void*)&index);
max_length = MAX(max_length, length);
total_length += (Int8) length;
}
itr = BlastSeqSrcIteratorFree(itr);
BOOST_REQUIRE_EQUAL(kRealNumSeqs, last_index);
BOOST_REQUIRE_EQUAL(kTotLenRange, (int)total_length);
BOOST_REQUIRE_EQUAL(kMaxLenRange, max_length);
// Test a particular sequence
BlastSeqSrcGetSeqArg* seq_arg = (BlastSeqSrcGetSeqArg*) calloc(1, sizeof(BlastSeqSrcGetSeqArg));
seq_arg->oid = kSeqIndex;
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src, seq_arg) >= 0);
// Sequence length
BOOST_REQUIRE_EQUAL(kSeqLength, seq_arg->seq->length);
BOOST_REQUIRE_EQUAL(kSeqLength,
BlastSeqSrcGetSeqLen(seq_src, (void*) &seq_arg->oid));
// Check first few bytes of a compressed sequence
for (index = 0; index < kNumBytes_2na; ++index) {
BOOST_REQUIRE_EQUAL(kNcbi2naSeqBytes[index],
(int)seq_arg->seq->sequence[index]);
}
BlastSeqSrcReleaseSequence(seq_src, seq_arg);
// Now check the uncompressed sequence retrieval
seq_arg->encoding = eBlastEncodingNucleotide;
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src, seq_arg) >= 0);
BOOST_REQUIRE(seq_arg != NULL);
BOOST_REQUIRE(seq_arg->seq != NULL);
BOOST_REQUIRE(seq_arg->seq->sequence_start != NULL);
for (index = 0; index < kNumBytes_4na; ++index) {
BOOST_REQUIRE_EQUAL(kBlastnaSeqBytes[index],
(int)seq_arg->seq->sequence_start[index]);
}
BlastSeqSrcReleaseSequence(seq_src, seq_arg);
BlastSequenceBlkFree(seq_arg->seq);
sfree(seq_arg);
}
BOOST_AUTO_TEST_CASE(testSeqDBSrc) {
const char* kDbName = "data/seqn";
const Uint4 kFirstSeq = 1000;
const Uint4 kFinalSeq = 2000;
BlastSeqSrc* seq_src =
SeqDbBlastSeqSrcInit(kDbName, false, kFirstSeq, kFinalSeq);
s_checkDbSeqSrcFunctions(seq_src, kDbName);
BlastSeqSrcFree(seq_src);
}
BOOST_AUTO_TEST_CASE(testSeqDBSrcExisting)
{
// Test that a SeqDB object can be shared with the SeqSrc
// mechanism safely.
const char* kDbName = "data/seqn";
const Uint4 kFirstSeq = 1000;
const Uint4 kFinalSeq = 2000;
CRef<CSeqDB> seqdb(new CSeqDB(kDbName, CSeqDB::eNucleotide, kFirstSeq, kFinalSeq, true));
string title(seqdb->GetTitle());
BlastSeqSrc* seq_src = SeqDbBlastSeqSrcInit(seqdb);
s_checkDbSeqSrcFunctions(seq_src, kDbName);
BlastSeqSrcFree(seq_src);
string title2(seqdb->GetTitle());
BOOST_REQUIRE_EQUAL(title, title2);
}
BOOST_AUTO_TEST_CASE(testSeqDBSrcShared)
{
// Further test - multiple SeqSrc objects can use the same
// SeqDB object.
const char* kDbName = "data/seqn";
const Uint4 kFirstSeq = 1000;
const Uint4 kFinalSeq = 2000;
BlastSeqSrc * seq_src2 = 0;
{
BlastSeqSrc * seq_src1 = 0;
CRef<CSeqDB> seqdb(new CSeqDB(kDbName, CSeqDB::eNucleotide, kFirstSeq, kFinalSeq, true));
seq_src1 = SeqDbBlastSeqSrcInit(seqdb);
seq_src2 = SeqDbBlastSeqSrcInit(seqdb);
BlastSeqSrcGetSeqArg seq_arg1, seq_arg2;
memset((void*) &seq_arg1, 0, sizeof(BlastSeqSrcGetSeqArg));
memset((void*) &seq_arg2, 0, sizeof(BlastSeqSrcGetSeqArg));
seq_arg1.oid = seq_arg2.oid = 5;
s_checkDbSeqSrcFunctions(seq_src1, kDbName);
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src1, &seq_arg1) >= 0);
BOOST_REQUIRE(BlastSeqSrcGetSequence(seq_src2, &seq_arg2) >= 0);
BOOST_REQUIRE(seq_arg1.seq);
BOOST_REQUIRE(seq_arg2.seq);
BlastSeqSrcReleaseSequence(seq_src1, &seq_arg1);
BlastSeqSrcReleaseSequence(seq_src2, &seq_arg2);
BlastSequenceBlkFree(seq_arg1.seq);
BlastSequenceBlkFree(seq_arg2.seq);
BlastSeqSrcFree(seq_src1);
}
// The SeqDB object should not be deleted until here.
BlastSeqSrcFree(seq_src2);
}
// Disabled because boost does not support MT testing
#if 0
/// Structure containing counts that are updated during iteration.
/// Updating total length and maximal length is expensive, so it is not done
/// for large databases.
typedef struct SSeqSrcTestInfo {
Int4 num_seqs; ///< Number of sequences.
Int4 max_length; ///< Maximal length.
Int8 total_length; ///< Total length of sequences.
} SSeqSrcTestInfo;
/// Enumeration specifying what to database lengths to check in iteration
/// tests.
typedef enum ECheckLengths {
eCheckNone = 0, ///< Test only number of sequences.
eCheckTotal, ///< Also test total database length and average
/// sequence length
eCheckTotalAndMax ///< Also test maximal sequence length. This can only
/// work for real databases, not restricted to range
/// or OID mask.
} ECheckLengths;
/// Class for multi-threaded iteration over a BlastSeqSrc.
class CSeqSrcTestThread : public CThread
{
BlastSeqSrc* m_ipSeqSrc;
CFastMutex* m_pMutex;
SSeqSrcTestInfo* m_pTestInfo;
ECheckLengths m_iCheckLengths;
CSeqSrcTestThread(BlastSeqSrc* seq_src, CFastMutex* mutex,
SSeqSrcTestInfo* info, ECheckLengths cl)
: m_pMutex(mutex), m_pTestInfo(info), m_iCheckLengths(cl)
{
m_ipSeqSrc = BlastSeqSrcCopy(seq_src);
}
~CSeqSrcTestThread() {}
virtual void* Main(void)
{
BlastSeqSrcIterator* itr = BlastSeqSrcIteratorNew();
Int4 oid;
Int4 counter = 0;
Int4 length, max_len = 0;
Int8 tot_len = 0;
while ( (oid = BlastSeqSrcIteratorNext(m_ipSeqSrc, itr))
!= BLAST_SEQSRC_EOF) {
if (oid == BLAST_SEQSRC_ERROR)
break;
++counter;
if (m_iCheckLengths != eCheckNone) {
length = BlastSeqSrcGetSeqLen(m_ipSeqSrc, (void*)&oid);
max_len = MAX(max_len, length);
tot_len += (Int8) length;
}
}
m_ipSeqSrc = BlastSeqSrcFree(m_ipSeqSrc);
BlastSeqSrcIteratorFree(itr);
CFastMutexGuard g(*m_pMutex);
m_pTestInfo->num_seqs += counter;
m_pTestInfo->total_length += tot_len;
m_pTestInfo->max_length = MAX(m_pTestInfo->max_length, max_len);
return NULL;
}
virtual void OnExit(void) {}
};
/// Tests multi-threaded BlastSeqSrc iterator functionality
/// and frees BlastSeqSrc when done.
/// @param seq_src Pointer to the BlastSeqSrc structure. [in]
/// @param check_lengths Which lengths should be calculated in the iteration
/// and tested? [in]
/// @param num_threads How many threads to use? [in]
/// @param numseqs Number of sequences in database, used if database is
/// restricted to a range; real number of sequences is used
/// if 0 is passed. [in]
static void
s_TestSeqSrcIteratorMT(BlastSeqSrc** seq_src_ptr,
ECheckLengths check_lengths,
int num_threads, int numseqs)
{
vector< CRef<CSeqSrcTestThread> > test_thread_v;
test_thread_v.reserve(num_threads);
CFastMutex mutex;
int thr_index;
BlastSeqSrc* seq_src;
if (!seq_src_ptr)
return;
seq_src = *seq_src_ptr;
if (numseqs == 0)
numseqs = BlastSeqSrcGetNumSeqs(seq_src);
SSeqSrcTestInfo* info =
(SSeqSrcTestInfo*) calloc(1, sizeof(SSeqSrcTestInfo));
for (thr_index = 0; thr_index < num_threads; ++thr_index) {
CRef<CSeqSrcTestThread>
next_thread(new CSeqSrcTestThread(seq_src, &mutex, info,
check_lengths));
test_thread_v.push_back(next_thread);
next_thread->Run();
}
for (thr_index = 0; thr_index < num_threads; ++thr_index) {
test_thread_v[thr_index]->Join();
}
BOOST_REQUIRE_EQUAL(numseqs, info->num_seqs);
if (check_lengths != eCheckNone) {
BOOST_REQUIRE_EQUAL(BlastSeqSrcGetTotLen(seq_src),
info->total_length);
BOOST_REQUIRE_EQUAL(BlastSeqSrcGetAvgSeqLen(seq_src),
(int) (info->total_length/info->num_seqs));
if (check_lengths == eCheckTotalAndMax) {
BOOST_REQUIRE_EQUAL(BlastSeqSrcGetMaxSeqLen(seq_src),
info->max_length);
}
}
sfree(info);
*seq_src_ptr = BlastSeqSrcFree(seq_src);
}
/// Finds a range in a multi-volume database which spans several volumes.
/// Range spans 'num' sequences in starting volume and ending volume, plus
/// everything in between.
/// @param dbname Name of the database [in]
/// @param is_prot Is database nucleotide or protein? [in]
/// @param vol_start Starting volume [in]
/// @param vol_end Ending volume [in]
/// @param num Number of sequences in first and last volumes to include in
/// the range [in]
/// @param first_seq First ordinal id in the range [out]
/// @param last_seq Last ordinal id in the range [out]
/// @param use_seqdb Use readdb or SeqDb interface? [in]
static void
s_GetRangeBounds(const string& dbname, bool is_prot,
int vol_start, int vol_end, int num,
Uint4* first_seq, Uint4* last_seq,
bool use_seqdb)
{
string vol_name;
int index;
int seqs_count = 0;
CSeqDB::ESeqType prot_nucl = (is_prot ? CSeqDB::eProtein : CSeqDB::eNucleotide);
for (index = 0; index <= vol_start; ++index) {
vol_name = dbname + ".0" + NStr::IntToString(index);
CSeqDB seqdb(vol_name, prot_nucl);
int nseqs(0);
seqdb.GetTotals(CSeqDB::eFilteredAll, & nseqs, 0, true);
seqs_count += nseqs;
}
*first_seq = seqs_count - num;
for ( ; index < vol_end; ++index) {
vol_name = dbname + ".0" + NStr::IntToString(index);
CSeqDB seqdb(vol_name, prot_nucl);
int nseqs(0);
seqdb.GetTotals(CSeqDB::eFilteredAll, & nseqs, 0, true);
seqs_count += nseqs;
}
*last_seq = seqs_count + num;
}
/// Tests multi-threaded SeqDB iteration.
static void
s_TestSeqDbIterator(const string& dbname, bool is_prot, int first_seq,
int last_seq, int nthreads, ECheckLengths check_lengths)
{
BlastSeqSrc* seq_src =
SeqDbBlastSeqSrcInit(dbname, is_prot, first_seq, last_seq);
s_TestSeqSrcIteratorMT(&seq_src, check_lengths, nthreads,
last_seq - first_seq);
}
/// Plain single volume seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_2)
{
s_TestSeqDbIterator("patnt", false, 0, 0, 2, eCheckNone);
}
/// Plain single volume seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_4)
{
s_TestSeqDbIterator("patnt", false, 0, 0, 4, eCheckNone);
}
/// Plain single volume seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_20)
{
s_TestSeqDbIterator("patnt", false, 0, 0, 20, eCheckNone);
}
/// Plain single volume seqdb, restricted to range of ordinal ids,
/// 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_range_2)
{
s_TestSeqDbIterator("patnt", false, 1000, 10000, 2, eCheckNone);
}
/// Plain single volume seqdb, restricted to range of ordinal ids,
/// 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_range_4)
{
s_TestSeqDbIterator("patnt", false, 1000, 10000, 4, eCheckNone);
}
/// Plain single volume seqdb, restricted to range of ordinal ids,
/// 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_patnt_range_20)
{
s_TestSeqDbIterator("patnt", false, 1000, 10000, 20, eCheckNone);
}
/// Multi-volume seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_2)
{
s_TestSeqDbIterator("nt", false, 0, 0, 2, eCheckNone);
}
/// Multi-volume seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_4)
{
s_TestSeqDbIterator("nt", false, 0, 0, 4, eCheckNone);
}
/// Multi-volume seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_20)
{
s_TestSeqDbIterator("nt", false, 0, 0, 20, eCheckNone);
}
/// Multi volume seqdb, restricted to range of ordinal ids spanning
/// 3 volumes;
void s_TestSeqDbIterator_nt_range(int nthreads)
{
const int kNumSeqs = 1000;
const string kDbName("nt");
Uint4 first_seq;
Uint4 last_seq;
s_GetRangeBounds(kDbName, false, 0, 2, kNumSeqs, &first_seq, &last_seq,
true);
s_TestSeqDbIterator(kDbName, false, first_seq, last_seq, nthreads,
eCheckNone);
}
/// Multi volume seqdb, restricted to range of ordinal ids spanning
/// 3 volumes; 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_range_2)
{
s_TestSeqDbIterator_nt_range(2);
}
/// Multi volume seqdb, restricted to range of ordinal ids spanning
/// 3 volumes; 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_range_4)
{
s_TestSeqDbIterator_nt_range(4);
}
/// Multi volume seqdb, restricted to range of ordinal ids spanning
/// 3 volumes; 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_nt_range_20)
{
s_TestSeqDbIterator_nt_range(20);
}
/// Multi-volume protein seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_2)
{
s_TestSeqDbIterator("UnitTest/pataa_multivol", true, 0, 0, 2,
eCheckTotalAndMax);
}
/// Multi-volume protein seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_4)
{
s_TestSeqDbIterator("UnitTest/pataa_multivol", true, 0, 0, 4,
eCheckTotalAndMax);
}
/// Multi-volume protein seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_20)
{
s_TestSeqDbIterator("UnitTest/pataa_multivol", true, 0, 0, 20,
eCheckTotalAndMax);
}
/// Multi volume readdb, restricted to range of ordinal ids spanning
/// 2 volumes;
void s_TestSeqDbIterator_pataa_multi_range(int nthreads)
{
const int kNumSeqs = 1000;
const string kDbName("UnitTest/pataa_multivol");
Uint4 first_seq;
Uint4 last_seq;
s_GetRangeBounds(kDbName, true, 0, 1, kNumSeqs,
&first_seq, &last_seq, true);
s_TestSeqDbIterator(kDbName, true, first_seq, last_seq, nthreads,
eCheckNone);
}
/// Multi volume readdb, restricted to range of ordinal ids spanning
/// 2 volumes; 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_range_2)
{
s_TestSeqDbIterator_pataa_multi_range(2);
}
/// Multi volume readdb, restricted to range of ordinal ids spanning
/// 2 volumes; 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_range_4)
{
s_TestSeqDbIterator_pataa_multi_range(4);
}
/// Multi volume readdb, restricted to range of ordinal ids spanning
/// 2 volumes; 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_multi_range_20)
{
s_TestSeqDbIterator_pataa_multi_range(20);
}
/// Multi-volume masked protein seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_emb_2)
{
s_TestSeqDbIterator("UnitTest/pataa_emb", true, 0, 0, 2, eCheckTotal);
}
/// Multi-volume masked protein seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_emb_4)
{
s_TestSeqDbIterator("UnitTest/pataa_emb", true, 0, 0, 4, eCheckTotal);
}
/// Multi-volume masked protein seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pataa_emb_20)
{
s_TestSeqDbIterator("UnitTest/pataa_emb", true, 0, 0, 20, eCheckTotal);
}
/// Single volume with mask protein seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbaa_2)
{
s_TestSeqDbIterator("pdbaa", true, 0, 0, 2, eCheckTotal);
}
/// Single volume with mask protein seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbaa_4)
{
s_TestSeqDbIterator("pdbaa", true, 0, 0, 4, eCheckTotal);
}
/// Single volume with mask protein seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbaa_20)
{
s_TestSeqDbIterator("pdbaa", true, 0, 0, 20, eCheckTotal);
}
/// Multi-volume with mask seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbnt_2)
{
s_TestSeqDbIterator("pdbnt", false, 0, 0, 2, eCheckTotal);
}
/// Multi-volume with mask seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbnt_4)
{
s_TestSeqDbIterator("pdbnt", false, 0, 0, 4, eCheckTotal);
}
/// Multi-volume with mask seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_pdbnt_20)
{
s_TestSeqDbIterator("pdbnt", false, 0, 0, 20, eCheckTotal);
}
/// Mixed database seqdb, 2 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_mixed_2)
{
s_TestSeqDbIterator("pataa pdbaa", true, 0, 0, 2, eCheckTotal);
}
/// Mixed database seqdb, 4 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_mixed_4)
{
s_TestSeqDbIterator("pataa pdbaa", true, 0, 0, 4, eCheckTotal);
}
/// Mixed database seqdb, 20 threads
BOOST_AUTO_TEST_CASE(testSeqDbIterator_mixed_20)
{
s_TestSeqDbIterator("pataa pdbaa", true, 0, 0, 20, eCheckTotal);
}
#endif
BOOST_AUTO_TEST_SUITE_END()
/*
* ===========================================================================
*
* $Log: seqsrc-cppunit.cpp,v $
* Revision 1.42 2008/10/27 17:00:12 camacho
* Fix include paths to deprecated headers
*
* Revision 1.41 2008/05/29 13:59:34 camacho
* Update after merge of mask_subjects branch
*
* Revision 1.39 2007/11/01 21:35:03 camacho
* Updated for recent changes in BlastSeqSrc
*
* Revision 1.38 2006/05/31 19:00:31 camacho
* + KAPPA_PRINT_DIAGNOSTICS debugging feature
*
* Revision 1.37 2006/02/17 17:35:47 camacho
* Update to reflect new return value of BlastSeqSrcGetName
*
* Revision 1.36 2006/01/09 21:10:17 bealer
* - Use GetTotals() method.
* - Fix some summary information for data directory cases.
*
* Revision 1.35 2005/12/22 21:18:40 bealer
* - Fix remote blast "null" input.
* - SeqSrc now tests for correct totals from iteration.
*
* Revision 1.34 2005/06/09 20:37:06 camacho
* Use new private header blast_objmgr_priv.hpp
*
* Revision 1.33 2005/05/17 22:16:21 dondosha
* Testing of C versions of BlastSeqSrc moved to the C toolkit area
*
* Revision 1.32 2005/05/10 16:09:04 camacho
* Changed *_ENCODING #defines to EBlastEncoding enumeration
*
* Revision 1.31 2005/04/21 15:00:54 dondosha
* Removed unused void* argument in ReaddbBlastSeqSrcInit
*
* Revision 1.30 2005/04/18 14:01:55 camacho
* Updates following BlastSeqSrc reorganization
*
* Revision 1.29 2005/04/13 22:36:46 camacho
* Renamed BlastSeqSrc RetSequence to ReleaseSequence
*
* Revision 1.28 2005/04/06 21:26:37 dondosha
* GapEditBlock structure and redundant fields in BlastHSP have been removed
*
* Revision 1.27 2005/03/08 23:26:18 bealer
* - Use eProtein and eNucleotide.
*
* Revision 1.26 2005/03/04 17:20:45 bealer
* - Command line option support.
*
* Revision 1.25 2005/01/27 02:33:25 dondosha
* Added test for ReaddbBlastSeqSrcAttach with NULL input
*
* Revision 1.24 2004/12/29 15:14:44 camacho
* Fix memory leak
*
* Revision 1.23 2004/12/20 17:03:50 bealer
* - Unit test for SeqDB seqsrc with shared SeqDB objects:
*
* Revision 1.22 2004/12/17 21:49:48 bealer
* - Fix indentations.
*
* Revision 1.21 2004/12/09 15:29:28 dondosha
* Refactored code; renamed constants according to toolkit guideline; added more tests
*
* Revision 1.20 2004/12/06 21:42:37 bealer
* - Re-enable test.
*
* Revision 1.19 2004/12/01 22:30:28 camacho
* Removed unused argument
*
* Revision 1.18 2004/11/23 22:03:33 camacho
* Remove readdb warning message
*
* Revision 1.17 2004/11/17 20:41:27 camacho
* Fix to previous commit
*
* Revision 1.16 2004/11/17 20:29:03 camacho
* Use new BlastSeqSrc initialization function names, added tests for BlastSeqSrc initialization failures
*
* Revision 1.15 2004/10/06 15:12:17 dondosha
* BlastSeqSrcGetName returns const char*
*
* Revision 1.14 2004/10/06 15:02:42 dondosha
* Removed testing of the functionality that is no longer provided
*
* Revision 1.13 2004/09/23 15:48:50 dondosha
* Added test for the BlastSeqSrcGetName method, previously effectively commented out
*
* Revision 1.12 2004/07/21 14:35:27 dondosha
* Added multi-threaded tests with various types of BLAST databases
*
* Revision 1.11 2004/07/19 15:05:00 dondosha
* Renamed multiseq_src to seqsrc_multiseq, seqdb_src to seqsrc_seqdb
*
* Revision 1.10 2004/07/19 14:12:33 dondosha
* Removed test of GetSeqLoc method, because this method has been purged from the interface
*
* Revision 1.9 2004/06/23 14:13:25 dondosha
* Call BlastSeqSrcReleaseSequence instead of BlastSequenceBlkClean when testing SeqDb
*
* Revision 1.8 2004/05/17 15:44:03 dondosha
* Memory leak fixes
*
* Revision 1.7 2004/05/17 14:01:16 dondosha
* Corrected range in testReadDBSeqSrc, due to a fix in seqsrc_readdb.c
*
* Revision 1.6 2004/04/28 19:43:33 dondosha
* Modified database tests to check a local database; enabled testSeqDBSrc
*
* Revision 1.5 2004/04/06 22:21:28 dondosha
* Added checks for all sequence source functions; added test for seqdb source, commented out because some parts are not working yet
*
* Revision 1.4 2004/03/24 22:14:23 dondosha
* Fixed memory leaks
*
* Revision 1.3 2004/03/23 16:10:34 camacho
* Minor changes to CTestObjMgr
*
* Revision 1.2 2004/03/22 20:26:33 dondosha
* Do not use reading sequences from file for testMultiSeqFile; fixed object manager error
*
* Revision 1.1 2004/03/15 20:07:54 dondosha
* Test to check sequence source functionality
*
* Revision 1.7 2004/03/09 18:58:56 dondosha
* Added extension parameters argument to BlastHitSavingParametersNew calls
*
* Revision 1.6 2004/03/01 14:14:50 madden
* Add check for number of identitical letters in final alignment
*
* Revision 1.5 2004/02/27 21:26:56 madden
* Cleanup testBLASTNTraceBack
*
* Revision 1.4 2004/02/27 21:22:25 madden
* Add tblastn test: testTBLASTNTraceBack
*
* Revision 1.3 2004/02/27 20:34:34 madden
* Add setUp and tearDown routines, use tearDown for deallocation
*
* Revision 1.2 2004/02/27 20:14:24 madden
* Add protein-protein test: testBLASTPTraceBack
*
* Revision 1.1 2004/02/27 19:45:35 madden
* Unit test for traceback (mostly BlastHSPListGetTraceback)
*
*
*
* ===========================================================================
*/
|
/*
* QR Code generator library (C++)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
#include <climits>
#include <cstring>
#include <utility>
#include "QrSegment.hpp"
using std::uint8_t;
using std::vector;
namespace qrcodegen {
QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
modeBits(mode) {
numBitsCharCount[0] = cc0;
numBitsCharCount[1] = cc1;
numBitsCharCount[2] = cc2;
}
int QrSegment::Mode::getModeBits() const {
return modeBits;
}
int QrSegment::Mode::numCharCountBits(int ver) const {
if ( 1 <= ver && ver <= 9) return numBitsCharCount[0];
else if (10 <= ver && ver <= 26) return numBitsCharCount[1];
else if (27 <= ver && ver <= 40) return numBitsCharCount[2];
else throw "Version number out of range";
}
const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14);
const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13);
const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16);
const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12);
const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0);
QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) {
if (data.size() > INT_MAX)
throw "Data too long";
BitBuffer bb;
for (uint8_t b : data)
bb.appendBits(b, 8);
return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb));
}
QrSegment QrSegment::makeNumeric(const char *digits) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *digits != '\0'; digits++, charCount++) {
char c = *digits;
if (c < '0' || c > '9')
throw "String contains non-numeric characters";
accumData = accumData * 10 + (c - '0');
accumCount++;
if (accumCount == 3) {
bb.appendBits(accumData, 10);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 or 2 digits remaining
bb.appendBits(accumData, accumCount * 3 + 1);
return QrSegment(Mode::NUMERIC, charCount, std::move(bb));
}
QrSegment QrSegment::makeAlphanumeric(const char *text) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *text != '\0'; text++, charCount++) {
const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text);
if (temp == nullptr)
throw "String contains unencodable characters in alphanumeric mode";
accumData = accumData * 45 + (temp - ALPHANUMERIC_CHARSET);
accumCount++;
if (accumCount == 2) {
bb.appendBits(accumData, 11);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 character remaining
bb.appendBits(accumData, 6);
return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb));
}
vector<QrSegment> QrSegment::makeSegments(const char *text) {
// Select the most efficient segment encoding automatically
vector<QrSegment> result;
if (*text == '\0'); // Leave result empty
else if (isNumeric(text))
result.push_back(makeNumeric(text));
else if (isAlphanumeric(text))
result.push_back(makeAlphanumeric(text));
else {
vector<uint8_t> bytes;
for (; *text != '\0'; text++)
bytes.push_back(static_cast<uint8_t>(*text));
result.push_back(makeBytes(bytes));
}
return result;
}
QrSegment QrSegment::makeEci(long assignVal) {
BitBuffer bb;
if (0 <= assignVal && assignVal < (1 << 7))
bb.appendBits(assignVal, 8);
else if ((1 << 7) <= assignVal && assignVal < (1 << 14)) {
bb.appendBits(2, 2);
bb.appendBits(assignVal, 14);
} else if ((1 << 14) <= assignVal && assignVal < 1000000L) {
bb.appendBits(6, 3);
bb.appendBits(assignVal, 21);
} else
throw "ECI assignment value out of range";
return QrSegment(Mode::ECI, 0, std::move(bb));
}
QrSegment::QrSegment(Mode md, int numCh, const std::vector<bool> &dt) :
mode(md),
numChars(numCh),
data(dt) {
if (numCh < 0)
throw "Invalid value";
}
QrSegment::QrSegment(Mode md, int numCh, std::vector<bool> &&dt) :
mode(md),
numChars(numCh),
data(std::move(dt)) {
if (numCh < 0)
throw "Invalid value";
}
int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) {
if (version < 1 || version > 40)
throw "Version number out of range";
int result = 0;
for (const QrSegment &seg : segs) {
int ccbits = seg.mode.numCharCountBits(version);
// Fail if segment length value doesn't fit in the length field's bit-width
if (seg.numChars >= (1L << ccbits))
return -1;
if (4 + ccbits > INT_MAX - result)
return -1;
result += 4 + ccbits;
if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result))
return -1;
result += static_cast<int>(seg.data.size());
}
return result;
}
bool QrSegment::isAlphanumeric(const char *text) {
for (; *text != '\0'; text++) {
if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr)
return false;
}
return true;
}
bool QrSegment::isNumeric(const char *text) {
for (; *text != '\0'; text++) {
char c = *text;
if (c < '0' || c > '9')
return false;
}
return true;
}
QrSegment::Mode QrSegment::getMode() const {
return mode;
}
int QrSegment::getNumChars() const {
return numChars;
}
const std::vector<bool> &QrSegment::getData() const {
return data;
}
const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
}
|
#include <iostream>
#include <semver.hpp>
int main() {
constexpr semver::version v_default;
std::cout << v_default << std::endl; // 0.1.0
constexpr semver::version v1{1, 4, 3};
constexpr semver::version v2{"1.2.4-alpha.10"};
std::cout << v1 << std::endl; // 1.4.3
std::cout << v2 << std::endl; // 1.2.4-alpha.10
semver::version v_s;
v_s.from_string("1.2.3-rc.1");
std::string s1 = v_s.to_string();
std::cout << s1 << std::endl; // 1.2.3-rc.1
v_s.prerelease_number = 0;
std::string s2 = v_s.to_string();
std::cout << s2 << std::endl; // 1.2.3-rc
return 0;
}
|
/*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef NV_WINDOWPROFILER_GL_INCLUDED
#define NV_WINDOWPROFILER_GL_INCLUDED
#include <nvh/appwindowprofiler.hpp>
#include <nvvk/context_vk.hpp>
#include <nvvk/profiler_vk.hpp>
#include <nvvk/swapchain_vk.hpp>
namespace nvvk {
//////////////////////////////////////////////////////////////////////////
/**
# class nvvk::AppWindowProfilerVK
AppWindowProfilerVK derives from nvh::AppWindowProfiler
and overrides the context and swapbuffer functions.
The nvh class itself provides several utilities and
command line options to run automated benchmarks etc.
To influence the vulkan instance/device creation modify
`m_contextInfo` prior running AppWindowProfiler::run,
which triggers instance, device, window, swapchain creation etc.
The class comes with a nvvk::ProfilerVK instance that references the
AppWindowProfiler::m_profiler's data.
*/
#define NV_PROFILE_VK_SECTION(name, cmd) const nvvk::ProfilerVK::Section _tempTimer(m_profilerVK, name, cmd)
#define NV_PROFILE_VK_SPLIT() m_profilerVK.accumulationSplit()
class AppWindowProfilerVK : public nvh::AppWindowProfiler
{
public:
AppWindowProfilerVK(bool singleThreaded = true)
: nvh::AppWindowProfiler(singleThreaded)
, m_profilerVK(&m_profiler)
{
}
bool m_swapVsync = false;
ContextCreateInfo m_contextInfo{};
Context m_context{};
SwapChain m_swapChain{};
VkSurfaceKHR m_surface{};
ProfilerVK m_profilerVK{};
int run(const std::string& name, int argc, const char** argv, int width, int height)
{
return AppWindowProfiler::run(name, argc, argv, width, height, false);
}
virtual void contextInit() override;
virtual void contextDeinit() override;
virtual void contextSync() override;
virtual const char* contextGetDeviceName() override;
virtual void swapResize(int width, int height) override;
virtual void swapPrepare() override;
virtual void swapBuffers() override;
virtual void swapVsync(bool state) override;
};
} // namespace nvvk
#endif
|
/****************************************************************************
* hipipe library
* Copyright (c) 2018, Iterait a.s.
* Author(s) Filip Matzner, Adam Blazek
*
* This file is distributed under the MIT License.
* See the accompanying file LICENSE.txt for the complete license agreement.
****************************************************************************/
#pragma once
#include <hipipe/build_config.hpp>
#include <hipipe/core/stream/column_t.hpp>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
namespace hipipe::stream {
/// \ingroup Stream
/// \brief Container for multiple columns.
///
/// This is the value type of the stream.
class batch {
private:
/// The stored columns.
std::unordered_map<std::type_index, std::unique_ptr<abstract_column>> columns_;
/// \brief Check whether the given column is present in the stream.
///
/// \tparam Column The column to be retrieved.
/// \throws std::runtime_error If the check fails.
template<typename Column>
void throw_check_contains() const
{
if (!columns_.count(std::type_index{typeid(Column)})) {
throw std::runtime_error{
std::string{"Trying to retrieve column `"} + Column{}.name()
+ "`, but the batch contains no such column."};
}
}
public:
// constructors //
batch() = default;
batch(const batch&) = delete;
batch(batch&&) = default;
// direct access //
/// \brief Retrieve the handle (unique pointer reference) to the given column.
///
/// Example:
/// \code
/// HIPIPE_DEFINE_COLUMN(IntCol, int)
/// stream::batch b;
/// b.insert_or_assign<IntCol>(std::vector<int>{0, 1, 2});
/// b.at<IntCol>()->extract<IntCol>() == std::vector<int>{0, 1, 2};
/// \endcode
///
/// \tparam Column The column whose handle should be retrieved.
/// \throws std::runtime_error If the batch does not contain the given column.
template<typename Column>
std::unique_ptr<abstract_column>& at()
{
throw_check_contains<Column>();
return columns_.at(std::type_index{typeid(Column)});
}
// value extraction //
/// \brief Extract a reference to the stored data of the given column.
///
/// Example:
/// \code
/// HIPIPE_DEFINE_COLUMN(IntCol, int)
/// stream::batch b;
/// b.insert_or_assign<IntCol>(std::vector<int>{0, 1, 2});
/// b.extract<IntCol>() == std::vector<int>{0, 1, 2};
/// \endcode
///
/// \tparam Column The column whose data should be retrieved.
/// \throws std::runtime_error If the batch does not contain the given column.
template<typename Column>
typename Column::data_type& extract()
{
throw_check_contains<Column>();
return columns_.at(std::type_index{typeid(Column)})->extract<Column>();
}
/// Extract a const reference to the stored data of the given column.
///
/// This is the same as previous, but returns a const reference.
template<typename Column>
const typename Column::data_type& extract() const
{
throw_check_contains<Column>();
return columns_.at(std::type_index{typeid(Column)})->extract<Column>();
}
// column insertion/rewrite //
/// \brief Insert a new column to the batch or overwrite an existing one.
///
/// The parameters of this function are forwarded to the constructor of the given column.
///
/// Example:
/// \code
/// HIPIPE_DEFINE_COLUMN(IntCol, int)
/// stream::batch b;
/// b.insert_or_assign<IntCol>(std::vector<int>{0, 1, 2});
/// b.extract<IntCol>() == std::vector<int>{0, 1, 2};
/// \endcode
///
/// \tparam Column The column to be inserted.
/// \param args The parameters that are forwarded to the constructor of the column.
template<typename Column, typename... Args>
void insert_or_assign(Args&&... args)
{
static_assert(std::is_constructible_v<Column, Args&&...>,
"Cannot construct the given column from the provided arguments.");
columns_.insert_or_assign(
std::type_index{typeid(Column)},
std::make_unique<Column>(std::forward<Args>(args)...));
}
/// \brief Insert a raw column handle to the batch or rewrite an existing one.
///
/// This is particularly useful when a raw column handle is retrieved with the at()
/// function and there is no need for creating a new column.
///
/// Example:
/// \code
/// HIPIPE_DEFINE_COLUMN(IntCol, int)
/// stream::batch b1, b2;
/// b1.insert_or_assign<IntCol>(std::vector<int>{0, 1, 2});
/// b2.raw_insert_or_assign<IntCol>(std::move(b1.at<IntCol>())); // b2 now holds the vector
/// \endcode
///
/// \tparam Column The column to be inserted.
/// \param column_ptr The unique pointer to the column.
template<typename Column>
void raw_insert_or_assign(std::unique_ptr<abstract_column> column_ptr)
{
columns_.insert_or_assign(std::type_index{typeid(Column)}, std::move(column_ptr));
}
// column check //
/// \brief Get the number of columns in the batch.
std::size_t size() const
{
return columns_.size();
}
/// \brief Check whether the given column is present in the batch.
///
/// \tparam Column The column to be checked.
template<typename Column>
bool contains() const
{
return columns_.count(std::type_index{typeid(Column)});
}
// column removal //
/// \brief Remove the given column from the batch.
///
/// \tparam Column The column to be removed.
/// \throws std::runtime_error If the columns is not in the batch.
template<typename Column>
void erase()
{
throw_check_contains<Column>();
columns_.erase(std::type_index{typeid(Column)});
}
// batching utilities //
/// \brief Calculate the batch size.
///
/// If the batch contains no columns, returns zero.
///
/// \throws std::runtime_error If all the columns do not have the same size.
std::size_t batch_size() const
{
if (columns_.empty()) return 0;
std::size_t batch_size = columns_.begin()->second->size();
for (auto it = ++columns_.begin(); it != columns_.end(); ++it) {
if (it->second->size() != batch_size) {
throw std::runtime_error{"hipipe: Canot deduce a batch size from a batch "
"with columns of different size (`" + it->second->name() + "`)."};
}
batch_size = it->second->size();
}
return batch_size;
}
/// \brief Steal the given number of examples from all the
/// columns and create a new batch of them.
///
/// The behaviour of this function is equivalent to calling \ref column_base::take()
/// of on all the columns.
///
/// \param n The number of examples to steal.
batch take(std::size_t n)
{
batch new_batch;
for (const auto& [key, col] : columns_) {
new_batch.columns_.insert_or_assign(key, col->take(n));
}
return new_batch;
}
/// \brief Concatenate the columns from two batches.
///
/// If some of the pushed columns is not in this batch, it is inserted as a new column.
///
/// The behaviour of this function is almost equivalent to calling
/// \ref column_base::push_back() of on all the columns.
///
/// \param rhs The batch whose columns will be stolen and appended.
void push_back(batch rhs)
{
for (auto& [key, col] : rhs.columns_) {
if (!columns_.count(key)) {
columns_[key] = std::move(col);
} else {
columns_.at(key)->push_back(std::move(col));
}
}
}
/// \brief Convert all the columns to a Python `dict`.
///
/// The dict is indexed by `column.name()` and the value is `column.to_python()`.
///
/// WARNING: The data are moved out of this objects and using this object further
/// will result in an undefined behavior.
#ifdef HIPIPE_BUILD_PYTHON
boost::python::dict to_python()
{
boost::python::dict res;
for (auto it = columns_.begin(); it != columns_.end(); ++it) {
res[it->second->name()] = it->second->to_python();
}
columns_.clear();
return res;
}
#endif
};
/// Alias to the batch class.
using batch_t = batch;
} // namespace hipipe::stream
|
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of libsoundio, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#include <soundio/soundio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static int usage(char *exe) {
fprintf(stderr, "Usage: %s [options]\n"
"Options:\n"
" [--backend dummy|alsa|pulseaudio|jack|coreaudio|wasapi]\n"
" [--device id]\n"
" [--raw]\n"
" [--name stream_name]\n"
" [--latency seconds]\n"
" [--sample-rate hz]\n"
, exe);
return 1;
}
static void write_sample_s16ne(char *ptr, double sample) {
int16_t *buf = (int16_t *)ptr;
double range = (double)INT16_MAX - (double)INT16_MIN;
double val = sample * range / 2.0;
*buf = val;
}
static void write_sample_s32ne(char *ptr, double sample) {
int32_t *buf = (int32_t *)ptr;
double range = (double)INT32_MAX - (double)INT32_MIN;
double val = sample * range / 2.0;
*buf = val;
}
static void write_sample_float32ne(char *ptr, double sample) {
float *buf = (float *)ptr;
*buf = sample;
}
static void write_sample_float64ne(char *ptr, double sample) {
double *buf = (double *)ptr;
*buf = sample;
}
static void (*write_sample)(char *ptr, double sample);
static const double PI = 3.14159265358979323846264338328;
static double seconds_offset = 0.0;
static volatile bool want_pause = false;
static void write_callback(struct SoundIoOutStream *outstream, int frame_count_min, int frame_count_max) {
double float_sample_rate = outstream->sample_rate;
double seconds_per_frame = 1.0 / float_sample_rate;
struct SoundIoChannelArea *areas;
int err;
int frames_left = frame_count_max;
for (;;) {
int frame_count = frames_left;
if ((err = soundio_outstream_begin_write(outstream, &areas, &frame_count))) {
fprintf(stderr, "unrecoverable stream error: %s\n", soundio_strerror(err));
exit(1);
}
if (!frame_count)
break;
const struct SoundIoChannelLayout *layout = &outstream->layout;
double pitch = 440.0;
double radians_per_second = pitch * 2.0 * PI;
for (int frame = 0; frame < frame_count; frame += 1) {
double sample = sin((seconds_offset + frame * seconds_per_frame) * radians_per_second);
for (int channel = 0; channel < layout->channel_count; channel += 1) {
write_sample(areas[channel].ptr, sample);
areas[channel].ptr += areas[channel].step;
}
}
seconds_offset = fmod(seconds_offset + seconds_per_frame * frame_count, 1.0);
if ((err = soundio_outstream_end_write(outstream))) {
if (err == SoundIoErrorUnderflow)
return;
fprintf(stderr, "unrecoverable stream error: %s\n", soundio_strerror(err));
exit(1);
}
frames_left -= frame_count;
if (frames_left <= 0)
break;
}
soundio_outstream_pause(outstream, want_pause);
}
static void underflow_callback(struct SoundIoOutStream *outstream) {
static int count = 0;
fprintf(stderr, "underflow %d\n", count++);
}
int main(int argc, char **argv) {
char *exe = argv[0];
enum SoundIoBackend backend = SoundIoBackendNone;
char *device_id = NULL;
bool raw = false;
char *stream_name = NULL;
double latency = 0.0;
int sample_rate = 0;
for (int i = 1; i < argc; i += 1) {
char *arg = argv[i];
if (arg[0] == '-' && arg[1] == '-') {
if (strcmp(arg, "--raw") == 0) {
raw = true;
} else {
i += 1;
if (i >= argc) {
return usage(exe);
} else if (strcmp(arg, "--backend") == 0) {
if (strcmp(argv[i], "dummy") == 0) {
backend = SoundIoBackendDummy;
} else if (strcmp(argv[i], "alsa") == 0) {
backend = SoundIoBackendAlsa;
} else if (strcmp(argv[i], "pulseaudio") == 0) {
backend = SoundIoBackendPulseAudio;
} else if (strcmp(argv[i], "jack") == 0) {
backend = SoundIoBackendJack;
} else if (strcmp(argv[i], "coreaudio") == 0) {
backend = SoundIoBackendCoreAudio;
} else if (strcmp(argv[i], "wasapi") == 0) {
backend = SoundIoBackendWasapi;
} else {
fprintf(stderr, "Invalid backend: %s\n", argv[i]);
return 1;
}
} else if (strcmp(arg, "--device") == 0) {
device_id = argv[i];
} else if (strcmp(arg, "--name") == 0) {
stream_name = argv[i];
} else if (strcmp(arg, "--latency") == 0) {
latency = atof(argv[i]);
} else if (strcmp(arg, "--sample-rate") == 0) {
sample_rate = atoi(argv[i]);
} else {
return usage(exe);
}
}
} else {
return usage(exe);
}
}
struct SoundIo *soundio = soundio_create();
if (!soundio) {
fprintf(stderr, "out of memory\n");
return 1;
}
int err = (backend == SoundIoBackendNone) ?
soundio_connect(soundio) : soundio_connect_backend(soundio, backend);
if (err) {
fprintf(stderr, "Unable to connect to backend: %s\n", soundio_strerror(err));
return 1;
}
fprintf(stderr, "Backend: %s\n", soundio_backend_name(soundio->current_backend));
soundio_flush_events(soundio);
int selected_device_index = -1;
if (device_id) {
int device_count = soundio_output_device_count(soundio);
for (int i = 0; i < device_count; i += 1) {
struct SoundIoDevice *device = soundio_get_output_device(soundio, i);
bool select_this_one = strcmp(device->id, device_id) == 0 && device->is_raw == raw;
soundio_device_unref(device);
if (select_this_one) {
selected_device_index = i;
break;
}
}
} else {
selected_device_index = soundio_default_output_device_index(soundio);
}
if (selected_device_index < 0) {
fprintf(stderr, "Output device not found\n");
return 1;
}
struct SoundIoDevice *device = soundio_get_output_device(soundio, selected_device_index);
if (!device) {
fprintf(stderr, "out of memory\n");
return 1;
}
fprintf(stderr, "Output device: %s\n", device->name);
if (device->probe_error) {
fprintf(stderr, "Cannot probe device: %s\n", soundio_strerror(device->probe_error));
return 1;
}
struct SoundIoOutStream *outstream = soundio_outstream_create(device);
if (!outstream) {
fprintf(stderr, "out of memory\n");
return 1;
}
outstream->write_callback = write_callback;
outstream->underflow_callback = underflow_callback;
outstream->name = stream_name;
outstream->software_latency = latency;
outstream->sample_rate = sample_rate;
if (soundio_device_supports_format(device, SoundIoFormatFloat32NE)) {
outstream->format = SoundIoFormatFloat32NE;
write_sample = write_sample_float32ne;
} else if (soundio_device_supports_format(device, SoundIoFormatFloat64NE)) {
outstream->format = SoundIoFormatFloat64NE;
write_sample = write_sample_float64ne;
} else if (soundio_device_supports_format(device, SoundIoFormatS32NE)) {
outstream->format = SoundIoFormatS32NE;
write_sample = write_sample_s32ne;
} else if (soundio_device_supports_format(device, SoundIoFormatS16NE)) {
outstream->format = SoundIoFormatS16NE;
write_sample = write_sample_s16ne;
} else {
fprintf(stderr, "No suitable device format available.\n");
return 1;
}
if ((err = soundio_outstream_open(outstream))) {
fprintf(stderr, "unable to open device: %s", soundio_strerror(err));
return 1;
}
fprintf(stderr, "Software latency: %f\n", outstream->software_latency);
fprintf(stderr,
"'p\\n' - pause\n"
"'u\\n' - unpause\n"
"'P\\n' - pause from within callback\n"
"'c\\n' - clear buffer\n"
"'q\\n' - quit\n");
if (outstream->layout_error)
fprintf(stderr, "unable to set channel layout: %s\n", soundio_strerror(outstream->layout_error));
if ((err = soundio_outstream_start(outstream))) {
fprintf(stderr, "unable to start device: %s\n", soundio_strerror(err));
return 1;
}
for (;;) {
soundio_flush_events(soundio);
int c = getc(stdin);
if (c == 'p') {
fprintf(stderr, "pausing result: %s\n",
soundio_strerror(soundio_outstream_pause(outstream, true)));
} else if (c == 'P') {
want_pause = true;
} else if (c == 'u') {
want_pause = false;
fprintf(stderr, "unpausing result: %s\n",
soundio_strerror(soundio_outstream_pause(outstream, false)));
} else if (c == 'c') {
fprintf(stderr, "clear buffer result: %s\n",
soundio_strerror(soundio_outstream_clear_buffer(outstream)));
} else if (c == 'q') {
break;
} else if (c == '\r' || c == '\n') {
// ignore
} else {
fprintf(stderr, "Unrecognized command: %c\n", c);
}
}
soundio_outstream_destroy(outstream);
soundio_device_unref(device);
soundio_destroy(soundio);
return 0;
}
|
#include "languages.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]){
if(argc <= 2){
return 1; exit(EXIT_FAILURE);
}
double comp = 0;
std::string name;
languages similar;
for (int i = 1; i < argc; i++){
std::ifstream my_file(argv[i]);
if (my_file.good()){continue;}
else{return 1; exit(EXIT_FAILURE);}
}
for (int i = 1; i < argc - 2; i++){
//language to be tested
languages lang = languages(argv[i]);
lang.setName(argv[i]);
std::vector<int> langtf = lang.getTrigramFreq();
//test language
languages test = languages(argv[argc-1]);
std::vector<int> testtf = test.getTrigramFreq();
double sim = similar.setSimilarity(langtf, testtf);
//seeing which lang is most similar
if(sim > comp){
comp = sim;
name = lang.getName();
}
}
std::cout << name << std::endl;
return 0;
}
|
int find(int i) { return (p[i] == i) ? i : (p[i] = find(p[i])); }
int join(int i, int j) {
int a = find(i), b = find(j);
if (a != b) {
if (rank[a] > rank[b]) p[b] = a;
else { p[a] = b;
if (rank[a] == rank[b]) rank[b]++; }
}
}
|
/*********************************************************************
* Filename: sha256.c
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Implementation of the SHA-256 hashing algorithm.
SHA-256 is one of the three algorithms in the SHA2
specification. The others, SHA-384 and SHA-512, are not
offered in this implementation.
Algorithm specification can be found here:
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
This implementation uses little endian byte order.
Ported to Arduino and objectified by Diego Zuccato <ndk.clanbo@gmail.com>
*********************************************************************/
/*************************** HEADER FILES ***************************/
//#include <stdlib.h>
//#include <memory.h>
#include <string.h>
#include "sha256.h"
/****************************** MACROS ******************************/
#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
/**************************** VARIABLES *****************************/
static const WORD k[64] = {
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
};
/*********************** ACTUAL IMPLEMENTATION ***********************/
Sha256::Sha256() {
this->datalen = 0;
this->bitlen = 0;
this->state[0] = 0x6a09e667;
this->state[1] = 0xbb67ae85;
this->state[2] = 0x3c6ef372;
this->state[3] = 0xa54ff53a;
this->state[4] = 0x510e527f;
this->state[5] = 0x9b05688c;
this->state[6] = 0x1f83d9ab;
this->state[7] = 0x5be0cd19;
}
void Sha256::update(const BYTE data[], size_t len) {
WORD i;
for (i = 0; i < len; ++i) {
this->data[this->datalen] = data[i];
this->datalen++;
if (this->datalen == 64) {
this->transform();
this->bitlen += 512;
this->datalen = 0;
}
}
}
void Sha256::final(BYTE hash[]) {
WORD i;
i = this->datalen;
// Pad whatever data is left in the buffer.
if (this->datalen < 56) {
this->data[i++] = 0x80;
while (i < 56) //@@@ optimize with memset
this->data[i++] = 0x00;
} else {
this->data[i++] = 0x80;
while (i < 64) //@@@ optimize with memset
this->data[i++] = 0x00;
this->transform();
memset(this->data, 0, 56);
}
// Append to the padding the total message's length in bits and transform.
this->bitlen += this->datalen * 8;
this->data[63] = this->bitlen;
this->data[62] = this->bitlen >> 8;
this->data[61] = this->bitlen >> 16;
this->data[60] = this->bitlen >> 24;
this->data[59] = this->bitlen >> 32;
this->data[58] = this->bitlen >> 40;
this->data[57] = this->bitlen >> 48;
this->data[56] = this->bitlen >> 56;
this->transform();
// Since this implementation uses little endian byte ordering and SHA uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i) {
hash[i] = (this->state[0] >> (24 - i * 8)) & 0x000000ff;
hash[i + 4] = (this->state[1] >> (24 - i * 8)) & 0x000000ff;
hash[i + 8] = (this->state[2] >> (24 - i * 8)) & 0x000000ff;
hash[i + 12] = (this->state[3] >> (24 - i * 8)) & 0x000000ff;
hash[i + 16] = (this->state[4] >> (24 - i * 8)) & 0x000000ff;
hash[i + 20] = (this->state[5] >> (24 - i * 8)) & 0x000000ff;
hash[i + 24] = (this->state[6] >> (24 - i * 8)) & 0x000000ff;
hash[i + 28] = (this->state[7] >> (24 - i * 8)) & 0x000000ff;
}
}
void Sha256::transform() {
WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
for (i = 0, j = 0; i < 16; ++i, j += 4)
m[i] = (this->data[j] << 24) | (this->data[j + 1] << 16) | (this->data[j + 2] << 8) | (this->data[j + 3]);
for ( ; i < 64; ++i)
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
a = this->state[0];
b = this->state[1];
c = this->state[2];
d = this->state[3];
e = this->state[4];
f = this->state[5];
g = this->state[6];
h = this->state[7];
for (i = 0; i < 64; ++i) {
t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
t2 = EP0(a) + MAJ(a,b,c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
this->state[0] += a;
this->state[1] += b;
this->state[2] += c;
this->state[3] += d;
this->state[4] += e;
this->state[5] += f;
this->state[6] += g;
this->state[7] += h;
}
|
#include "json_array2.h"
namespace bbai::jsonex {
//--------------------------------------------------------------------------------------------------
// to_string
//--------------------------------------------------------------------------------------------------
std::string json_array2::to_string() const noexcept {
std::string res;
res += '[';
for (size_t i=0; i<values_.size(); ++i) {
res += values_[i]->to_string();
if (i < values_.size()-1) {
res += ",";
}
}
res += ']';
return res;
}
} // namespace bbai::jsonex
|
/*
* SensorProcessorBase.hpp
*
* Created on: Jun 6, 2014
* Author: Péter Fankhauser, Hannes Keller
* Institute: ETH Zurich, ANYbotics
*/
#pragma once
// ROS
#include <ros/ros.h>
#include <tf/transform_listener.h>
// PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
// Eigen
#include <Eigen/Core>
// Kindr
#include <kindr/Core>
// STL
#include <unordered_map>
#include <string>
#include <memory>
namespace elevation_mapping {
/*!
* Generic Sensor processor base class. Provides functionalities
* common to all sensors and defines the interface for specialized
* sensor processor classes.
* Cleans the point cloud, transforms it to a desired frame, and
* computes the measurement variances based on a sensor model in
* the desired frame.
*/
class SensorProcessorBase
{
public:
/*!
* Constructor.
* @param nodeHandle the ROS node handle.
* @param transformListener the ROS transform listener.
*/
SensorProcessorBase(ros::NodeHandle& nodeHandle, tf::TransformListener& transformListener);
/*!
* Destructor.
*/
virtual ~SensorProcessorBase();
/*!
* Processes the point cloud.
* @param[in] pointCloudInput the input point cloud.
* @param[in] targetFrame the frame to which the point cloud should be transformed. // TODO Update.
* @param[out] pointCloudOutput the processed point cloud.
* @param[out] variances the measurement variances expressed in the target frame.
* @return true if successful.
*/
bool process(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloudInput,
const Eigen::Matrix<double, 6, 6>& robotPoseCovariance,
const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloudOutput, Eigen::VectorXf& variances);
typedef std::unique_ptr<SensorProcessorBase> Ptr;
friend class ElevationMapping;
protected:
/*!
* Reads and verifies the parameters.
* @return true if successful.
*/
virtual bool readParameters();
/*!
* Filters the point cloud regardless of the sensor type. Removes NaN values.
* Optionally, applies voxelGridFilter to reduce number of points in
* the point cloud.
* @param pointCloud the point cloud to clean.
* @return true if successful.
*/
bool filterPointCloud(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud);
/*!
* Sensor specific point cloud cleaning.
* @param pointCloud the point cloud to clean.
* @return true if successful.
*/
virtual bool filterPointCloudSensorType(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud);
bool filterPointCloudLegBox(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud);
/*!
* Computes the elevation map height variances for each point in a point cloud with the
* sensor model and the robot pose covariance.
* @param[in] pointCloud the point cloud for which the variances are computed.
* @param[in] robotPoseCovariance the robot pose covariance matrix.
* @param[out] variances the elevation map height variances.
* @return true if successful.
*/
virtual bool computeVariances(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloud,
const Eigen::Matrix<double, 6, 6>& robotPoseCovariance, Eigen::VectorXf& variances) = 0;
/*!
* Update the transformations for a given time stamp.
* @param timeStamp the time stamp for the transformation.
* @return true if successful.
*/
bool updateTransformations(const ros::Time& timeStamp);
/*!
* Transforms the point cloud the a target frame.
* @param[in] pointCloud the point cloud to be transformed.
* @param[out] pointCloudTransformed the resulting point cloud after transformation.
* @param[in] targetFrame the desired target frame.
* @return true if successful.
*/
bool transformPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloud,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloudTransformed,
const std::string& targetFrame);
/*!
* Removes points with z-coordinate above a limit in map frame.
* @param[in/out] pointCloud the point cloud to be cropped.
*/
void removePointsOutsideLimits(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr reference,
std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr>& pointClouds);
//! ROS nodehandle.
ros::NodeHandle& nodeHandle_;
//! TF transform listener.
tf::TransformListener& transformListener_;
//! The timeout duration for the lookup of the transformation between sensor frame and target frame.
ros::Duration transformListenerTimeout_;
//! Rotation from Base to Sensor frame (C_SB)
kindr::RotationMatrixD rotationBaseToSensor_;
//! Translation from Base to Sensor in Base frame (B_r_BS)
kindr::Position3D translationBaseToSensorInBaseFrame_;
//! Rotation from (elevation) Map to Base frame (C_BM)
kindr::RotationMatrixD rotationMapToBase_;
//! Translation from Map to Base in Map frame (M_r_MB)
kindr::Position3D translationMapToBaseInMapFrame_;
//! Transformation from Sensor to Map frame
Eigen::Affine3d transformationSensorToMap_;
//! TF frame id of the map.
std::string mapFrameId_;
//! TF frame id of the robot base.
std::string robotBaseFrameId_;
//! TF frame id of the range sensor for the point clouds.
std::string sensorFrameId_;
//! Ignore points above this height in map frame.
double ignorePointsUpperThreshold_;
//! Ignore points below this height in map frame.
double ignorePointsLowerThreshold_;
//! Sensor parameters.
std::unordered_map<std::string, double> sensorParameters_;
//! Use VoxelGrid filter to cleanup pointcloud if true.
bool applyVoxelGridFilter_;
//! Use LegBox filter to cleanup pointcloud if true.
bool applyLegBoxFilter_;
};
} /* namespace elevation_mapping */
|
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Talon_King_Ikiss
SD%Complete: 80
SDComment: Heroic supported. Some details missing, but most are spell related.
SDCategory: Auchindoun, Sethekk Halls
EndScriptData */
#include "precompiled.h"
#include "sethekk_halls.h"
#define SAY_INTRO -1556007
#define SAY_AGGRO_1 -1556008
#define SAY_AGGRO_2 -1556009
#define SAY_AGGRO_3 -1556010
#define SAY_SLAY_1 -1556011
#define SAY_SLAY_2 -1556012
#define SAY_DEATH -1556013
#define EMOTE_ARCANE_EXP -1556015
#define SPELL_BLINK 38194
#define SPELL_BLINK_TELEPORT 38203
#define SPELL_MANA_SHIELD 38151
#define SPELL_ARCANE_BUBBLE 9438
#define H_SPELL_SLOW 35032
#define SPELL_POLYMORPH 38245
#define H_SPELL_POLYMORPH 43309
#define SPELL_ARCANE_VOLLEY 35059
#define H_SPELL_ARCANE_VOLLEY 40424
#define SPELL_ARCANE_EXPLOSION 38197
#define H_SPELL_ARCANE_EXPLOSION 40425
struct MANGOS_DLL_DECL boss_talon_king_ikissAI : public ScriptedAI
{
boss_talon_king_ikissAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty();
Reset();
}
ScriptedInstance* m_pInstance;
bool m_bIsRegularMode;
uint32 ArcaneVolley_Timer;
uint32 Sheep_Timer;
uint32 Blink_Timer;
uint32 Slow_Timer;
bool ManaShield;
bool Blink;
bool Intro;
void Reset()
{
ArcaneVolley_Timer = 5000;
Sheep_Timer = 8000;
Blink_Timer = 35000;
Slow_Timer = urand(15000, 30000);
Blink = false;
Intro = false;
ManaShield = false;
}
void MoveInLineOfSight(Unit *who)
{
if (!m_creature->getVictim() && who->isTargetableForAttack() && (m_creature->IsHostileTo(who)) && who->isInAccessablePlaceFor(m_creature))
{
if (!Intro && m_creature->IsWithinDistInMap(who, 100))
{
Intro = true;
DoScriptText(SAY_INTRO, m_creature);
}
if (!m_creature->canFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
return;
float attackRadius = m_creature->GetAttackDistance(who);
if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who))
{
who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
AttackStart(who);
}
}
}
void Aggro(Unit *who)
{
switch(urand(0, 2))
{
case 0: DoScriptText(SAY_AGGRO_1, m_creature); break;
case 1: DoScriptText(SAY_AGGRO_2, m_creature); break;
case 2: DoScriptText(SAY_AGGRO_3, m_creature); break;
}
}
void JustDied(Unit* Killer)
{
DoScriptText(SAY_DEATH, m_creature);
if (m_pInstance)
m_pInstance->SetData(DATA_IKISSDOOREVENT, DONE);
}
void KilledUnit(Unit* victim)
{
DoScriptText(urand(0, 1) ? SAY_SLAY_1 : SAY_SLAY_2, m_creature);
}
void UpdateAI(const uint32 diff)
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (Blink)
{
DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_ARCANE_EXPLOSION : H_SPELL_ARCANE_EXPLOSION);
m_creature->CastSpell(m_creature,SPELL_ARCANE_BUBBLE,true);
Blink = false;
}
if (ArcaneVolley_Timer < diff)
{
DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_ARCANE_VOLLEY : H_SPELL_ARCANE_VOLLEY);
ArcaneVolley_Timer = urand(7000, 12000);
}else ArcaneVolley_Timer -= diff;
if (Sheep_Timer < diff)
{
//second top aggro target in normal, random target in heroic correct?
Unit *target = NULL;
if (m_bIsRegularMode ? target = SelectUnit(SELECT_TARGET_TOPAGGRO, 1) : target = SelectUnit(SELECT_TARGET_RANDOM, 0))
DoCastSpellIfCan(target, m_bIsRegularMode ? SPELL_POLYMORPH : H_SPELL_POLYMORPH);
Sheep_Timer = urand(15000, 17500);
}else Sheep_Timer -= diff;
//may not be correct time to cast
if (!ManaShield && m_creature->GetHealthPercent() < 20.0f)
{
DoCastSpellIfCan(m_creature,SPELL_MANA_SHIELD);
ManaShield = true;
}
if (!m_bIsRegularMode)
{
if (Slow_Timer < diff)
{
DoCastSpellIfCan(m_creature,H_SPELL_SLOW);
Slow_Timer = urand(15000, 40000);
}else Slow_Timer -= diff;
}
if (Blink_Timer < diff)
{
DoScriptText(EMOTE_ARCANE_EXP, m_creature);
if (Unit *target = SelectUnit(SELECT_TARGET_RANDOM,0))
{
if (m_creature->IsNonMeleeSpellCasted(false))
m_creature->InterruptNonMeleeSpells(false);
//Spell doesn't work, but we use for visual effect at least
DoCastSpellIfCan(target,SPELL_BLINK);
float X = target->GetPositionX();
float Y = target->GetPositionY();
float Z = target->GetPositionZ();
m_creature->GetMap()->CreatureRelocation(m_creature,X,Y,Z,0.0f);
m_creature->SendMonsterMove(X, Y, Z, SPLINETYPE_NORMAL, SPLINEFLAG_WALKMODE, 1);
DoCastSpellIfCan(target,SPELL_BLINK_TELEPORT);
Blink = true;
}
Blink_Timer = urand(35000, 40000);
}else Blink_Timer -= diff;
if (!Blink)
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_talon_king_ikiss(Creature* pCreature)
{
return new boss_talon_king_ikissAI(pCreature);
}
void AddSC_boss_talon_king_ikiss()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_talon_king_ikiss";
newscript->GetAI = &GetAI_boss_talon_king_ikiss;
newscript->RegisterSelf();
}
|
#include <algorithm>
#include "simulation/ElementCommon.h"
static void initDeltaPos();
static void changeType(ELEMENT_CHANGETYPE_FUNC_ARGS);
void Element::Element_ETRD()
{
Identifier = "DEFAULT_PT_ETRD";
Name = "ETRD";
Colour = PIXPACK(0x404040);
MenuVisible = 1;
MenuSection = SC_ELEC;
Enabled = 1;
Advection = 0.0f;
AirDrag = 0.00f * CFDS;
AirLoss = 0.90f;
Loss = 0.00f;
Collision = 0.0f;
Gravity = 0.0f;
Diffusion = 0.00f;
HotAir = 0.000f * CFDS;
Falldown = 0;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 1;
Weight = 100;
HeatConduct = 251;
Description = "Electrode. Creates a surface that allows Plasma arcs. (Use sparingly)";
Properties = TYPE_SOLID|PROP_CONDUCTS|PROP_LIFE_DEC;
LowPressure = IPL;
LowPressureTransition = NT;
HighPressure = IPH;
HighPressureTransition = NT;
LowTemperature = ITL;
LowTemperatureTransition = NT;
HighTemperature = ITH;
HighTemperatureTransition = NT;
ChangeType = &changeType;
initDeltaPos();
}
static void changeType(ELEMENT_CHANGETYPE_FUNC_ARGS)
{
if (sim->etrd_count_valid)
{
if (from == PT_ETRD && sim->parts[i].life == 0)
sim->etrd_life0_count--;
if (to == PT_ETRD && sim->parts[i].life == 0)
sim->etrd_life0_count++;
}
}
class ETRD_deltaWithLength
{
public:
ETRD_deltaWithLength(ui::Point a, int b):
d(a),
length(b)
{
}
ui::Point d;
int length;
};
const int maxLength = 12;
std::vector<ETRD_deltaWithLength> deltaPos;
static void initDeltaPos()
{
deltaPos.clear();
for (int ry = -maxLength; ry <= maxLength; ry++)
for (int rx = -maxLength; rx <= maxLength; rx++)
{
ui::Point d(rx, ry);
if (std::abs(d.X) + std::abs(d.Y) <= maxLength)
deltaPos.push_back(ETRD_deltaWithLength(d, std::abs(d.X) + std::abs(d.Y)));
}
std::stable_sort(deltaPos.begin(), deltaPos.end(), [](const ETRD_deltaWithLength &a, const ETRD_deltaWithLength &b) {
return a.length < b.length;
});
}
int Element_ETRD_nearestSparkablePart(Simulation *sim, int targetId)
{
if (!sim->elementCount[PT_ETRD])
return -1;
if (sim->etrd_count_valid && sim->etrd_life0_count <= 0)
return -1;
Particle *parts = sim->parts;
int foundDistance = XRES + YRES;
int foundI = -1;
ui::Point targetPos = ui::Point(int(parts[targetId].x), int(parts[targetId].y));
if (sim->etrd_count_valid)
{
// countLife0 doesn't need recalculating, so just focus on finding the nearest particle
// If the simulation contains lots of particles, check near the target position first since going through all particles will be slow.
// Threshold = number of positions checked, *2 because it's likely to access memory all over the place (less cache friendly) and there's extra logic needed
// TODO: probably not optimal if excessive stacking is used
if (sim->parts_lastActiveIndex > (int)deltaPos.size()*2)
{
for (std::vector<ETRD_deltaWithLength>::iterator iter = deltaPos.begin(), end = deltaPos.end(); iter != end; ++iter)
{
ETRD_deltaWithLength delta = (*iter);
ui::Point checkPos = targetPos + delta.d;
int checkDistance = delta.length;
if (foundDistance < checkDistance)
{
// deltaPos is sorted in order of ascending length, so foundDistance < checkDistance means all later items are further away.
break;
}
if (sim->InBounds(checkPos.X, checkPos.Y) && checkDistance <= foundDistance)
{
int r = sim->pmap[checkPos.Y][checkPos.X];
if (r && TYP(r) == PT_ETRD && !parts[ID(r)].life && ID(r) != targetId && checkDistance < foundDistance)
{
foundDistance = checkDistance;
foundI = ID(r);
}
}
}
}
// If neighbor search didn't find a suitable particle, search all particles
if (foundI < 0)
{
for (int i = 0; i <= sim->parts_lastActiveIndex; i++)
{
if (parts[i].type == PT_ETRD && !parts[i].life)
{
ui::Point checkPos = ui::Point(int(parts[i].x)-targetPos.X, int(parts[i].y)-targetPos.Y);
int checkDistance = std::abs(checkPos.X) + std::abs(checkPos.Y);
if (checkDistance < foundDistance && i != targetId)
{
foundDistance = checkDistance;
foundI = i;
}
}
}
}
}
else
{
// Recalculate countLife0, and search for the closest suitable particle
int countLife0 = 0;
for (int i = 0; i <= sim->parts_lastActiveIndex; i++)
{
if (parts[i].type == PT_ETRD && !parts[i].life)
{
countLife0++;
ui::Point checkPos = ui::Point(int(parts[i].x)-targetPos.X, int(parts[i].y)-targetPos.Y);
int checkDistance = std::abs(checkPos.X) + std::abs(checkPos.Y);
if (checkDistance < foundDistance && i != targetId)
{
foundDistance = checkDistance;
foundI = i;
}
}
}
sim->etrd_life0_count = countLife0;
sim->etrd_count_valid = true;
}
return foundI;
}
|
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::ifstream;
using std::istringstream;
using std::string;
using std::vector;
enum class State {OK,BAD };
vector<vector<State>> ReadBoard(string file){
ifstream boardFile(file);
}
void testing(int option) {
switch (option)
{
case 0:
// Test to write out to terminal
cout << "Hello world!" << endl;
break;
case 1:
// Test to read a file
break;
case 2:
// Test to read a line
break;
case 3:
// Test to parse a line
break;
}
}
int main() { testing(0); }
|
/**
@file escconf_sequence_sequence.cpp
@brief Configure BLHelo littlebee 30A brushless motor control ESC.
@author Pekka Lehtikoski
@version 1.0
@date 2.8.2020
Copyright 2020 Pekka Lehtikoski. This file is part of the eobjects project and shall only be used,
modified, and distributed under the terms of the project licensing. By continuing to use, modify,
or distribute this file you indicate that you have read the license and understand and accept
it fully.
****************************************************************************************************
*/
#include "buster.h"
/**
****************************************************************************************************
@brief Constructor.
Start the sequence as a new thread.
@return None.
****************************************************************************************************
*/
EscConfSequence::EscConfSequence() : AbstractSequence()
{
m_set_min_throttle = 0;
m_set_min_throttle_state_bits = 0;
m_min_throttle_pressed = OS_FALSE;
m_min_throttle_timer = 0;
m_set_max_throttle = 0;
m_set_max_throttle_state_bits = 0;
m_max_throttle_pressed = OS_FALSE;
m_max_throttle_timer = 0;
}
/**
****************************************************************************************************
@brief Virtual destructor.
Join worker thread to this thread and clean up.
@return None.
****************************************************************************************************
*/
EscConfSequence::~EscConfSequence()
{
}
void EscConfSequence::start(AbstractApplication *app)
{
if (m_started) return;
m_set_min_throttle = 0;
m_set_min_throttle_state_bits = 0;
m_min_throttle_pressed = OS_FALSE;
m_set_max_throttle = 0;
m_set_max_throttle_state_bits = 0;
m_max_throttle_pressed = OS_FALSE;
AbstractSequence::start(app);
}
void EscConfSequence::stop()
{
if (!m_started) return;
AbstractSequence::stop();
}
/**
****************************************************************************************************
@brief Run the sequence.
If this is to run in both single thread and multithread mode, implement as state machine
without sleeps.
@return None.
****************************************************************************************************
*/
void EscConfSequence::run(os_timer *ti)
{
os_long value;
os_char state_bits;
value = ioc_get_ext(&buster.imp.set_min_throttle, &state_bits, IOC_SIGNAL_DEFAULT);
if (value != m_set_min_throttle || state_bits != m_set_min_throttle_state_bits) {
m_set_min_throttle_state_bits = state_bits;
m_set_min_throttle = value;
if (value && !m_min_throttle_pressed && (state_bits & OSAL_STATE_CONNECTED)) {
os_get_timer(&m_min_throttle_timer);
m_min_throttle_pressed = OS_TRUE;
// ioc_set_double(&buster.exp.throttle, -100);
pin_set_scaled(&pins.pwm.throttle, -100, PIN_FORWARD_TO_IOCOM);
}
}
if (m_min_throttle_pressed) {
if (os_has_elapsed(&m_min_throttle_timer, 2000)) {
ioc_set(&buster.exp.min_throttle, OS_FALSE);
m_min_throttle_pressed = OS_FALSE;
}
}
value = ioc_get_ext(&buster.imp.set_max_throttle, &state_bits, IOC_SIGNAL_DEFAULT);
if (value != m_set_max_throttle || state_bits != m_set_max_throttle_state_bits) {
m_set_max_throttle_state_bits = state_bits;
m_set_max_throttle = value;
if (value && !m_max_throttle_pressed && (state_bits & OSAL_STATE_CONNECTED)) {
os_get_timer(&m_max_throttle_timer);
m_max_throttle_pressed = OS_TRUE;
// ioc_set_double(&buster.exp.throttle, 100);
pin_set_scaled(&pins.pwm.throttle, 100, PIN_FORWARD_TO_IOCOM);
}
}
if (m_max_throttle_pressed) {
if (os_has_elapsed(&m_max_throttle_timer, 2000)) {
ioc_set(&buster.exp.max_throttle, OS_FALSE);
m_max_throttle_pressed = OS_FALSE;
}
}
}
/**
****************************************************************************************************
@brief The thread function.
This function should be overloaded by actual sequence.
@return None.
****************************************************************************************************
*/
void EscConfSequence::task()
{
os_timer ti;
while (!m_stop_thread && osal_go())
{
// static long ulledoo; if (++ulledoo > 10009) {osal_debug_error("ulledoo blink\n"); ulledoo = 0;}
os_get_timer(&ti);
run(&ti);
osal_sleep(50);
}
}
|
#include "newprojectdialog.h"
#include "ui_newprojectdialog.h"
#include <QtWidgets>
NewProjectDialog::NewProjectDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::NewProjectDialog)
{
ui->setupUi(this);
}
NewProjectDialog::~NewProjectDialog()
{
delete ui;
}
void NewProjectDialog::on_pushButton_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, "Select Directory", ".");
if (dir.isEmpty())
{
return;
}
ui->pathField->setText(dir);
}
int NewProjectDialog::GetWidth()
{
return ui->widthField->value();
}
int NewProjectDialog::GetHeight()
{
return ui->heightField->value();
}
int NewProjectDialog::GetFps()
{
return ui->fpsField->value();
}
QString NewProjectDialog::GetPath()
{
return ui->pathField->text();
}
void NewProjectDialog::on_okButton_clicked()
{
QDir dir(ui->pathField->text());
if (!dir.exists())
{
QMessageBox::information(this, "Error", "Please select a folder");
return;
}
emit accept();
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Runtime.Remoting.RemotingServices
#include "System/Runtime/Remoting/RemotingServices.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Runtime::Remoting::RemotingServices::CACD);
DEFINE_IL2CPP_ARG_TYPE(::System::Runtime::Remoting::RemotingServices::CACD*, "System.Runtime.Remoting", "RemotingServices/CACD");
// Type namespace: System.Runtime.Remoting
namespace System::Runtime::Remoting {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: System.Runtime.Remoting.RemotingServices/System.Runtime.Remoting.CACD
// [TokenAttribute] Offset: FFFFFFFF
class RemotingServices::CACD : public ::Il2CppObject {
public:
public:
// public System.Object d
// Size: 0x8
// Offset: 0x10
::Il2CppObject* d;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// public System.Object c
// Size: 0x8
// Offset: 0x18
::Il2CppObject* c;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
public:
// Get instance field reference: public System.Object d
[[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn_d();
// Get instance field reference: public System.Object c
[[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn_c();
// public System.Void .ctor()
// Offset: 0xE580EC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RemotingServices::CACD* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::Remoting::RemotingServices::CACD::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RemotingServices::CACD*, creationType>()));
}
}; // System.Runtime.Remoting.RemotingServices/System.Runtime.Remoting.CACD
#pragma pack(pop)
static check_size<sizeof(RemotingServices::CACD), 24 + sizeof(::Il2CppObject*)> __System_Runtime_Remoting_RemotingServices_CACDSizeCheck;
static_assert(sizeof(RemotingServices::CACD) == 0x20);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Runtime::Remoting::RemotingServices::CACD::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
/*
* Copyright 2017-2019 Baidu 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.
*/
#include "utils/JsonReader.h"
#include "utils/YamlReader.h"
#include "openrasp.h"
#include "openrasp_ini.h"
extern "C"
{
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
}
#include "openrasp_log.h"
#include "openrasp_v8.h"
#include "openrasp_hook.h"
#include "openrasp_inject.h"
#include "openrasp_security_policy.h"
#include "openrasp_output_detect.h"
#ifdef HAVE_FSWATCH
#include "openrasp_fswatch.h"
#endif
#include <new>
#include "agent/shared_config_manager.h"
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
#include "agent/openrasp_agent_manager.h"
#endif
using openrasp::ConfigHolder;
ZEND_DECLARE_MODULE_GLOBALS(openrasp);
bool is_initialized = false;
bool remote_active = false;
static bool make_openrasp_root_dir();
static bool current_sapi_supported();
static std::string get_config_abs_path(ConfigHolder::FromType type);
static bool update_config(openrasp::ConfigHolder *config, ConfigHolder::FromType type = ConfigHolder::FromType::kYaml);
PHP_INI_BEGIN()
PHP_INI_ENTRY1("openrasp.root_dir", "", PHP_INI_SYSTEM, OnUpdateOpenraspCString, &openrasp_ini.root_dir)
#ifdef HAVE_GETTEXT
PHP_INI_ENTRY1("openrasp.locale", "", PHP_INI_SYSTEM, OnUpdateOpenraspCString, &openrasp_ini.locale)
#endif
PHP_INI_ENTRY1("openrasp.backend_url", "", PHP_INI_SYSTEM, OnUpdateOpenraspCString, &openrasp_ini.backend_url)
PHP_INI_ENTRY1("openrasp.app_id", "", PHP_INI_SYSTEM, OnUpdateOpenraspCString, &openrasp_ini.app_id)
PHP_INI_ENTRY1("openrasp.app_secret", "", PHP_INI_SYSTEM, OnUpdateOpenraspCString, &openrasp_ini.app_secret)
PHP_INI_ENTRY1("openrasp.remote_management_enable", "off", PHP_INI_SYSTEM, OnUpdateOpenraspBool, &openrasp_ini.remote_management_enable)
PHP_INI_ENTRY1("openrasp.heartbeat_interval", "180", PHP_INI_SYSTEM, OnUpdateOpenraspHeartbeatInterval, &openrasp_ini.heartbeat_interval)
PHP_INI_END()
PHP_GINIT_FUNCTION(openrasp)
{
#if defined(COMPILE_DL_JSON) && defined(ZTS)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
#ifdef ZTS
new (openrasp_globals) _zend_openrasp_globals;
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
if (!openrasp::oam)
{
update_config(&(openrasp_globals->config));
}
#else
update_config(&(openrasp_globals->config));
#endif
#endif
}
PHP_GSHUTDOWN_FUNCTION(openrasp)
{
#ifdef ZTS
openrasp_globals->~_zend_openrasp_globals();
#endif
}
PHP_MINIT_FUNCTION(openrasp)
{
ZEND_INIT_MODULE_GLOBALS(openrasp, PHP_GINIT(openrasp), PHP_GSHUTDOWN(openrasp));
REGISTER_INI_ENTRIES();
if (!current_sapi_supported())
{
return SUCCESS;
}
if (!make_openrasp_root_dir())
{
return SUCCESS;
}
openrasp::scm.reset(new openrasp::SharedConfigManager());
if (!openrasp::scm->startup())
{
openrasp_error(LEVEL_WARNING, RUNTIME_ERROR, _("Fail to startup SharedConfigManager."));
return SUCCESS;
}
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
if (need_alloc_shm_current_sapi() && openrasp_ini.remote_management_enable)
{
openrasp::oam.reset(new openrasp::OpenraspAgentManager());
if (!openrasp::oam->verify_ini_correct())
{
return SUCCESS;
}
remote_active = true;
}
#endif
if (!remote_active)
{
update_config(&OPENRASP_G(config));
}
if (PHP_MINIT(openrasp_log)(INIT_FUNC_ARGS_PASSTHRU) == FAILURE)
{
return SUCCESS;
}
if (PHP_MINIT(openrasp_v8)(INIT_FUNC_ARGS_PASSTHRU) == FAILURE)
{
return SUCCESS;
}
int result;
result = PHP_MINIT(openrasp_hook)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_MINIT(openrasp_inject)(INIT_FUNC_ARGS_PASSTHRU);
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
if (remote_active && openrasp::oam)
{
openrasp::oam->startup();
}
#endif
if (!remote_active)
{
std::string config_file_path = get_config_abs_path(ConfigHolder::FromType::kYaml);
std::string conf_contents;
if (get_entire_file_content(config_file_path.c_str(), conf_contents))
{
openrasp::YamlReader yreader(conf_contents);
std::vector<std::string> hook_white_key({"hook.white"});
std::map<std::string, std::vector<std::string>> hook_white_map;
std::vector<std::string> url_keys = yreader.fetch_object_keys(hook_white_key);
for (auto &key_item : url_keys)
{
hook_white_key.push_back(key_item);
std::vector<std::string> white_types = yreader.fetch_strings(hook_white_key, {});
hook_white_key.pop_back();
hook_white_map.insert({key_item, white_types});
}
openrasp::scm->build_check_type_white_array(hook_white_map);
}
#ifdef HAVE_FSWATCH
result = PHP_MINIT(openrasp_fswatch)(INIT_FUNC_ARGS_PASSTHRU);
#endif
}
result = PHP_MINIT(openrasp_security_policy)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_MINIT(openrasp_output_detect)(INIT_FUNC_ARGS_PASSTHRU);
is_initialized = true;
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(openrasp)
{
if (is_initialized)
{
int result;
if (!remote_active)
{
#ifdef HAVE_FSWATCH
result = PHP_MSHUTDOWN(openrasp_fswatch)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
#endif
}
result = PHP_MSHUTDOWN(openrasp_inject)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
result = PHP_MSHUTDOWN(openrasp_hook)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
result = PHP_MSHUTDOWN(openrasp_v8)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
result = PHP_MSHUTDOWN(openrasp_log)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
if (remote_active && openrasp::oam)
{
openrasp::oam->shutdown();
}
openrasp::oam.reset();
#endif
openrasp::scm->shutdown();
openrasp::scm.reset();
remote_active = false;
is_initialized = false;
}
UNREGISTER_INI_ENTRIES();
ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp, PHP_GSHUTDOWN(openrasp));
return SUCCESS;
}
PHP_RINIT_FUNCTION(openrasp)
{
if (is_initialized)
{
int result;
long config_last_update = openrasp::scm->get_config_last_update();
if (config_last_update && config_last_update > OPENRASP_G(config).GetLatestUpdateTime())
{
if (update_config(&OPENRASP_G(config), ConfigHolder::FromType::kJson))
{
OPENRASP_G(config).SetLatestUpdateTime(config_last_update);
}
}
// openrasp_inject must be called before openrasp_log cuz of request_id
result = PHP_RINIT(openrasp_inject)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_RINIT(openrasp_log)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_RINIT(openrasp_hook)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_RINIT(openrasp_v8)(INIT_FUNC_ARGS_PASSTHRU);
result = PHP_RINIT(openrasp_output_detect)(INIT_FUNC_ARGS_PASSTHRU);
}
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(openrasp)
{
if (is_initialized)
{
int result;
result = PHP_RSHUTDOWN(openrasp_log)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
result = PHP_RSHUTDOWN(openrasp_inject)(SHUTDOWN_FUNC_ARGS_PASSTHRU);
}
return SUCCESS;
}
PHP_MINFO_FUNCTION(openrasp)
{
php_info_print_table_start();
php_info_print_table_row(2, "Status", is_initialized ? "Protected" : "Unprotected, Initialization Failed");
php_info_print_table_row(2, "Version", PHP_OPENRASP_VERSION);
#ifdef OPENRASP_BUILD_TIME
php_info_print_table_row(2, "Build Time", OPENRASP_BUILD_TIME);
#endif
#ifdef OPENRASP_COMMIT_ID
php_info_print_table_row(2, "Commit Id", OPENRASP_COMMIT_ID);
#else
php_info_print_table_row(2, "Commit Id", "");
#endif
php_info_print_table_row(2, "V8 Version", ZEND_TOSTR(V8_MAJOR_VERSION) "." ZEND_TOSTR(V8_MINOR_VERSION));
php_info_print_table_row(2, "Antlr Version", "4.7.1 (JavaScript Runtime)");
#ifdef HAVE_OPENRASP_REMOTE_MANAGER
if (remote_active && openrasp::oam)
{
php_info_print_table_row(2, "Plugin Version",
openrasp::oam->agent_ctrl_block
? openrasp::oam->agent_ctrl_block->get_plugin_version()
: "");
}
#endif
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/** module depends
*/
#if ZEND_MODULE_API_NO >= 20050922
zend_module_dep openrasp_deps[] = {
ZEND_MOD_REQUIRED("standard")
ZEND_MOD_REQUIRED("json")
ZEND_MOD_CONFLICTS("xdebug")
ZEND_MOD_END};
#endif
zend_module_entry openrasp_module_entry = {
#if ZEND_MODULE_API_NO >= 20050922
STANDARD_MODULE_HEADER_EX,
NULL,
openrasp_deps,
#else
STANDARD_MODULE_HEADER,
#endif
"openrasp",
NULL,
PHP_MINIT(openrasp),
PHP_MSHUTDOWN(openrasp),
PHP_RINIT(openrasp),
PHP_RSHUTDOWN(openrasp),
PHP_MINFO(openrasp),
PHP_OPENRASP_VERSION,
STANDARD_MODULE_PROPERTIES};
#ifdef COMPILE_DL_OPENRASP
ZEND_GET_MODULE(openrasp)
#endif
static bool make_openrasp_root_dir()
{
char *path = openrasp_ini.root_dir;
if (!path)
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("openrasp.root_dir must not be an empty path"));
return false;
}
if (!IS_ABSOLUTE_PATH(path, strlen(path)))
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("openrasp.root_dir must not be a relative path"));
return false;
}
path = expand_filepath(path, nullptr);
if (!path || strnlen(path, 2) == 1)
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("openrasp.root_dir must not be a root path"));
efree(path);
return false;
}
std::string root_dir(path);
std::string default_slash(1, DEFAULT_SLASH);
efree(path);
std::vector<std::string> sub_dir_list{
"assets",
"conf",
"plugins",
"locale",
"logs" + default_slash + ALARM_LOG_DIR_NAME,
"logs" + default_slash + POLICY_LOG_DIR_NAME,
"logs" + default_slash + PLUGIN_LOG_DIR_NAME,
"logs" + default_slash + RASP_LOG_DIR_NAME};
for (auto dir : sub_dir_list)
{
std::string path(root_dir + DEFAULT_SLASH + dir);
if (!recursive_mkdir(path.c_str(), path.length(), 0777))
{
openrasp_error(LEVEL_WARNING, RUNTIME_ERROR, _("openrasp.root_dir must be a writable path"));
return false;
}
}
#ifdef HAVE_GETTEXT
if (nullptr != setlocale(LC_ALL, (nullptr == openrasp_ini.locale || strcmp(openrasp_ini.locale, "") == 0) ? "C" : openrasp_ini.locale))
{
std::string locale_path(root_dir + DEFAULT_SLASH + "locale" + DEFAULT_SLASH);
if (!bindtextdomain(GETTEXT_PACKAGE, locale_path.c_str()))
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("Fail to bindtextdomain - %s"), strerror(errno));
}
if (!textdomain(GETTEXT_PACKAGE))
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("Fail to textdomain - %s"), strerror(errno));
}
}
else
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("Unable to set OpenRASP locale to '%s'"), openrasp_ini.locale);
}
#endif
return true;
}
static std::string get_config_abs_path(ConfigHolder::FromType type)
{
std::string filename;
switch (type)
{
case ConfigHolder::FromType::kJson:
filename = "cloud-config.json";
break;
case ConfigHolder::FromType::kYaml:
default:
filename = "openrasp.yml";
break;
}
return std::string(openrasp_ini.root_dir) +
DEFAULT_SLASH +
"conf" +
DEFAULT_SLASH + filename;
}
static bool update_config(openrasp::ConfigHolder *config, ConfigHolder::FromType type)
{
if (nullptr != openrasp_ini.root_dir && strcmp(openrasp_ini.root_dir, "") != 0)
{
std::string config_file_path = get_config_abs_path(type);
std::string conf_contents;
if (get_entire_file_content(config_file_path.c_str(), conf_contents))
{
std::shared_ptr<openrasp::BaseReader> config_reader = nullptr;
switch (type)
{
case ConfigHolder::FromType::kJson:
config_reader.reset(new openrasp::JsonReader());
break;
case ConfigHolder::FromType::kYaml:
default:
config_reader.reset(new openrasp::YamlReader());
break;
}
if (config_reader)
{
config_reader->load(conf_contents);
if (config_reader->has_error())
{
openrasp_error(LEVEL_WARNING, CONFIG_ERROR, _("Fail to parse config, cuz of %s."),
config_reader->get_error_msg().c_str());
}
else
{
return config->update(config_reader.get());
}
}
}
}
return false;
}
static bool current_sapi_supported()
{
const static std::set<std::string> supported_sapis =
{
#ifdef HAVE_CLI_SUPPORT
"cli",
#endif
"cli-server",
"cgi-fcgi",
"fpm-fcgi",
"apache2handler"};
auto iter = supported_sapis.find(std::string(sapi_module.name));
if (iter == supported_sapis.end())
{
return false;
}
return true;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkTextureMapToSphere.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 "vtkTextureMapToSphere.h"
#include "vtkCellData.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
vtkStandardNewMacro(vtkTextureMapToSphere);
// Create object with Center (0,0,0) and the PreventSeam ivar is set to true. The
// sphere center is automatically computed.
vtkTextureMapToSphere::vtkTextureMapToSphere()
{
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->AutomaticSphereGeneration = 1;
this->PreventSeam = 1;
}
int vtkTextureMapToSphere::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkFloatArray *newTCoords;
vtkIdType numPts=input->GetNumberOfPoints();
vtkIdType ptId;
double x[3], rho, r, tc[2], phi=0.0, thetaX, thetaY;
double diff, PiOverTwo=vtkMath::Pi()/2.0;
vtkDebugMacro(<<"Generating Spherical Texture Coordinates");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
if ( numPts < 1 )
{
vtkErrorMacro(<<"Can't generate texture coordinates without points");
return 1;
}
if ( this->AutomaticSphereGeneration )
{
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
for ( ptId=0; ptId < numPts; ptId++ )
{
input->GetPoint(ptId, x);
this->Center[0] += x[0];
this->Center[1] += x[1];
this->Center[2] += x[2];
}
this->Center[0] /= numPts;
this->Center[1] /= numPts;
this->Center[2] /= numPts;
vtkDebugMacro(<<"Center computed as: (" << this->Center[0] <<", "
<< this->Center[1] <<", " << this->Center[2] <<")");
}
//loop over all points computing spherical coordinates. Only tricky part
//is keeping track of singularities/numerical problems.
newTCoords = vtkFloatArray::New();
newTCoords->SetName("Texture Coordinates");
newTCoords->SetNumberOfComponents(2);
newTCoords->SetNumberOfTuples(numPts);
for ( ptId=0; ptId < numPts; ptId++ )
{
input->GetPoint(ptId, x);
rho = sqrt((double)vtkMath::Distance2BetweenPoints(x,this->Center));
if ( rho != 0.0 )
{
// watch for truncation problems
if ( fabs((diff=x[2]-this->Center[2])) > rho )
{
phi = 0.0;
if ( diff > 0.0 )
{
tc[1] = 0.0;
}
else
{
tc[1] = 1.0;
}
}
else
{
phi = acos((double)(diff/rho));
tc[1] = phi / vtkMath::Pi();
}
}
else
{
tc[1] = 0.0;
}
r = rho * sin((double)phi);
if ( r != 0.0 )
{
// watch for truncation problems
if ( fabs((diff=x[0]-this->Center[0])) > r )
{
if ( diff > 0.0 )
{
thetaX = 0.0;
}
else
{
thetaX = vtkMath::Pi();
}
}
else
{
thetaX = acos ((double)diff/r);
}
if ( fabs((diff=x[1]-this->Center[1])) > r )
{
if ( diff > 0.0 )
{
thetaY = PiOverTwo;
}
else
{
thetaY = -PiOverTwo;
}
}
else
{
thetaY = asin ((double)diff/r);
}
}
else
{
thetaX = thetaY = 0.0;
}
if ( this->PreventSeam )
{
tc[0] = thetaX / vtkMath::Pi();
}
else
{
tc[0] = thetaX / (2.0*vtkMath::Pi());
if ( thetaY < 0.0 )
{
tc[0] = 1.0 - tc[0];
}
}
newTCoords->SetTuple(ptId,tc);
}
output->GetPointData()->CopyTCoordsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
return 1;
}
void vtkTextureMapToSphere::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Automatic Sphere Generation: " <<
(this->AutomaticSphereGeneration ? "On\n" : "Off\n");
os << indent << "Prevent Seam: " <<
(this->PreventSeam ? "On\n" : "Off\n");
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", "
<< this->Center[2] << ")\n";
}
|
// Copyright 2014 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 "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/test_data_source.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/guest_view/browser/guest_view_manager_delegate.h"
#include "components/guest_view/browser/test_guest_view_manager.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/test.h"
#include "extensions/common/extension.h"
#include "extensions/test/extension_test_message_listener.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace OnMessage = api::test::OnMessage;
namespace {
// Tests running extension APIs on WebUI.
class ExtensionWebUITest : public ExtensionApiTest {
protected:
testing::AssertionResult RunTest(const char* name,
const GURL& page_url,
bool expected_result) {
std::string script;
{
base::ScopedAllowBlockingForTesting allow_blocking;
// Tests are located in chrome/test/data/extensions/webui/$(name).
base::FilePath path;
base::PathService::Get(chrome::DIR_TEST_DATA, &path);
path =
path.AppendASCII("extensions").AppendASCII("webui").AppendASCII(name);
// Read the test.
if (!base::PathExists(path))
return testing::AssertionFailure() << "Couldn't find " << path.value();
base::ReadFileToString(path, &script);
script = "(function(){'use strict';" + script + "}());";
}
// Run the test.
bool actual_result = false;
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
content::RenderFrameHost* webui =
browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame();
if (!webui)
return testing::AssertionFailure() << "Failed to navigate to WebUI";
CHECK(content::ExecuteScriptAndExtractBool(webui, script, &actual_result));
return (expected_result == actual_result)
? testing::AssertionSuccess()
: (testing::AssertionFailure() << "Check console output");
}
testing::AssertionResult RunTestOnExtensionsPage(const char* name) {
return RunTest(name, GURL("chrome://extensions"), true);
}
testing::AssertionResult RunTestOnAboutPage(const char* name) {
// chrome://about is an innocuous page that doesn't have any bindings.
// Tests should fail.
return RunTest(name, GURL("chrome://about"), false);
}
};
// Tests running within an <extensionoptions> WebContents.
class ExtensionWebUIEmbeddedOptionsTest : public ExtensionWebUITest {
public:
void SetUpOnMainThread() override {
ExtensionWebUITest::SetUpOnMainThread();
guest_view::GuestViewManager::set_factory_for_testing(
&test_guest_view_manager_factory_);
test_guest_view_manager_ = static_cast<guest_view::TestGuestViewManager*>(
guest_view::GuestViewManager::CreateWithDelegate(
browser()->profile(),
ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate(
browser()->profile())));
}
protected:
// Loads |extension|'s options page in an <extensionoptions> and returns the
// <extensionoptions>'s WebContents.
content::WebContents* OpenExtensionOptions(const Extension* extension) {
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL(chrome::kChromeUIExtensionsURL)));
content::WebContents* webui =
browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_EQ(0U, test_guest_view_manager_->num_guests_created());
EXPECT_TRUE(content::ExecuteScript(
webui,
content::JsReplace(
"let extensionoptions = document.createElement('extensionoptions');"
"extensionoptions.extension = $1;"
"document.body.appendChild(extensionoptions);",
extension->id())));
content::WebContents* guest_web_contents =
test_guest_view_manager_->WaitForSingleGuestCreated();
EXPECT_TRUE(guest_web_contents);
EXPECT_TRUE(content::WaitForLoadStop(guest_web_contents));
return guest_web_contents;
}
private:
guest_view::TestGuestViewManagerFactory test_guest_view_manager_factory_;
raw_ptr<guest_view::TestGuestViewManager> test_guest_view_manager_ = nullptr;
};
#if !defined(OS_WIN) // flaky http://crbug.com/530722
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, SanityCheckAvailableAPIs) {
ASSERT_TRUE(RunTestOnExtensionsPage("sanity_check_available_apis.js"));
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, SanityCheckUnavailableAPIs) {
ASSERT_TRUE(RunTestOnAboutPage("sanity_check_available_apis.js"));
}
// Tests chrome.test.sendMessage, which exercises WebUI making a
// function call and receiving a response.
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, SendMessage) {
ExtensionTestMessageListener ping_listener("ping", true);
ASSERT_TRUE(RunTestOnExtensionsPage("send_message.js"));
ASSERT_TRUE(ping_listener.WaitUntilSatisfied());
ExtensionTestMessageListener result_listener(false);
ping_listener.Reply("pong");
ASSERT_TRUE(result_listener.WaitUntilSatisfied());
EXPECT_EQ("true", result_listener.message());
}
// Tests chrome.runtime.onMessage, which exercises WebUI registering and
// receiving an event.
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, OnMessage) {
ASSERT_TRUE(RunTestOnExtensionsPage("on_message.js"));
ExtensionTestMessageListener result_listener(false);
OnMessage::Info info;
info.data = "hi";
info.last_message = true;
EventRouter::Get(profile())->BroadcastEvent(base::WrapUnique(
new Event(events::RUNTIME_ON_MESSAGE, OnMessage::kEventName,
OnMessage::Create(info))));
ASSERT_TRUE(result_listener.WaitUntilSatisfied());
EXPECT_EQ("true", result_listener.message());
}
// Tests chrome.runtime.lastError, which exercises WebUI accessing a property
// on an API which it doesn't actually have access to. A bindings test really.
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, RuntimeLastError) {
ExtensionTestMessageListener ping_listener("ping", true);
ASSERT_TRUE(RunTestOnExtensionsPage("runtime_last_error.js"));
ASSERT_TRUE(ping_listener.WaitUntilSatisfied());
ExtensionTestMessageListener result_listener(false);
ping_listener.ReplyWithError("unknown host");
ASSERT_TRUE(result_listener.WaitUntilSatisfied());
EXPECT_EQ("true", result_listener.message());
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, CanEmbedExtensionOptions) {
ExtensionTestMessageListener ready_listener("ready", true);
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("extension_with_options_page"));
ASSERT_TRUE(extension);
ASSERT_TRUE(RunTestOnExtensionsPage("can_embed_extension_options.js"));
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ExtensionTestMessageListener load_listener("load", false);
ready_listener.Reply(extension->id());
ASSERT_TRUE(load_listener.WaitUntilSatisfied());
}
// Tests that an <extensionoptions> guest view can access the chrome.storage
// API, a privileged extension API.
IN_PROC_BROWSER_TEST_F(ExtensionWebUIEmbeddedOptionsTest,
ExtensionOptionsCanAccessStorage) {
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("extension_with_options_page"));
ASSERT_TRUE(extension);
content::WebContents* guest_web_contents = OpenExtensionOptions(extension);
const std::string storage_key = "test";
const int storage_value = 42;
EXPECT_TRUE(content::ExecuteScript(
guest_web_contents,
content::JsReplace("var onChangedPromise = new Promise((resolve) => {"
" chrome.storage.onChanged.addListener((change) => {"
" resolve(change[$1].newValue);"
" });"
"});",
storage_key)));
std::string set_result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
guest_web_contents,
content::JsReplace(
"try {"
" chrome.storage.local.set({$1: $2}, () => {"
" domAutomationController.send("
" chrome.runtime.lastError ?"
" chrome.runtime.lastError.message : 'success');"
" });"
"} catch (e) {"
" domAutomationController.send(e.name + ': ' + e.message);"
"}",
storage_key, storage_value),
&set_result));
ASSERT_EQ("success", set_result);
int actual_value = 0;
EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
guest_web_contents,
content::JsReplace("chrome.storage.local.get((storage) => {"
" domAutomationController.send(storage[$1]);"
"});",
storage_key),
&actual_value));
EXPECT_EQ(storage_value, actual_value);
EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
guest_web_contents,
"onChangedPromise.then((newValue) => {"
" domAutomationController.send(newValue);"
"});",
&actual_value));
EXPECT_EQ(storage_value, actual_value);
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUIEmbeddedOptionsTest,
ExtensionOptionsExternalLinksOpenInNewTab) {
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("extension_with_options_page"));
ASSERT_TRUE(extension);
content::WebContents* guest_web_contents = OpenExtensionOptions(extension);
content::WebContentsAddedObserver new_contents_observer;
EXPECT_TRUE(content::ExecuteScript(
guest_web_contents, "document.getElementById('link').click();"));
content::WebContents* new_contents = new_contents_observer.GetWebContents();
EXPECT_NE(TabStripModel::kNoTab,
browser()->tab_strip_model()->GetIndexOfWebContents(new_contents));
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, ReceivesExtensionOptionsOnClose) {
ExtensionTestMessageListener ready_listener("ready", true);
const Extension* extension =
InstallExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("close_self"), 1);
ASSERT_TRUE(extension);
ASSERT_TRUE(
RunTestOnExtensionsPage("receives_extension_options_on_close.js"));
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ExtensionTestMessageListener onclose_listener("onclose received", false);
ready_listener.Reply(extension->id());
ASSERT_TRUE(onclose_listener.WaitUntilSatisfied());
}
// Regression test for crbug.com/414526.
//
// Same setup as CanEmbedExtensionOptions but disable the extension before
// embedding.
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, EmbedDisabledExtension) {
ExtensionTestMessageListener ready_listener("ready", true);
std::string extension_id;
{
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("extension_with_options_page"));
ASSERT_TRUE(extension);
extension_id = extension->id();
DisableExtension(extension_id);
}
ASSERT_TRUE(RunTestOnExtensionsPage("can_embed_extension_options.js"));
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ExtensionTestMessageListener create_failed_listener("createfailed", false);
ready_listener.Reply(extension_id);
ASSERT_TRUE(create_failed_listener.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, EmbedInvalidExtension) {
ExtensionTestMessageListener ready_listener("ready", true);
const std::string extension_id = "thisisprobablynotrealextensionid";
ASSERT_TRUE(RunTestOnExtensionsPage("can_embed_extension_options.js"));
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ExtensionTestMessageListener create_failed_listener("createfailed", false);
ready_listener.Reply(extension_id);
ASSERT_TRUE(create_failed_listener.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, EmbedExtensionWithoutOptionsPage) {
ExtensionTestMessageListener ready_listener("ready", true);
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension_options")
.AppendASCII("extension_without_options_page"));
ASSERT_TRUE(extension);
ASSERT_TRUE(RunTestOnExtensionsPage("can_embed_extension_options.js"));
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ExtensionTestMessageListener create_failed_listener("createfailed", false);
ready_listener.Reply(extension->id());
ASSERT_TRUE(create_failed_listener.WaitUntilSatisfied());
}
// Tests crbug.com/1253745 where adding and removing listeners in a WebUI frame
// causes all listeners to be removed.
IN_PROC_BROWSER_TEST_F(ExtensionWebUITest, MultipleURLListeners) {
content::URLDataSource::Add(profile(),
std::make_unique<TestDataSource>("extensions"));
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(),
GURL("chrome://test/body1.html")));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* main_frame = web_contents->GetMainFrame();
EventRouter* event_router = EventRouter::Get(profile());
EXPECT_FALSE(event_router->HasEventListener("test.onMessage"));
// Register a listener and create a child frame at a different URL.
content::TestNavigationObserver observer(web_contents);
EXPECT_TRUE(content::ExecuteScript(main_frame, R"(
const listener = e => {};
chrome.test.onMessage.addListener(listener);
const iframe = document.createElement('iframe');
iframe.src = 'chrome://test/body2.html';
document.body.appendChild(iframe);
)"));
EXPECT_TRUE(event_router->HasEventListener("test.onMessage"));
observer.Wait();
// Add and remove the listener in the child frame.
content::RenderFrameHost* child_frame = ChildFrameAt(main_frame, 0);
EXPECT_EQ(GURL("chrome://test/body2.html"),
child_frame->GetLastCommittedURL());
EXPECT_TRUE(content::ExecuteScript(child_frame, R"(
const listener = e => {};
chrome.test.onMessage.addListener(listener);
chrome.test.onMessage.removeListener(listener);
)"));
EXPECT_TRUE(event_router->HasEventListener("test.onMessage"));
// Now remove last listener from main frame.
EXPECT_TRUE(content::ExecuteScript(main_frame, R"(
chrome.test.onMessage.removeListener(listener);
)"));
EXPECT_FALSE(event_router->HasEventListener("test.onMessage"));
}
#endif
} // namespace
} // namespace extensions
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#include <seastar/core/reactor.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/app-template.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/distributed.hh>
#include <seastar/core/queue.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/metrics.hh>
#include <seastar/core/print.hh>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <limits>
#include <cctype>
#include <vector>
#include <seastar/http/httpd.hh>
#include <seastar/http/reply.hh>
using namespace std::chrono_literals;
namespace seastar {
namespace httpd {
http_stats::http_stats(http_server& server, const sstring& name)
{
namespace sm = seastar::metrics;
std::vector<sm::label_instance> labels;
labels.push_back(sm::label_instance("service", name));
_metric_groups.add_group("httpd", {
sm::make_derive("connections_total", [&server] { return server.total_connections(); }, sm::description("The total number of connections opened"), labels),
sm::make_gauge("connections_current", [&server] { return server.current_connections(); }, sm::description("The current number of open connections"), labels),
sm::make_derive("read_errors", [&server] { return server.read_errors(); }, sm::description("The total number of errors while reading http requests"), labels),
sm::make_derive("reply_errors", [&server] { return server.reply_errors(); }, sm::description("The total number of errors while replying to http"), labels),
sm::make_derive("requests_served", [&server] { return server.requests_served(); }, sm::description("The total number of http requests served"), labels)
});
}
sstring http_server_control::generate_server_name() {
static thread_local uint16_t idgen;
return seastar::format("http-{}", idgen++);
}
future<> connection::do_response_loop() {
return _replies.pop_eventually().then(
[this] (std::unique_ptr<reply> resp) {
if (!resp) {
// eof
return make_ready_future<>();
}
_resp = std::move(resp);
return start_response().then([this] {
return do_response_loop();
});
});
}
future<> connection::start_response() {
if (_resp->_body_writer) {
return _resp->write_reply_to_connection(*this).then_wrapped([this] (auto f) {
if (f.failed()) {
// In case of an error during the write close the connection
_server._respond_errors++;
_done = true;
_replies.abort(std::make_exception_ptr(std::logic_error("Unknown exception during body creation")));
_replies.push(std::unique_ptr<reply>());
f.ignore_ready_future();
return make_ready_future<>();
}
return _write_buf.write("0\r\n\r\n", 5);
}).then_wrapped([this ] (auto f) {
if (f.failed()) {
// We could not write the closing sequence
// Something is probably wrong with the connection,
// we should close it, so the client will disconnect
_done = true;
_replies.abort(std::make_exception_ptr(std::logic_error("Unknown exception during body creation")));
_replies.push(std::unique_ptr<reply>());
f.ignore_ready_future();
return make_ready_future<>();
} else {
return _write_buf.flush();
}
}).then_wrapped([this] (auto f) {
if (f.failed()) {
// flush failed. just close the connection
_done = true;
_replies.abort(std::make_exception_ptr(std::logic_error("Unknown exception during body creation")));
_replies.push(std::unique_ptr<reply>());
f.ignore_ready_future();
}
_resp.reset();
return make_ready_future<>();
});
}
set_headers(*_resp);
_resp->_headers["Content-Length"] = to_sstring(
_resp->_content.size());
return _write_buf.write(_resp->_response_line.begin(),
_resp->_response_line.size()).then([this] {
return _resp->write_reply_headers(*this);
}).then([this] {
return _write_buf.write("\r\n", 2);
}).then([this] {
return write_body();
}).then([this] {
return _write_buf.flush();
}).then([this] {
_resp.reset();
});
}
connection::~connection() {
--_server._current_connections;
_server._connections.erase(_server._connections.iterator_to(*this));
_server.maybe_idle();
}
void connection::on_new_connection() {
++_server._total_connections;
++_server._current_connections;
_server._connections.push_back(*this);
}
future<> connection::read() {
return do_until([this] {return _done;}, [this] {
return read_one();
}).then_wrapped([this] (future<> f) {
// swallow error
if (f.failed()) {
_server._read_errors++;
}
f.ignore_ready_future();
return _replies.push_eventually( {});
}).finally([this] {
return _read_buf.close();
});
}
// Check if the request has a body, and if so read it. This function modifies
// the request object with the newly read body, and returns the object for
// further processing.
// FIXME: reading the entire request body into a string req->_content is a
// bad idea, because it may be very big. Instead, we should present to the
// handler a req->_content_stream, an input stream that reads from the request
// body - via a specialized input streams which reads exactly up to
// Content-Length or decodes chunked-encoding.
// FIXME: We currently support the case that there is a "Content-Length:"
// header - chunked encoding is not yet supported.
static future<std::unique_ptr<httpd::request>>
read_request_body(input_stream<char>& buf, std::unique_ptr<httpd::request> req) {
req->content_length = strtol(req->get_header("Content-Length").c_str(), nullptr, 10);
if (!req->content_length) {
return make_ready_future<std::unique_ptr<httpd::request>>(std::move(req));
}
return buf.read_exactly(req->content_length).then([req = std::move(req)] (temporary_buffer<char> body) mutable {
req->content = seastar::to_sstring(std::move(body));
return make_ready_future<std::unique_ptr<httpd::request>>(std::move(req));
});
}
future<> connection::read_one() {
_parser.init();
return _read_buf.consume(_parser).then([this] () mutable {
if (_parser.eof()) {
_done = true;
return make_ready_future<>();
}
++_server._requests_served;
std::unique_ptr<httpd::request> req = _parser.get_parsed_request();
if (_server._credentials) {
req->protocol_name = "https";
}
return read_request_body(_read_buf, std::move(req)).then([this] (std::unique_ptr<httpd::request> req) {
return _replies.not_full().then([req = std::move(req), this] () mutable {
return generate_reply(std::move(req));
}).then([this](bool done) {
_done = done;
});
});
});
}
future<> connection::respond() {
return do_response_loop().then_wrapped([this] (future<> f) {
// swallow error
if (f.failed()) {
_server._respond_errors++;
}
f.ignore_ready_future();
return _write_buf.close();
});
}
future<> connection::write_body() {
return _write_buf.write(_resp->_content.begin(),
_resp->_content.size());
}
void connection::set_headers(reply& resp) {
resp._headers["Server"] = "Seastar httpd";
resp._headers["Date"] = _server._date;
}
future<bool> connection::generate_reply(std::unique_ptr<request> req) {
auto resp = std::make_unique<reply>();
bool conn_keep_alive = false;
bool conn_close = false;
auto it = req->_headers.find("Connection");
if (it != req->_headers.end()) {
if (it->second == "Keep-Alive") {
conn_keep_alive = true;
} else if (it->second == "Close") {
conn_close = true;
}
}
bool should_close;
// TODO: Handle HTTP/2.0 when it releases
resp->set_version(req->_version);
if (req->_version == "1.0") {
if (conn_keep_alive) {
resp->_headers["Connection"] = "Keep-Alive";
}
should_close = !conn_keep_alive;
} else if (req->_version == "1.1") {
should_close = conn_close;
} else {
// HTTP/0.9 goes here
should_close = true;
}
sstring url = set_query_param(*req.get());
sstring version = req->_version;
set_headers(*resp);
resp->set_version(version);
return _server._routes.handle(url, std::move(req), std::move(resp)).
// Caller guarantees enough room
then([this, should_close, version = std::move(version)](std::unique_ptr<reply> rep) {
rep->set_version(version).done();
this->_replies.push(std::move(rep));
return make_ready_future<bool>(should_close);
});
}
}
}
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node.h"
#include "platform.h"
#include <unistd.h> /* getpagesize() */
#include <stdlib.h> /* getexecname() */
#include <strings.h> /* strncpy() */
#include <kstat.h>
#include <errno.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/loadavg.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#ifdef SUNOS_HAVE_IFADDRS
# include <ifaddrs.h>
#endif
#if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
#define PROCFS_FILE_OFFSET_BITS_HACK 1
#undef _FILE_OFFSET_BITS
#else
#define PROCFS_FILE_OFFSET_BITS_HACK 0
#endif
#include <procfs.h>
#if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
#define _FILE_OFFSET_BITS 64
#endif
namespace node {
using namespace v8;
double Platform::prog_start_time = Platform::GetUptime();
char** Platform::SetupArgs(int argc, char *argv[]) {
return argv;
}
void Platform::SetProcessTitle(char *title) {
;
}
const char* Platform::GetProcessTitle(int *len) {
*len = 0;
return NULL;
}
int Platform::GetMemory(size_t *rss) {
psinfo_t psinfo;
int fd;
if ((fd = open("/proc/self/psinfo", O_RDONLY)) < 0)
return -1;
if (read(fd, &psinfo, sizeof (psinfo_t)) != sizeof (psinfo_t)) {
(void) close(fd);
return -1;
}
*rss = (size_t) psinfo.pr_rssize * 1024;
(void) close(fd);
return 0;
}
static Handle<Value> data_named(kstat_named_t *knp) {
Handle<Value> val;
switch (knp->data_type) {
case KSTAT_DATA_CHAR:
val = Number::New(knp->value.c[0]);
break;
case KSTAT_DATA_INT32:
val = Number::New(knp->value.i32);
break;
case KSTAT_DATA_UINT32:
val = Number::New(knp->value.ui32);
break;
case KSTAT_DATA_INT64:
val = Number::New(knp->value.i64);
break;
case KSTAT_DATA_UINT64:
val = Number::New(knp->value.ui64);
break;
case KSTAT_DATA_STRING:
val = String::New(KSTAT_NAMED_STR_PTR(knp));
break;
default:
val = String::New("unrecognized data type");
}
return (val);
}
int Platform::GetCPUInfo(Local<Array> *cpus) {
HandleScope scope;
Local<Object> cpuinfo;
Local<Object> cputimes;
int lookup_instance;
kstat_ctl_t *kc;
kstat_t *ksp;
kstat_named_t *knp;
if ((kc = kstat_open()) == NULL)
return -1;
*cpus = Array::New();
lookup_instance = 0;
while (ksp = kstat_lookup(kc, (char *)"cpu_info", lookup_instance, NULL)){
cpuinfo = Object::New();
if (kstat_read(kc, ksp, NULL) == -1) {
/*
* It is deeply annoying, but some kstats can return errors
* under otherwise routine conditions. (ACPI is one
* offender; there are surely others.) To prevent these
* fouled kstats from completely ruining our day, we assign
* an "error" member to the return value that consists of
* the strerror().
*/
cpuinfo->Set(String::New("error"), String::New(strerror(errno)));
(*cpus)->Set(lookup_instance, cpuinfo);
} else {
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"clock_MHz");
cpuinfo->Set(String::New("speed"), data_named(knp));
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"brand");
cpuinfo->Set(String::New("model"), data_named(knp));
(*cpus)->Set(lookup_instance, cpuinfo);
}
lookup_instance++;
}
lookup_instance = 0;
while (ksp = kstat_lookup(kc, (char *)"cpu", lookup_instance, (char *)"sys")){
cpuinfo = (*cpus)->Get(lookup_instance)->ToObject();
cputimes = Object::New();
if (kstat_read(kc, ksp, NULL) == -1) {
cputimes->Set(String::New("error"), String::New(strerror(errno)));
cpuinfo->Set(String::New("times"), cpuinfo);
} else {
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"cpu_ticks_kernel");
cputimes->Set(String::New("system"), data_named(knp));
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"cpu_ticks_user");
cputimes->Set(String::New("user"), data_named(knp));
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"cpu_ticks_idle");
cputimes->Set(String::New("idle"), data_named(knp));
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"intr");
cputimes->Set(String::New("irq"), data_named(knp));
cpuinfo->Set(String::New("times"), cputimes);
}
lookup_instance++;
}
kstat_close(kc);
return 0;
}
double Platform::GetUptimeImpl() {
kstat_ctl_t *kc;
kstat_t *ksp;
kstat_named_t *knp;
long hz = sysconf(_SC_CLK_TCK);
double clk_intr;
if ((kc = kstat_open()) == NULL)
return -1;
ksp = kstat_lookup(kc, (char *)"unix", 0, (char *)"system_misc");
if (kstat_read(kc, ksp, NULL) == -1) {
clk_intr = -1;
} else {
knp = (kstat_named_t *) kstat_data_lookup(ksp, (char *)"clk_intr");
clk_intr = knp->value.ul / hz;
}
kstat_close(kc);
return clk_intr;
}
Handle<Value> Platform::GetInterfaceAddresses() {
HandleScope scope;
#ifndef SUNOS_HAVE_IFADDRS
return ThrowException(Exception::Error(String::New(
"This version of sunos doesn't support getifaddrs")));
#else
struct ::ifaddrs *addrs, *ent;
struct ::sockaddr_in *in4;
struct ::sockaddr_in6 *in6;
char ip[INET6_ADDRSTRLEN];
Local<Object> ret, o;
Local<String> name, ipaddr, family;
Local<Array> ifarr;
if (getifaddrs(&addrs) != 0) {
return ThrowException(ErrnoException(errno, "getifaddrs"));
}
ret = Object::New();
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
bzero(&ip, sizeof (ip));
if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING)) {
continue;
}
if (ent->ifa_addr == NULL) {
continue;
}
name = String::New(ent->ifa_name);
if (ret->Has(name)) {
ifarr = Local<Array>::Cast(ret->Get(name));
} else {
ifarr = Array::New();
ret->Set(name, ifarr);
}
if (ent->ifa_addr->sa_family == AF_INET6) {
in6 = (struct sockaddr_in6 *)ent->ifa_addr;
inet_ntop(AF_INET6, &(in6->sin6_addr), ip, INET6_ADDRSTRLEN);
family = String::New("IPv6");
} else if (ent->ifa_addr->sa_family == AF_INET) {
in4 = (struct sockaddr_in *)ent->ifa_addr;
inet_ntop(AF_INET, &(in4->sin_addr), ip, INET6_ADDRSTRLEN);
family = String::New("IPv4");
} else {
(void) strlcpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN);
family = String::New("<unknown>");
}
o = Object::New();
o->Set(String::New("address"), String::New(ip));
o->Set(String::New("family"), family);
o->Set(String::New("internal"), ent->ifa_flags & IFF_PRIVATE || ent->ifa_flags &
IFF_LOOPBACK ? True() : False());
ifarr->Set(ifarr->Length(), o);
}
freeifaddrs(addrs);
return scope.Close(ret);
#endif // SUNOS_HAVE_IFADDRS
}
} // namespace node
|
/**
* @file
* @copyright defined in eos/LICENSE
*/
#pragma once
#include <appbase/application.hpp>
#include <eosio/chain/asset.hpp>
#include <eosio/chain/authority.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/contract_table_objects.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/abi_serializer.hpp>
#include <eosio/chain/plugin_interface.hpp>
#include <eosio/chain/types.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <fc/static_variant.hpp>
namespace fc { class variant; }
namespace eosio {
using chain::controller;
using std::unique_ptr;
using std::pair;
using namespace appbase;
using chain::name;
using chain::uint128_t;
using chain::public_key_type;
using chain::transaction;
using chain::transaction_id_type;
using fc::optional;
using boost::container::flat_set;
using chain::asset;
using chain::symbol;
using chain::authority;
using chain::account_name;
using chain::action_name;
using chain::abi_def;
using chain::abi_serializer;
namespace chain_apis {
struct empty{};
struct permission {
name perm_name;
name parent;
authority required_auth;
};
template<typename>
struct resolver_factory;
// see specializations for uint64_t and double in source file
template<typename Type>
Type convert_to_type(const string& str, const string& desc) {
try {
return fc::variant(str).as<Type>();
} FC_RETHROW_EXCEPTIONS(warn, "Could not convert ${desc} string '${str}' to key type.", ("desc", desc)("str",str) )
}
template<>
uint64_t convert_to_type(const string& str, const string& desc);
template<>
double convert_to_type(const string& str, const string& desc);
class read_only {
const controller& db;
const fc::microseconds abi_serializer_max_time;
bool shorten_abi_errors = true;
public:
static const string KEYi64;
read_only(const controller& db, const fc::microseconds& abi_serializer_max_time)
: db(db), abi_serializer_max_time(abi_serializer_max_time) {}
void validate() const {}
void set_shorten_abi_errors( bool f ) { shorten_abi_errors = f; }
using get_info_params = empty;
struct get_info_results {
string server_version;
chain::chain_id_type chain_id;
uint32_t head_block_num = 0;
uint32_t last_irreversible_block_num = 0;
chain::block_id_type last_irreversible_block_id;
chain::block_id_type head_block_id;
fc::time_point head_block_time;
account_name head_block_producer;
uint64_t virtual_block_cpu_limit = 0;
uint64_t virtual_block_net_limit = 0;
uint64_t block_cpu_limit = 0;
uint64_t block_net_limit = 0;
//string recent_slots;
//double participation_rate = 0;
optional<string> server_version_string;
optional<uint32_t> fork_db_head_block_num;
optional<chain::block_id_type> fork_db_head_block_id;
};
get_info_results get_info(const get_info_params&) const;
struct get_activated_protocol_features_params {
optional<uint32_t> lower_bound;
optional<uint32_t> upper_bound;
uint32_t limit = 10;
bool search_by_block_num = false;
bool reverse = false;
};
struct get_activated_protocol_features_results {
fc::variants activated_protocol_features;
optional<uint32_t> more;
};
get_activated_protocol_features_results get_activated_protocol_features( const get_activated_protocol_features_params& params )const;
struct producer_info {
name producer_name;
};
using account_resource_limit = chain::resource_limits::account_resource_limit;
struct get_account_results {
name account_name;
uint32_t head_block_num = 0;
fc::time_point head_block_time;
bool privileged = false;
fc::time_point last_code_update;
fc::time_point created;
optional<asset> core_liquid_balance;
int64_t ram_quota = 0;
int64_t net_weight = 0;
int64_t cpu_weight = 0;
account_resource_limit net_limit;
account_resource_limit cpu_limit;
int64_t ram_usage = 0;
vector<permission> permissions;
fc::variant total_resources;
fc::variant self_delegated_bandwidth;
fc::variant refund_request;
fc::variant voter_info;
};
struct get_account_params {
name account_name;
optional<symbol> expected_core_symbol;
};
get_account_results get_account( const get_account_params& params )const;
struct get_code_results {
name account_name;
string wast;
string wasm;
fc::sha256 code_hash;
optional<abi_def> abi;
};
struct get_code_params {
name account_name;
bool code_as_wasm = false;
};
struct get_code_hash_results {
name account_name;
fc::sha256 code_hash;
};
struct get_code_hash_params {
name account_name;
};
struct get_abi_results {
name account_name;
optional<abi_def> abi;
};
struct get_abi_params {
name account_name;
};
struct get_raw_code_and_abi_results {
name account_name;
chain::blob wasm;
chain::blob abi;
};
struct get_raw_code_and_abi_params {
name account_name;
};
struct get_raw_abi_params {
name account_name;
optional<fc::sha256> abi_hash;
};
struct get_raw_abi_results {
name account_name;
fc::sha256 code_hash;
fc::sha256 abi_hash;
optional<chain::blob> abi;
};
get_code_results get_code( const get_code_params& params )const;
get_code_hash_results get_code_hash( const get_code_hash_params& params )const;
get_abi_results get_abi( const get_abi_params& params )const;
get_raw_code_and_abi_results get_raw_code_and_abi( const get_raw_code_and_abi_params& params)const;
get_raw_abi_results get_raw_abi( const get_raw_abi_params& params)const;
struct abi_json_to_bin_params {
name code;
name action;
fc::variant args;
};
struct abi_json_to_bin_result {
vector<char> binargs;
};
abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const;
struct abi_bin_to_json_params {
name code;
name action;
vector<char> binargs;
};
struct abi_bin_to_json_result {
fc::variant args;
};
abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const;
struct get_required_keys_params {
fc::variant transaction;
flat_set<public_key_type> available_keys;
};
struct get_required_keys_result {
flat_set<public_key_type> required_keys;
};
get_required_keys_result get_required_keys( const get_required_keys_params& params)const;
using get_transaction_id_params = transaction;
using get_transaction_id_result = transaction_id_type;
get_transaction_id_result get_transaction_id( const get_transaction_id_params& params)const;
struct get_block_params {
string block_num_or_id;
};
fc::variant get_block(const get_block_params& params) const;
struct get_block_header_state_params {
string block_num_or_id;
};
fc::variant get_block_header_state(const get_block_header_state_params& params) const;
struct get_table_rows_params {
bool json = false;
name code;
string scope;
name table;
string table_key;
string lower_bound;
string upper_bound;
uint32_t limit = 10;
string key_type; // type of key specified by index_position
string index_position; // 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc
string encode_type{"dec"}; //dec, hex , default=dec
optional<bool> reverse;
optional<bool> show_payer; // show RAM pyer
};
struct get_table_rows_result {
vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object
bool more = false; ///< true if last element in data is not the end and sizeof data() < limit
};
get_table_rows_result get_table_rows( const get_table_rows_params& params )const;
struct get_table_by_scope_params {
name code; // mandatory
name table = 0; // optional, act as filter
string lower_bound; // lower bound of scope, optional
string upper_bound; // upper bound of scope, optional
uint32_t limit = 10;
optional<bool> reverse;
};
struct get_table_by_scope_result_row {
name code;
name scope;
name table;
name payer;
uint32_t count;
};
struct get_table_by_scope_result {
vector<get_table_by_scope_result_row> rows;
string more; ///< fill lower_bound with this value to fetch more rows
};
get_table_by_scope_result get_table_by_scope( const get_table_by_scope_params& params )const;
struct get_currency_balance_params {
name code;
name account;
optional<string> symbol;
};
vector<asset> get_currency_balance( const get_currency_balance_params& params )const;
struct get_currency_stats_params {
name code;
string symbol;
};
struct get_currency_stats_result {
asset supply;
asset max_supply;
account_name issuer;
};
fc::variant get_currency_stats( const get_currency_stats_params& params )const;
struct get_producers_params {
bool json = false;
string lower_bound;
uint32_t limit = 50;
};
struct get_producers_result {
vector<fc::variant> rows; ///< one row per item, either encoded as hex string or JSON object
double total_producer_vote_weight;
string more; ///< fill lower_bound with this value to fetch more rows
};
get_producers_result get_producers( const get_producers_params& params )const;
struct get_producer_schedule_params {
};
struct get_producer_schedule_result {
fc::variant active;
fc::variant pending;
fc::variant proposed;
};
get_producer_schedule_result get_producer_schedule( const get_producer_schedule_params& params )const;
struct get_scheduled_transactions_params {
bool json = false;
string lower_bound; /// timestamp OR transaction ID
uint32_t limit = 50;
};
struct get_scheduled_transactions_result {
fc::variants transactions;
string more; ///< fill lower_bound with this to fetch next set of transactions
};
get_scheduled_transactions_result get_scheduled_transactions( const get_scheduled_transactions_params& params ) const;
static void copy_inline_row(const chain::key_value_object& obj, vector<char>& data) {
data.resize( obj.value.size() );
memcpy( data.data(), obj.value.data(), obj.value.size() );
}
template<typename Function>
void walk_key_value_table(const name& code, const name& scope, const name& table, Function f) const
{
const auto& d = db.db();
const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(code, scope, table));
if (t_id != nullptr) {
const auto &idx = d.get_index<chain::key_value_index, chain::by_scope_primary>();
decltype(t_id->id) next_tid(t_id->id._id + 1);
auto lower = idx.lower_bound(boost::make_tuple(t_id->id));
auto upper = idx.lower_bound(boost::make_tuple(next_tid));
for (auto itr = lower; itr != upper; ++itr) {
if (!f(*itr)) {
break;
}
}
}
}
static uint64_t get_table_index_name(const read_only::get_table_rows_params& p, bool& primary);
template <typename IndexType, typename SecKeyType, typename ConvFn>
read_only::get_table_rows_result get_table_rows_by_seckey( const read_only::get_table_rows_params& p, const abi_def& abi, ConvFn conv )const {
read_only::get_table_rows_result result;
const auto& d = db.db();
uint64_t scope = convert_to_type<uint64_t>(p.scope, "scope");
abi_serializer abis;
abis.set_abi(abi, abi_serializer_max_time);
bool primary = false;
const uint64_t table_with_index = get_table_index_name(p, primary);
const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, p.table));
const auto* index_t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, table_with_index));
if( t_id != nullptr && index_t_id != nullptr ) {
using secondary_key_type = std::result_of_t<decltype(conv)(SecKeyType)>;
static_assert( std::is_same<typename IndexType::value_type::secondary_key_type, secondary_key_type>::value, "Return type of conv does not match type of secondary key for IndexType" );
const auto& secidx = d.get_index<IndexType, chain::by_secondary>();
auto lower_bound_lookup_tuple = std::make_tuple( index_t_id->id._id,
eosio::chain::secondary_key_traits<secondary_key_type>::true_lowest(),
std::numeric_limits<uint64_t>::lowest() );
auto upper_bound_lookup_tuple = std::make_tuple( index_t_id->id._id,
eosio::chain::secondary_key_traits<secondary_key_type>::true_highest(),
std::numeric_limits<uint64_t>::max() );
if( p.lower_bound.size() ) {
if( p.key_type == "name" ) {
name s(p.lower_bound);
SecKeyType lv = convert_to_type<SecKeyType>( s.to_string(), "lower_bound name" ); // avoids compiler error
std::get<1>(lower_bound_lookup_tuple) = conv( lv );
} else {
SecKeyType lv = convert_to_type<SecKeyType>( p.lower_bound, "lower_bound" );
std::get<1>(lower_bound_lookup_tuple) = conv( lv );
}
}
if( p.upper_bound.size() ) {
if( p.key_type == "name" ) {
name s(p.upper_bound);
SecKeyType uv = convert_to_type<SecKeyType>( s.to_string(), "upper_bound name" );
std::get<1>(upper_bound_lookup_tuple) = conv( uv );
} else {
SecKeyType uv = convert_to_type<SecKeyType>( p.upper_bound, "upper_bound" );
std::get<1>(upper_bound_lookup_tuple) = conv( uv );
}
}
if( upper_bound_lookup_tuple < lower_bound_lookup_tuple )
return result;
auto walk_table_row_range = [&]( auto itr, auto end_itr ) {
auto cur_time = fc::time_point::now();
auto end_time = cur_time + fc::microseconds(1000 * 10); /// 10ms max time
vector<char> data;
for( unsigned int count = 0; cur_time <= end_time && count < p.limit && itr != end_itr; ++itr, cur_time = fc::time_point::now() ) {
const auto* itr2 = d.find<chain::key_value_object, chain::by_scope_primary>( boost::make_tuple(t_id->id, itr->primary_key) );
if( itr2 == nullptr ) continue;
copy_inline_row(*itr2, data);
fc::variant data_var;
if( p.json ) {
data_var = abis.binary_to_variant( abis.get_table_type(p.table), data, abi_serializer_max_time, shorten_abi_errors );
} else {
data_var = fc::variant( data );
}
if( p.show_payer && *p.show_payer ) {
result.rows.emplace_back( fc::mutable_variant_object("data", std::move(data_var))("payer", itr->payer) );
} else {
result.rows.emplace_back( std::move(data_var) );
}
++count;
}
if( itr != end_itr ) {
result.more = true;
}
};
auto lower = secidx.lower_bound( lower_bound_lookup_tuple );
auto upper = secidx.upper_bound( upper_bound_lookup_tuple );
if( p.reverse && *p.reverse ) {
walk_table_row_range( boost::make_reverse_iterator(upper), boost::make_reverse_iterator(lower) );
} else {
walk_table_row_range( lower, upper );
}
}
return result;
}
template <typename IndexType>
read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p, const abi_def& abi )const {
read_only::get_table_rows_result result;
const auto& d = db.db();
uint64_t scope = convert_to_type<uint64_t>(p.scope, "scope");
abi_serializer abis;
abis.set_abi(abi, abi_serializer_max_time);
const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, p.table));
if( t_id != nullptr ) {
const auto& idx = d.get_index<IndexType, chain::by_scope_primary>();
auto lower_bound_lookup_tuple = std::make_tuple( t_id->id, std::numeric_limits<uint64_t>::lowest() );
auto upper_bound_lookup_tuple = std::make_tuple( t_id->id, std::numeric_limits<uint64_t>::max() );
if( p.lower_bound.size() ) {
if( p.key_type == "name" ) {
name s(p.lower_bound);
std::get<1>(lower_bound_lookup_tuple) = s.value;
} else {
auto lv = convert_to_type<typename IndexType::value_type::key_type>( p.lower_bound, "lower_bound" );
std::get<1>(lower_bound_lookup_tuple) = lv;
}
}
if( p.upper_bound.size() ) {
if( p.key_type == "name" ) {
name s(p.upper_bound);
std::get<1>(upper_bound_lookup_tuple) = s.value;
} else {
auto uv = convert_to_type<typename IndexType::value_type::key_type>( p.upper_bound, "upper_bound" );
std::get<1>(upper_bound_lookup_tuple) = uv;
}
}
if( upper_bound_lookup_tuple < lower_bound_lookup_tuple )
return result;
auto walk_table_row_range = [&]( auto itr, auto end_itr ) {
auto cur_time = fc::time_point::now();
auto end_time = cur_time + fc::microseconds(1000 * 10); /// 10ms max time
vector<char> data;
for( unsigned int count = 0; cur_time <= end_time && count < p.limit && itr != end_itr; ++count, ++itr, cur_time = fc::time_point::now() ) {
copy_inline_row(*itr, data);
fc::variant data_var;
if( p.json ) {
data_var = abis.binary_to_variant( abis.get_table_type(p.table), data, abi_serializer_max_time, shorten_abi_errors );
} else {
data_var = fc::variant( data );
}
if( p.show_payer && *p.show_payer ) {
result.rows.emplace_back( fc::mutable_variant_object("data", std::move(data_var))("payer", itr->payer) );
} else {
result.rows.emplace_back( std::move(data_var) );
}
}
if( itr != end_itr ) {
result.more = true;
}
};
auto lower = idx.lower_bound( lower_bound_lookup_tuple );
auto upper = idx.upper_bound( upper_bound_lookup_tuple );
if( p.reverse && *p.reverse ) {
walk_table_row_range( boost::make_reverse_iterator(upper), boost::make_reverse_iterator(lower) );
} else {
walk_table_row_range( lower, upper );
}
}
return result;
}
chain::symbol extract_core_symbol()const;
friend struct resolver_factory<read_only>;
};
class read_write {
controller& db;
const fc::microseconds abi_serializer_max_time;
public:
read_write(controller& db, const fc::microseconds& abi_serializer_max_time);
void validate() const;
using push_block_params = chain::signed_block;
using push_block_results = empty;
void push_block(push_block_params&& params, chain::plugin_interface::next_function<push_block_results> next);
using push_transaction_params = fc::variant_object;
struct push_transaction_results {
chain::transaction_id_type transaction_id;
fc::variant processed;
};
void push_transaction(const push_transaction_params& params, chain::plugin_interface::next_function<push_transaction_results> next);
void push_transaction_v2(const push_transaction_params& params, chain::plugin_interface::next_function<push_transaction_results> next);
using push_transactions_params = vector<push_transaction_params>;
using push_transactions_results = vector<push_transaction_results>;
void push_transactions(const push_transactions_params& params, chain::plugin_interface::next_function<push_transactions_results> next);
using send_transaction_params = push_transaction_params;
using send_transaction_results = push_transaction_results;
void send_transaction(const send_transaction_params& params, chain::plugin_interface::next_function<send_transaction_results> next);
friend resolver_factory<read_write>;
};
//support for --key_types [sha256,ripemd160] and --encoding [dec/hex]
constexpr const char i64[] = "i64";
constexpr const char i128[] = "i128";
constexpr const char i256[] = "i256";
constexpr const char float64[] = "float64";
constexpr const char float128[] = "float128";
constexpr const char sha256[] = "sha256";
constexpr const char ripemd160[] = "ripemd160";
constexpr const char dec[] = "dec";
constexpr const char hex[] = "hex";
template<const char*key_type , const char *encoding=chain_apis::dec>
struct keytype_converter ;
template<>
struct keytype_converter<chain_apis::sha256, chain_apis::hex> {
using input_type = chain::checksum256_type;
using index_type = chain::index256_index;
static auto function() {
return [](const input_type& v) {
chain::key256_t k;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
k[0] = ((uint128_t *)&v._hash)[0]; //0-127
k[1] = ((uint128_t *)&v._hash)[1]; //127-256
#pragma GCC diagnostic pop
return k;
};
}
};
//key160 support with padding zeros in the end of key256
template<>
struct keytype_converter<chain_apis::ripemd160, chain_apis::hex> {
using input_type = chain::checksum160_type;
using index_type = chain::index256_index;
static auto function() {
return [](const input_type& v) {
chain::key256_t k;
memset(k.data(), 0, sizeof(k));
memcpy(k.data(), v._hash, sizeof(v._hash));
return k;
};
}
};
template<>
struct keytype_converter<chain_apis::i256> {
using input_type = boost::multiprecision::uint256_t;
using index_type = chain::index256_index;
static auto function() {
return [](const input_type v) {
chain::key256_t k;
k[0] = ((uint128_t *)&v)[0]; //0-127
k[1] = ((uint128_t *)&v)[1]; //127-256
return k;
};
}
};
} // namespace chain_apis
class chain_plugin : public plugin<chain_plugin> {
public:
APPBASE_PLUGIN_REQUIRES()
chain_plugin();
virtual ~chain_plugin();
virtual void set_program_options(options_description& cli, options_description& cfg) override;
void plugin_initialize(const variables_map& options);
void plugin_startup();
void plugin_shutdown();
chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain(), get_abi_serializer_max_time()); }
chain_apis::read_write get_read_write_api() { return chain_apis::read_write(chain(), get_abi_serializer_max_time()); }
void accept_block( const chain::signed_block_ptr& block );
void accept_transaction(const chain::packed_transaction& trx, chain::plugin_interface::next_function<chain::transaction_trace_ptr> next);
void accept_transaction(const chain::transaction_metadata_ptr& trx, chain::plugin_interface::next_function<chain::transaction_trace_ptr> next);
bool block_is_on_preferred_chain(const chain::block_id_type& block_id);
static bool recover_reversible_blocks( const fc::path& db_dir,
uint32_t cache_size,
optional<fc::path> new_db_dir = optional<fc::path>(),
uint32_t truncate_at_block = 0
);
static bool import_reversible_blocks( const fc::path& reversible_dir,
uint32_t cache_size,
const fc::path& reversible_blocks_file
);
static bool export_reversible_blocks( const fc::path& reversible_dir,
const fc::path& reversible_blocks_file
);
// Only call this after plugin_initialize()!
controller& chain();
// Only call this after plugin_initialize()!
const controller& chain() const;
chain::chain_id_type get_chain_id() const;
fc::microseconds get_abi_serializer_max_time() const;
static void handle_guard_exception(const chain::guard_exception& e);
static void handle_db_exhaustion();
static void handle_bad_alloc();
private:
static void log_guard_exception(const chain::guard_exception& e);
unique_ptr<class chain_plugin_impl> my;
};
}
FC_REFLECT( eosio::chain_apis::permission, (perm_name)(parent)(required_auth) )
FC_REFLECT(eosio::chain_apis::empty, )
FC_REFLECT(eosio::chain_apis::read_only::get_info_results,
(server_version)(chain_id)(head_block_num)(last_irreversible_block_num)(last_irreversible_block_id)(head_block_id)(head_block_time)(head_block_producer)(virtual_block_cpu_limit)(virtual_block_net_limit)(block_cpu_limit)(block_net_limit)(server_version_string)(fork_db_head_block_num)(fork_db_head_block_id) )
FC_REFLECT(eosio::chain_apis::read_only::get_activated_protocol_features_params, (lower_bound)(upper_bound)(limit)(search_by_block_num)(reverse) )
FC_REFLECT(eosio::chain_apis::read_only::get_activated_protocol_features_results, (activated_protocol_features)(more) )
FC_REFLECT(eosio::chain_apis::read_only::get_block_params, (block_num_or_id))
FC_REFLECT(eosio::chain_apis::read_only::get_block_header_state_params, (block_num_or_id))
FC_REFLECT( eosio::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) )
FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_params, (json)(code)(scope)(table)(table_key)(lower_bound)(upper_bound)(limit)(key_type)(index_position)(encode_type)(reverse)(show_payer) )
FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_result, (rows)(more) );
FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_params, (code)(table)(lower_bound)(upper_bound)(limit)(reverse) )
FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_result_row, (code)(scope)(table)(payer)(count));
FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_result, (rows)(more) );
FC_REFLECT( eosio::chain_apis::read_only::get_currency_balance_params, (code)(account)(symbol));
FC_REFLECT( eosio::chain_apis::read_only::get_currency_stats_params, (code)(symbol));
FC_REFLECT( eosio::chain_apis::read_only::get_currency_stats_result, (supply)(max_supply)(issuer));
FC_REFLECT( eosio::chain_apis::read_only::get_producers_params, (json)(lower_bound)(limit) )
FC_REFLECT( eosio::chain_apis::read_only::get_producers_result, (rows)(total_producer_vote_weight)(more) );
FC_REFLECT_EMPTY( eosio::chain_apis::read_only::get_producer_schedule_params )
FC_REFLECT( eosio::chain_apis::read_only::get_producer_schedule_result, (active)(pending)(proposed) );
FC_REFLECT( eosio::chain_apis::read_only::get_scheduled_transactions_params, (json)(lower_bound)(limit) )
FC_REFLECT( eosio::chain_apis::read_only::get_scheduled_transactions_result, (transactions)(more) );
FC_REFLECT( eosio::chain_apis::read_only::get_account_results,
(account_name)(head_block_num)(head_block_time)(privileged)(last_code_update)(created)
(core_liquid_balance)(ram_quota)(net_weight)(cpu_weight)(net_limit)(cpu_limit)(ram_usage)(permissions)
(total_resources)(self_delegated_bandwidth)(refund_request)(voter_info) )
// @swap code_hash
FC_REFLECT( eosio::chain_apis::read_only::get_code_results, (account_name)(code_hash)(wast)(wasm)(abi) )
FC_REFLECT( eosio::chain_apis::read_only::get_code_hash_results, (account_name)(code_hash) )
FC_REFLECT( eosio::chain_apis::read_only::get_abi_results, (account_name)(abi) )
FC_REFLECT( eosio::chain_apis::read_only::get_account_params, (account_name)(expected_core_symbol) )
FC_REFLECT( eosio::chain_apis::read_only::get_code_params, (account_name)(code_as_wasm) )
FC_REFLECT( eosio::chain_apis::read_only::get_code_hash_params, (account_name) )
FC_REFLECT( eosio::chain_apis::read_only::get_abi_params, (account_name) )
FC_REFLECT( eosio::chain_apis::read_only::get_raw_code_and_abi_params, (account_name) )
FC_REFLECT( eosio::chain_apis::read_only::get_raw_code_and_abi_results, (account_name)(wasm)(abi) )
FC_REFLECT( eosio::chain_apis::read_only::get_raw_abi_params, (account_name)(abi_hash) )
FC_REFLECT( eosio::chain_apis::read_only::get_raw_abi_results, (account_name)(code_hash)(abi_hash)(abi) )
FC_REFLECT( eosio::chain_apis::read_only::producer_info, (producer_name) )
FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) )
FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_result, (binargs) )
FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) )
FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_result, (args) )
FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_params, (transaction)(available_keys) )
FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_result, (required_keys) )
|
// Copyright (c) 2012, 2013 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#include "book/types.h"
#include "latency/clock_gettime.h"
#include "simple/simple_order_book.h"
#include <iostream>
#include <stdexcept>
#include <stdlib.h>
using namespace liquibook;
using namespace liquibook::book;
typedef simple::SimpleOrderBook<5> FullDepthOrderBook;
typedef simple::SimpleOrderBook<1> BboOrderBook;
typedef book::OrderBook<simple::SimpleOrder*> NoDepthOrderBook;
void build_histogram(timespec* timestamps, int count) {
timespec* prev = nullptr;
std::cout << "Latency (ns) " << std::endl;
for (timespec* timestamp = timestamps;
(timestamp - timestamps) <= count;
++timestamp)
{
if (prev) {
timespec elapsed;
if (timestamp->tv_sec == prev->tv_sec) {
elapsed.tv_sec = 0;
elapsed.tv_nsec = timestamp->tv_nsec - prev->tv_nsec;
} else {
// Second changed
elapsed.tv_sec = timestamp->tv_sec - prev->tv_sec;
// Borrow from sec if necessary
if (prev->tv_nsec > timestamp->tv_nsec) {
--elapsed.tv_sec;
elapsed.tv_nsec = 1000000000 + timestamp->tv_nsec - prev->tv_nsec;
} else {
elapsed.tv_nsec = timestamp->tv_nsec - prev->tv_nsec;
}
}
if (elapsed.tv_sec) {
std::cout << elapsed.tv_sec * 1000000000 + elapsed.tv_nsec << std::endl;
} else {
std::cout << elapsed.tv_nsec << std::endl;
}
}
prev = timestamp;
}
}
template <class TypedOrderBook, class TypedOrder>
int run_test(TypedOrderBook& order_book, TypedOrder** orders,
timespec* timestamps) {
int count = 0;
TypedOrder** pp_order = orders;
timespec* timestamp = timestamps;
do {
// Take timestamp at start of each order
int status = clock_gettime(CLOCK_REALTIME, timestamp);
if (status) {
throw std::runtime_error("clock_gettime() failed");
}
order_book.add(*pp_order);
++pp_order;
++timestamp;
if (*pp_order == nullptr) {
break;
}
++count;
} while (true);
// Take timestamp at end
int status = clock_gettime(CLOCK_REALTIME, timestamp);
if (status) {
throw std::runtime_error("clock_gettime() failed");
}
return int(pp_order - orders);
}
template <class TypedOrderBook>
bool build_and_run_test(uint32_t num_to_try, bool dry_run = false) {
TypedOrderBook order_book;
simple::SimpleOrder** orders = new simple::SimpleOrder*[num_to_try + 1];
timespec* timestamps = new timespec[num_to_try + 1];
for (uint32_t i = 0; i < num_to_try; ++i) {
bool is_buy((i % 2) == 0);
uint32_t delta = is_buy ? 1880 : 1884;
// AsSK 1893
// ASK 1892
// ASK 1891
// ASK 1890
// ASK 1889 crossable
// ASK 1888 crossable
// ASK 1887 crossable
// ASK 1886 crossable
// ASK 1885 crossable
// ASK 1884 crossable
// BID 1889 crossable
// BID 1888 crossable
// BID 1887 crossable
// BID 1886 crossable
// BID 1885 crossable
// BID 1884 crossable
// BID 1883
// BID 1882
// BID 1881
// BID 1880
Price price = (rand() % 10) + delta;
Quantity qty = ((rand() % 10) + 1) * 100;
orders[i] = new simple::SimpleOrder(is_buy, price, qty);
}
orders[num_to_try] = nullptr; // Final null
run_test(order_book, orders, timestamps);
for (uint32_t i = 0; i <= num_to_try; ++i) {
delete orders[i];
}
delete [] orders;
std::cout << " - complete!" << std::endl;
uint32_t remain = uint32_t(order_book.bids().size() + order_book.asks().size());
if (!dry_run) {
std::cout << "Building histogram" << std::endl;
build_histogram(timestamps, num_to_try);
}
delete [] timestamps;
return true;
}
int main(int argc, const char* argv[])
{
uint32_t num_to_try = 10000;
if (argc > 1) {
num_to_try = atoi(argv[1]);
if (!num_to_try) {
num_to_try = 10000;
}
}
std::cout << num_to_try << " order latency test of order book" << std::endl;
srand(num_to_try);
{
std::cout << "starting dry run" << std::endl;
build_and_run_test<FullDepthOrderBook>(num_to_try, true);
}
{
std::cout << "testing order book with depth" << std::endl;
build_and_run_test<FullDepthOrderBook>(num_to_try);
}
{
std::cout << "testing order book with bbo" << std::endl;
build_and_run_test<BboOrderBook>(num_to_try);
}
{
std::cout << "testing order book without depth" << std::endl;
build_and_run_test<NoDepthOrderBook>(num_to_try);
}
}
|
//CodeChef
//Beginner Practice Problem
//Chef and Remissness [REMISS]
#include <bits/stdc++.h>
using namespace std;
int main()
{
unsigned long long t=0;
cin>>t;
while(t--)
{
unsigned long long a=0,b=0;
cin>>a>>b;
if(b>a) {cout<<b<<" ";}
else {cout<<a<<" ";}
cout<<a+b<<"\n";
}
return 0;
}
|
// Copyright (c) 2018, Ryo Currency Project
// Portions copyright (c) 2014-2018, The Monero Project
//
// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details
// All rights reserved.
//
// Authors and copyright holders give permission for following:
//
// 1. Redistribution and use in source and binary forms WITHOUT modification.
//
// 2. Modification of the source form for your own personal use.
//
// As long as the following conditions are met:
//
// 3. You must not distribute modified copies of the to third parties. This includes
// posting the work online, or hosting copies of the modified work for download.
//
// 4. Any derivative version of this work is also covered by this license, including point 8.
//
// 5. Neither the name of the copyright holders nor the names of the authors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// 6. You agree that this licence is governed by and shall be construed in accordance
// with the laws of England and Wales.
//
// 7. You agree to submit all disputes arising out of or in connection with this licence
// to the exclusive jurisdiction of the Courts of England and Wales.
//
// Authors and copyright holders agree that:
//
// 8. This licence expires and the work covered by it is released into the
// public domain on 1st of February 2019
//
// 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.
/*!
* \file electrum-words.cpp
*
* \brief Mnemonic seed generation and wallet restoration from them.
*
* This file and its header file are for translating Electrum-style word lists
* into their equivalent byte representations for cross-compatibility with
* that method of "backing up" one's wallet keys.
*/
#include "mnemonics/electrum-words.h"
#include "crypto/crypto.h" // for declaration of crypto::secret_key
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/crc.hpp>
#include <boost/filesystem.hpp>
#include <cassert>
#include <cstdint>
#include <fstream>
#include <map>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "chinese_simplified.h"
#include "dutch.h"
#include "english.h"
#include "esperanto.h"
#include "french.h"
#include "german.h"
#include "italian.h"
#include "japanese.h"
#include "language_base.h"
#include "lojban.h"
#include "portuguese.h"
#include "russian.h"
#include "singleton.h"
#include "spanish.h"
/*!
* \namespace crypto
*
* \brief crypto namespace.
*/
namespace crypto
{
// Polynomial chosen using https://users.ece.cmu.edu/~koopman/crc/
// Params width=12 poly=0x987 init=0x000 refin=false refout=false xorout=0x000 check=0xf1a residue=0x000
const uint16_t crc12_table[256] = {
0x000, 0x987, 0xa89, 0x30e, 0xc95, 0x512, 0x61c, 0xf9b, 0x0ad, 0x92a, 0xa24, 0x3a3, 0xc38, 0x5bf, 0x6b1, 0xf36,
0x15a, 0x8dd, 0xbd3, 0x254, 0xdcf, 0x448, 0x746, 0xec1, 0x1f7, 0x870, 0xb7e, 0x2f9, 0xd62, 0x4e5, 0x7eb, 0xe6c,
0x2b4, 0xb33, 0x83d, 0x1ba, 0xe21, 0x7a6, 0x4a8, 0xd2f, 0x219, 0xb9e, 0x890, 0x117, 0xe8c, 0x70b, 0x405, 0xd82,
0x3ee, 0xa69, 0x967, 0x0e0, 0xf7b, 0x6fc, 0x5f2, 0xc75, 0x343, 0xac4, 0x9ca, 0x04d, 0xfd6, 0x651, 0x55f, 0xcd8,
0x568, 0xcef, 0xfe1, 0x666, 0x9fd, 0x07a, 0x374, 0xaf3, 0x5c5, 0xc42, 0xf4c, 0x6cb, 0x950, 0x0d7, 0x3d9, 0xa5e,
0x432, 0xdb5, 0xebb, 0x73c, 0x8a7, 0x120, 0x22e, 0xba9, 0x49f, 0xd18, 0xe16, 0x791, 0x80a, 0x18d, 0x283, 0xb04,
0x7dc, 0xe5b, 0xd55, 0x4d2, 0xb49, 0x2ce, 0x1c0, 0x847, 0x771, 0xef6, 0xdf8, 0x47f, 0xbe4, 0x263, 0x16d, 0x8ea,
0x686, 0xf01, 0xc0f, 0x588, 0xa13, 0x394, 0x09a, 0x91d, 0x62b, 0xfac, 0xca2, 0x525, 0xabe, 0x339, 0x037, 0x9b0,
0xad0, 0x357, 0x059, 0x9de, 0x645, 0xfc2, 0xccc, 0x54b, 0xa7d, 0x3fa, 0x0f4, 0x973, 0x6e8, 0xf6f, 0xc61, 0x5e6,
0xb8a, 0x20d, 0x103, 0x884, 0x71f, 0xe98, 0xd96, 0x411, 0xb27, 0x2a0, 0x1ae, 0x829, 0x7b2, 0xe35, 0xd3b, 0x4bc,
0x864, 0x1e3, 0x2ed, 0xb6a, 0x4f1, 0xd76, 0xe78, 0x7ff, 0x8c9, 0x14e, 0x240, 0xbc7, 0x45c, 0xddb, 0xed5, 0x752,
0x93e, 0x0b9, 0x3b7, 0xa30, 0x5ab, 0xc2c, 0xf22, 0x6a5, 0x993, 0x014, 0x31a, 0xa9d, 0x506, 0xc81, 0xf8f, 0x608,
0xfb8, 0x63f, 0x531, 0xcb6, 0x32d, 0xaaa, 0x9a4, 0x023, 0xf15, 0x692, 0x59c, 0xc1b, 0x380, 0xa07, 0x909, 0x08e,
0xee2, 0x765, 0x46b, 0xdec, 0x277, 0xbf0, 0x8fe, 0x179, 0xe4f, 0x7c8, 0x4c6, 0xd41, 0x2da, 0xb5d, 0x853, 0x1d4,
0xd0c, 0x48b, 0x785, 0xe02, 0x199, 0x81e, 0xb10, 0x297, 0xda1, 0x426, 0x728, 0xeaf, 0x134, 0x8b3, 0xbbd, 0x23a,
0xc56, 0x5d1, 0x6df, 0xf58, 0x0c3, 0x944, 0xa4a, 0x3cd, 0xcfb, 0x57c, 0x672, 0xff5, 0x06e, 0x9e9, 0xae7, 0x360};
inline void update_crc12(uint32_t &crcv, uint8_t data)
{
uint8_t idx = uint8_t((crcv >> 4) ^ data);
crcv = crc12_table[idx] ^ (crcv << 8);
}
uint32_t calc_crc12(const crypto::secret_key_16 &key, uint8_t extra)
{
uint32_t crcv = 0;
for(size_t i = 0; i < 16; i++)
update_crc12(crcv, tools::unwrap(key).data[i]);
update_crc12(crcv, extra);
return crcv & 0xfff;
}
/*!
* \namespace crypto::ElectrumWords
*
* \brief Mnemonic seed word generation and wallet restoration helper functions.
*/
/*!
* \brief Finds the word list that contains the seed words and puts the indices
* where matches occured in matched_indices.
* \param seed List of words to match.
* \param has_checksum The seed has a checksum word (maybe not checked).
* \param matched_indices The indices where the seed words were found are added to this.
* \param language Language instance pointer to write to after it is found.
* \return true if all the words were present in some language false if not.
*/
bool find_seed_language(const std::vector<std::string> &seed, Language::Base **language)
{
// Yes, I don't like std::pair
struct sort_pair
{
Language::Base *inst;
size_t score;
inline bool operator<(const sort_pair &oth) { return score < oth.score; }
};
// If there's a new language added, add an instance of it here.
std::vector<sort_pair> language_instances({{Language::Singleton<Language::Chinese_Simplified>::instance(), 0},
{Language::Singleton<Language::English>::instance(), 0},
{Language::Singleton<Language::Dutch>::instance(), 0},
{Language::Singleton<Language::French>::instance(), 0},
{Language::Singleton<Language::Spanish>::instance(), 0},
{Language::Singleton<Language::German>::instance(), 0},
{Language::Singleton<Language::Italian>::instance(), 0},
{Language::Singleton<Language::Portuguese>::instance(), 0},
{Language::Singleton<Language::Japanese>::instance(), 0},
{Language::Singleton<Language::Russian>::instance(), 0},
{Language::Singleton<Language::Esperanto>::instance(), 0},
{Language::Singleton<Language::Lojban>::instance(), 0}});
// Assumption here is that the end user will spell more words correctly than get at random in a foreign lang
for(sort_pair &pair : language_instances)
{
const std::unordered_map<std::string, uint32_t> &word_map = pair.inst->get_word_map();
for(const std::string &word : seed)
{
if(word_map.count(word) > 0)
pair.score++;
}
}
std::sort(language_instances.begin(), language_instances.end());
if(language_instances.back().score > 0)
{
*language = language_instances.back().inst;
return true;
}
return false;
}
bool match_words(const Language::Base &lang, const std::vector<std::string> &seed, std::vector<uint32_t> &matched_indices)
{
size_t trim_size = lang.get_unique_prefix_length();
const std::unordered_map<std::string, uint32_t> &trimmed_word_map = lang.get_trimmed_word_map();
matched_indices.reserve(seed.size());
for(const std::string &word : seed)
{
std::string trimmed_word = Language::utf8prefix(word, trim_size);
if(trimmed_word_map.count(trimmed_word) > 0)
matched_indices.push_back(trimmed_word_map.at(trimmed_word));
else
return false;
}
return true;
}
namespace Electrum
{
/*!
* \brief Gets a list of seed languages that are supported.
* \param languages The vector is set to the list of languages.
*/
const std::vector<const Language::Base *> &get_language_list()
{
static const std::vector<const Language::Base *> language_instances({Language::Singleton<Language::German>::instance(),
Language::Singleton<Language::English>::instance(),
Language::Singleton<Language::Spanish>::instance(),
Language::Singleton<Language::French>::instance(),
Language::Singleton<Language::Italian>::instance(),
Language::Singleton<Language::Dutch>::instance(),
Language::Singleton<Language::Portuguese>::instance(),
Language::Singleton<Language::Russian>::instance(),
Language::Singleton<Language::Japanese>::instance(),
Language::Singleton<Language::Chinese_Simplified>::instance(),
Language::Singleton<Language::Esperanto>::instance(),
Language::Singleton<Language::Lojban>::instance()});
return language_instances;
}
void get_language_list(std::vector<std::string> &languages, bool english)
{
const std::vector<const Language::Base *> language_instances = get_language_list();
for(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();
it != language_instances.end(); it++)
{
languages.push_back(english ? (*it)->get_english_language_name() : (*it)->get_language_name());
}
}
std::string get_english_name_for(const std::string &name)
{
const std::vector<const Language::Base *> language_instances = get_language_list();
for(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();
it != language_instances.end(); it++)
{
if((*it)->get_language_name() == name)
return (*it)->get_english_language_name();
}
return "<language not found>";
}
}
namespace Electrum14Words
{
bool words_to_bytes(std::string words, crypto::secret_key_16 &dst, uint8_t &extra, std::string &language_name)
{
std::vector<std::string> seed;
boost::algorithm::trim(words);
boost::split(seed, words, boost::is_any_of(" "), boost::token_compress_on);
if(seed.size() != 14 && seed.size() != 12)
return false;
Language::Base *language;
if(!find_seed_language(seed, &language))
return false;
std::vector<uint32_t> matched_indices;
if(!match_words(*language, seed, matched_indices))
return false;
language_name = language->get_language_name();
uint32_t word_list_length = language->get_word_list().size();
uint32_t *out = (uint32_t *)tools::unwrap(dst).data;
for(unsigned int i = 0; i < seed.size() / 3; i++)
{
uint32_t val;
uint32_t w1, w2, w3;
w1 = matched_indices[i * 3];
w2 = matched_indices[i * 3 + 1];
w3 = matched_indices[i * 3 + 2];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +
word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);
if(!(val % word_list_length == w1))
return false;
out[i] = val;
}
if(seed.size() == 14)
{
uint32_t val;
uint32_t w1, w2;
w1 = matched_indices[12];
w2 = matched_indices[13];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length);
val &= 0xfffff; // 20 bytes
extra = uint8_t(val & 0xff);
val >>= 8;
if(calc_crc12(dst, extra) != val)
return false;
}
return true;
}
bool bytes_to_words(const crypto::secret_key_16 &src, uint8_t extra, std::string &words, const std::string &language_name)
{
const std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();
const Language::Base *language = nullptr;
for(const Language::Base *b : lng_insts)
{
if(b->get_language_name() == language_name || b->get_english_language_name() == language_name)
{
language = b;
break;
}
}
if(language == nullptr)
return false;
const std::vector<std::string> &word_list = language->get_word_list();
uint32_t word_list_length = word_list.size();
const uint32_t *psrc = (const uint32_t *)tools::unwrap(src).data;
for(unsigned int i = 0; i < 4; i++, words += ' ')
{
uint32_t w1, w2, w3;
uint32_t val = psrc[i];
w1 = val % word_list_length;
w2 = ((val / word_list_length) + w1) % word_list_length;
w3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
words += ' ';
words += word_list[w3];
}
uint32_t w1, w2;
uint32_t checksum = calc_crc12(src, extra);
checksum <<= 8;
checksum |= extra;
w1 = checksum % word_list_length;
w2 = ((checksum / word_list_length) + w1) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
return true;
}
}
namespace Electrum25Words
{
/*!
* \brief Creates a checksum index in the word list array on the list of words.
* \param word_list Vector of words
* \param unique_prefix_length the prefix length of each word to use for checksum
* \return Checksum index
*/
uint32_t create_checksum_index(const std::vector<std::string> &word_list, uint32_t unique_prefix_length)
{
std::string trimmed_words = "";
for(std::vector<std::string>::const_iterator it = word_list.begin(); it != word_list.end(); it++)
{
if(it->length() > unique_prefix_length)
{
trimmed_words += Language::utf8prefix(*it, unique_prefix_length);
}
else
{
trimmed_words += *it;
}
}
boost::crc_32_type result;
result.process_bytes(trimmed_words.data(), trimmed_words.length());
return result.checksum() % seed_length;
}
/*!
* \brief Does the checksum test on the seed passed.
* \param seed Vector of seed words
* \param unique_prefix_length the prefix length of each word to use for checksum
* \return True if the test passed false if not.
*/
bool checksum_test(std::vector<std::string> seed, uint32_t unique_prefix_length)
{
if(seed.empty())
return false;
// The last word is the checksum.
std::string last_word = seed.back();
seed.pop_back();
std::string checksum = seed[create_checksum_index(seed, unique_prefix_length)];
std::string trimmed_checksum = checksum.length() > unique_prefix_length ? Language::utf8prefix(checksum, unique_prefix_length) : checksum;
std::string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) : last_word;
return trimmed_checksum == trimmed_last_word;
}
/*!
* \brief Converts seed words to bytes (secret key).
* \param words String containing the words separated by spaces.
* \param dst To put the secret data restored from the words.
* \param len The number of bytes to expect, 0 if unknown
* \param duplicate If true and len is not zero, we accept half the data, and duplicate it
* \param language_name Language of the seed as found gets written here.
* \return false if not a multiple of 3 words, or if word is not in the words list
*/
bool words_to_bytes(std::string words, std::string &dst, size_t len, std::string &language_name)
{
std::vector<std::string> seed;
boost::algorithm::trim(words);
boost::split(seed, words, boost::is_any_of(" "), boost::token_compress_on);
if(len % 4)
return false;
if(seed.size() == 26) //Last word is a funky sumo attempt at a second checksum, ignore it
seed.pop_back();
bool has_checksum = true;
if(len)
{
// error on non-compliant word list
const size_t expected = len * 8 * 3 / 32;
if(seed.size() != expected / 2 && seed.size() != expected && seed.size() != expected + 1)
return false;
// If it is seed with a checksum.
has_checksum = seed.size() == (expected + 1);
}
Language::Base *language;
if(!find_seed_language(seed, &language))
return false;
std::vector<uint32_t> matched_indices;
if(!match_words(*language, seed, matched_indices))
return false;
language_name = language->get_language_name();
uint32_t word_list_length = language->get_word_list().size();
if(has_checksum)
{
if(!checksum_test(seed, language->get_unique_prefix_length()))
{
// Checksum fail
return false;
}
seed.pop_back();
}
for(unsigned int i = 0; i < seed.size() / 3; i++)
{
uint32_t val;
uint32_t w1, w2, w3;
w1 = matched_indices[i * 3];
w2 = matched_indices[i * 3 + 1];
w3 = matched_indices[i * 3 + 2];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +
word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);
if(!(val % word_list_length == w1))
return false;
dst.append((const char *)&val, 4); // copy 4 bytes to position
}
return true;
}
/*!
* \brief Converts seed words to bytes (secret key).
* \param words String containing the words separated by spaces.
* \param dst To put the secret key restored from the words.
* \param language_name Language of the seed as found gets written here.
* \return false if not a multiple of 3 words, or if word is not in the words list
*/
bool words_to_bytes(std::string words, crypto::secret_key &dst, std::string &language_name)
{
std::string s;
if(!words_to_bytes(words, s, sizeof(dst), language_name))
return false;
if(s.size() != sizeof(dst))
return false;
dst = *(const crypto::secret_key *)s.data();
return true;
}
/*!
* \brief Converts bytes (secret key) to seed words.
* \param src Secret key
* \param words Space delimited concatenated words get written here.
* \param language_name Seed language name
* \return true if successful false if not. Unsuccessful if wrong key size.
*/
bool bytes_to_words(const char *src, size_t len, std::string &words, const std::string &language_name)
{
if(len % 4 != 0 || len == 0)
return false;
const std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();
const Language::Base *language = nullptr;
for(const Language::Base *b : lng_insts)
{
if(b->get_language_name() == language_name || b->get_english_language_name() == language_name)
{
language = b;
break;
}
}
if(language == nullptr)
return false;
const std::vector<std::string> &word_list = language->get_word_list();
// To store the words for random access to add the checksum word later.
std::vector<std::string> words_store;
uint32_t word_list_length = word_list.size();
// 4 bytes -> 3 words. 8 digits base 16 -> 3 digits base 1626
for(unsigned int i = 0; i < len / 4; i++, words += ' ')
{
uint32_t w1, w2, w3;
uint32_t val;
memcpy(&val, src + (i * 4), 4);
w1 = val % word_list_length;
w2 = ((val / word_list_length) + w1) % word_list_length;
w3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
words += ' ';
words += word_list[w3];
words_store.push_back(word_list[w1]);
words_store.push_back(word_list[w2]);
words_store.push_back(word_list[w3]);
}
words.pop_back();
words += (' ' + words_store[create_checksum_index(words_store, language->get_unique_prefix_length())]);
return true;
}
bool bytes_to_words(const crypto::secret_key &src, std::string &words, const std::string &language_name)
{
return bytes_to_words(src.data, sizeof(src), words, language_name);
}
}
}
|
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int i=2;
for(;i<=n-1;i++){
if(n%i==0){
cout<<n<<" is not Prime"<<endl;
break;
}
}
if(i==n){
cout<<n<<" is prime"<<endl;
}
}
|
//
// Created by aicdg on 2017/6/20.
//
//
// Chapter: 03 Command Buffers and Synchronization
// Recipe: 04 Ending a command buffer recording operation
#include "S04_Ending_a_command_buffer_recording_operation.h"
namespace VKCookbook {
bool EndCommandBufferRecordingOperation( VkCommandBuffer command_buffer ) {
VkResult result = vkEndCommandBuffer( command_buffer );
if( VK_SUCCESS != result ) {
std::cout << "Error occurred during command buffer recording." << std::endl;
return false;
}
return true;
}
}
|
// Dear ImGui: standalone example application for DirectX 12
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// FIXME: 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*))
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx12.h"
#include <d3d12.h>
#include <dxgi1_4.h>
#include <tchar.h>
#ifdef _DEBUG
#define DX12_ENABLE_DEBUG_LAYER
#endif
#ifdef DX12_ENABLE_DEBUG_LAYER
#include <dxgidebug.h>
#pragma comment(lib, "dxguid.lib")
#endif
struct FrameContext
{
ID3D12CommandAllocator* CommandAllocator;
UINT64 FenceValue;
};
// Data
static int const NUM_FRAMES_IN_FLIGHT = 3;
static FrameContext g_frameContext[NUM_FRAMES_IN_FLIGHT] = {};
static UINT g_frameIndex = 0;
static int const NUM_BACK_BUFFERS = 3;
static ID3D12Device* g_pd3dDevice = NULL;
static ID3D12DescriptorHeap* g_pd3dRtvDescHeap = NULL;
static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL;
static ID3D12CommandQueue* g_pd3dCommandQueue = NULL;
static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL;
static ID3D12Fence* g_fence = NULL;
static HANDLE g_fenceEvent = NULL;
static UINT64 g_fenceLastSignaledValue = 0;
static IDXGISwapChain3* g_pSwapChain = NULL;
static HANDLE g_hSwapChainWaitableObject = NULL;
static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
void WaitForLastSubmittedFrame();
FrameContext* WaitForNextFrameResources();
void ResizeSwapChain(HWND hWnd, int width, int height);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
//io.ConfigViewportsNoAutoMerge = true;
//io.ConfigViewportsNoTaskBarIcon = true;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT,
DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap,
g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL);
// Our state
bool show_demo_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
// Poll and handle messages (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX12_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
// Rendering
FrameContext* frameCtxt = WaitForNextFrameResources();
UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex();
frameCtxt->CommandAllocator->Reset();
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx];
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
g_pd3dCommandList->Reset(frameCtxt->CommandAllocator, NULL);
g_pd3dCommandList->ResourceBarrier(1, &barrier);
g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], (float*)&clear_color, 0, NULL);
g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL);
g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap);
ImGui::Render();
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList);
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
g_pd3dCommandList->ResourceBarrier(1, &barrier);
g_pd3dCommandList->Close();
g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList);
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault(NULL, (void*)g_pd3dCommandList);
}
g_pSwapChain->Present(1, 0); // Present with vsync
//g_pSwapChain->Present(0, 0); // Present without vsync
UINT64 fenceValue = g_fenceLastSignaledValue + 1;
g_pd3dCommandQueue->Signal(g_fence, fenceValue);
g_fenceLastSignaledValue = fenceValue;
frameCtxt->FenceValue = fenceValue;
}
WaitForLastSubmittedFrame();
ImGui_ImplDX12_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC1 sd;
{
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = NUM_BACK_BUFFERS;
sd.Width = 0;
sd.Height = 0;
sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
sd.Scaling = DXGI_SCALING_STRETCH;
sd.Stereo = FALSE;
}
// [DEBUG] Enable debug interface
#ifdef DX12_ENABLE_DEBUG_LAYER
ID3D12Debug* pdx12Debug = NULL;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pdx12Debug))))
pdx12Debug->EnableDebugLayer();
#endif
// Create device
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK)
return false;
// [DEBUG] Setup debug interface to break on any warnings/errors
#ifdef DX12_ENABLE_DEBUG_LAYER
if (pdx12Debug != NULL)
{
ID3D12InfoQueue* pInfoQueue = NULL;
g_pd3dDevice->QueryInterface(IID_PPV_ARGS(&pInfoQueue));
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true);
pInfoQueue->Release();
pdx12Debug->Release();
}
#endif
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
desc.NumDescriptors = NUM_BACK_BUFFERS;
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
desc.NodeMask = 1;
if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
return false;
SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
{
g_mainRenderTargetDescriptor[i] = rtvHandle;
rtvHandle.ptr += rtvDescriptorSize;
}
}
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
desc.NumDescriptors = 1;
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
return false;
}
{
D3D12_COMMAND_QUEUE_DESC desc = {};
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 1;
if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK)
return false;
}
for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
return false;
if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK ||
g_pd3dCommandList->Close() != S_OK)
return false;
if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK)
return false;
g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (g_fenceEvent == NULL)
return false;
{
IDXGIFactory4* dxgiFactory = NULL;
IDXGISwapChain1* swapChain1 = NULL;
if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK ||
dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1) != S_OK ||
swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK)
return false;
swapChain1->Release();
dxgiFactory->Release();
g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
}
CreateRenderTarget();
return true;
}
void CleanupDeviceD3D()
{
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
if (g_hSwapChainWaitableObject != NULL) { CloseHandle(g_hSwapChainWaitableObject); }
for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = NULL; }
if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = NULL; }
if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = NULL; }
if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = NULL; }
if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = NULL; }
if (g_fence) { g_fence->Release(); g_fence = NULL; }
if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = NULL; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
#ifdef DX12_ENABLE_DEBUG_LAYER
IDXGIDebug1* pDebug = NULL;
if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug))))
{
pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_SUMMARY);
pDebug->Release();
}
#endif
}
void CreateRenderTarget()
{
for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
{
ID3D12Resource* pBackBuffer = NULL;
g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]);
g_mainRenderTargetResource[i] = pBackBuffer;
}
}
void CleanupRenderTarget()
{
WaitForLastSubmittedFrame();
for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; }
}
void WaitForLastSubmittedFrame()
{
FrameContext* frameCtxt = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT];
UINT64 fenceValue = frameCtxt->FenceValue;
if (fenceValue == 0)
return; // No fence was signaled
frameCtxt->FenceValue = 0;
if (g_fence->GetCompletedValue() >= fenceValue)
return;
g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
WaitForSingleObject(g_fenceEvent, INFINITE);
}
FrameContext* WaitForNextFrameResources()
{
UINT nextFrameIndex = g_frameIndex + 1;
g_frameIndex = nextFrameIndex;
HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL };
DWORD numWaitableObjects = 1;
FrameContext* frameCtxt = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT];
UINT64 fenceValue = frameCtxt->FenceValue;
if (fenceValue != 0) // means no fence was signaled
{
frameCtxt->FenceValue = 0;
g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
waitableObjects[1] = g_fenceEvent;
numWaitableObjects = 2;
}
WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE);
return frameCtxt;
}
void ResizeSwapChain(HWND hWnd, int width, int height)
{
DXGI_SWAP_CHAIN_DESC1 sd;
g_pSwapChain->GetDesc1(&sd);
sd.Width = width;
sd.Height = height;
IDXGIFactory4* dxgiFactory = NULL;
g_pSwapChain->GetParent(IID_PPV_ARGS(&dxgiFactory));
g_pSwapChain->Release();
CloseHandle(g_hSwapChainWaitableObject);
IDXGISwapChain1* swapChain1 = NULL;
dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1);
swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain));
swapChain1->Release();
dxgiFactory->Release();
g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
assert(g_hSwapChainWaitableObject != NULL);
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
WaitForLastSubmittedFrame();
ImGui_ImplDX12_InvalidateDeviceObjects();
CleanupRenderTarget();
ResizeSwapChain(hWnd, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam));
CreateRenderTarget();
ImGui_ImplDX12_CreateDeviceObjects();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
|
// Copyright 2013 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 "content/browser/frame_host/render_frame_host_delegate.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/strings/string16.h"
#include "build/build_config.h"
#include "ipc/ipc_message.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
#include "ui/gfx/native_widget_types.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace content {
bool RenderFrameHostDelegate::OnMessageReceived(
RenderFrameHostImpl* render_frame_host,
const IPC::Message& message) {
return false;
}
const GURL& RenderFrameHostDelegate::GetMainFrameLastCommittedURL() {
return GURL::EmptyGURL();
}
bool RenderFrameHostDelegate::DidAddMessageToConsole(
blink::mojom::ConsoleMessageLevel log_level,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) {
return false;
}
void RenderFrameHostDelegate::RunFileChooser(
RenderFrameHost* render_frame_host,
std::unique_ptr<FileChooserImpl::FileSelectListenerImpl> listener,
const blink::mojom::FileChooserParams& params) {
listener->FileSelectionCanceled();
}
void RenderFrameHostDelegate::EnumerateDirectory(
RenderFrameHost* render_frame_host,
std::unique_ptr<FileChooserImpl::FileSelectListenerImpl> listener,
const base::FilePath& path) {
listener->FileSelectionCanceled();
}
WebContents* RenderFrameHostDelegate::GetAsWebContents() {
return nullptr;
}
InterstitialPage* RenderFrameHostDelegate::GetAsInterstitialPage() {
return nullptr;
}
void RenderFrameHostDelegate::RequestMediaAccessPermission(
const MediaStreamRequest& request,
MediaResponseCallback callback) {
LOG(ERROR) << "RenderFrameHostDelegate::RequestMediaAccessPermission: "
<< "Not supported.";
std::move(callback).Run(blink::MediaStreamDevices(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED,
std::unique_ptr<MediaStreamUI>());
}
bool RenderFrameHostDelegate::CheckMediaAccessPermission(
RenderFrameHost* render_frame_host,
const url::Origin& security_origin,
blink::mojom::MediaStreamType type) {
LOG(ERROR) << "RenderFrameHostDelegate::CheckMediaAccessPermission: "
<< "Not supported.";
return false;
}
std::string RenderFrameHostDelegate::GetDefaultMediaDeviceID(
blink::mojom::MediaStreamType type) {
return std::string();
}
ui::AXMode RenderFrameHostDelegate::GetAccessibilityMode() {
return ui::AXMode();
}
RenderFrameHost* RenderFrameHostDelegate::GetGuestByInstanceID(
RenderFrameHost* render_frame_host,
int browser_plugin_instance_id) {
return nullptr;
}
device::mojom::GeolocationContext*
RenderFrameHostDelegate::GetGeolocationContext() {
return nullptr;
}
#if defined(OS_ANDROID)
void RenderFrameHostDelegate::GetNFC(
RenderFrameHost* render_frame_host,
mojo::PendingReceiver<device::mojom::NFC> receiver) {}
#endif
bool RenderFrameHostDelegate::CanEnterFullscreenMode() {
return true;
}
bool RenderFrameHostDelegate::ShouldRouteMessageEvent(
RenderFrameHost* target_rfh,
SiteInstance* source_site_instance) const {
return false;
}
RenderFrameHost*
RenderFrameHostDelegate::GetFocusedFrameIncludingInnerWebContents() {
return nullptr;
}
RenderFrameHostImpl* RenderFrameHostDelegate::GetMainFrame() {
return nullptr;
}
std::unique_ptr<WebUIImpl>
RenderFrameHostDelegate::CreateWebUIForRenderFrameHost(const GURL& url) {
return nullptr;
}
RenderFrameHostDelegate* RenderFrameHostDelegate::CreateNewWindow(
RenderFrameHost* opener,
const mojom::CreateNewWindowParams& params,
bool is_new_browsing_instance,
bool has_user_gesture,
SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
bool RenderFrameHostDelegate::ShouldAllowRunningInsecureContent(
WebContents* web_contents,
bool allowed_per_prefs,
const url::Origin& origin,
const GURL& resource_url) {
return false;
}
#if defined(OS_ANDROID)
base::android::ScopedJavaLocalRef<jobject>
RenderFrameHostDelegate::GetJavaRenderFrameHostDelegate() {
return nullptr;
}
#endif
bool RenderFrameHostDelegate::IsBeingDestroyed() {
return false;
}
Visibility RenderFrameHostDelegate::GetVisibility() {
return Visibility::HIDDEN;
}
ukm::SourceId RenderFrameHostDelegate::
GetUkmSourceIdForLastCommittedSourceIncludingSameDocument() const {
return ukm::kInvalidSourceId;
}
RenderFrameHostImpl* RenderFrameHostDelegate::GetMainFrameForInnerDelegate(
FrameTreeNode* frame_tree_node) {
return nullptr;
}
media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
RenderFrameHostDelegate::GetRecordAggregateWatchTimeCallback() {
return base::NullCallback();
}
bool RenderFrameHostDelegate::IsFrameLowPriority(
const RenderFrameHost* render_frame_host) {
return false;
}
void RenderFrameHostDelegate::IsClipboardPasteAllowed(
const GURL& url,
const ui::ClipboardFormatType& data_type,
const std::string& data,
IsClipboardPasteAllowedCallback callback) {
std::move(callback).Run(ClipboardPasteAllowed(true));
}
bool RenderFrameHostDelegate::HasSeenRecentScreenOrientationChange() {
return false;
}
} // namespace content
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* 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 name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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.
***********************************************************************************************************************/
#include "../ForwardTranslator.hpp"
#include "../../model/Model.hpp"
#include "../../model/OutputVariable.hpp"
#include "../../model/OutputVariable_Impl.hpp"
#include "../../model/OutputMeter.hpp"
#include "../../model/OutputMeter_Impl.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
#include "../../model/EnergyManagementSystemInternalVariable.hpp"
#include "../../model/EnergyManagementSystemInternalVariable_Impl.hpp"
#include <utilities/idd/EnergyManagementSystem_InternalVariable_FieldEnums.hxx>
#include "../../utilities/idd/IddEnums.hpp"
#include <utilities/idd/IddEnums.hxx>
using namespace openstudio::model;
using namespace std;
namespace openstudio {
namespace energyplus {
boost::optional<IdfObject> ForwardTranslator::translateEnergyManagementSystemInternalVariable(EnergyManagementSystemInternalVariable& modelObject) {
boost::optional<int> i;
boost::optional<std::string> s;
IdfObject idfObject(openstudio::IddObjectType::EnergyManagementSystem_InternalVariable);
m_idfObjects.push_back(idfObject);
//Name
s = modelObject.name();
if (s) {
idfObject.setName(*s);
}
// look for UID and if found replace with object name; otherwise just use string value
s = modelObject.internalDataIndexKeyName();
if (s) {
//find uids
const int subs[] = {1};
std::string newline = s.get();
std::string possible_uid;
size_t pos;
bool is_uuid = false;
const Model m = modelObject.model();
boost::optional<ModelObject> mObject;
boost::sregex_token_iterator j(s.get().begin(), s.get().end(), uuidInString(), subs);
while (j != boost::sregex_token_iterator()) {
possible_uid = *j++;
//look to see if uid is in the model and return the object
UUID uid = toUUID(possible_uid);
mObject = m.getModelObject<model::ModelObject>(uid);
if (mObject) {
is_uuid = true;
//replace uid with namestring
pos = newline.find(possible_uid);
if (pos + 38 <= newline.length()) {
newline.replace(pos, 38, mObject.get().nameString());
idfObject.setString(EnergyManagementSystem_InternalVariableFields::InternalDataIndexKeyName, newline);
}
} else {
//did not find an object with the UID so do not FT
LOG(Error, "InternalIndexDataKeyName for EMS:InternalVariable '" << modelObject.nameString()
<< "' is UID but does not exist, it will not be translated.");
return boost::none;
}
}
//string is not a uuid so just translate its value for the EMSVariableName
if (!is_uuid) {
idfObject.setString(EnergyManagementSystem_InternalVariableFields::InternalDataIndexKeyName, s.get());
}
}
s = modelObject.internalDataType();
if (s) {
idfObject.setString(EnergyManagementSystem_InternalVariableFields::InternalDataType, s.get());
}
return idfObject;
}
} // namespace energyplus
} // namespace openstudio
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020-2021 Couchbase, 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.
*/
#pragma once
#include <couchbase/io/mcbp_message.hxx>
#include <couchbase/protocol/client_opcode.hxx>
#include <couchbase/protocol/cmd_info.hxx>
#include <couchbase/protocol/status.hxx>
#include <couchbase/topology/error_map.hxx>
namespace couchbase::protocol
{
class get_error_map_response_body
{
public:
static const inline client_opcode opcode = client_opcode::get_error_map;
private:
error_map errmap_{};
public:
[[nodiscard]] const couchbase::error_map& errmap() const
{
return errmap_;
}
bool parse(protocol::status status,
const header_buffer& header,
std::uint8_t framing_extras_size,
std::uint16_t key_size,
std::uint8_t extras_size,
const std::vector<uint8_t>& body,
const cmd_info& info);
};
class get_error_map_request_body
{
public:
using response_body_type = get_error_map_response_body;
static const inline client_opcode opcode = client_opcode::get_error_map;
private:
std::uint16_t version_{ 2 };
std::vector<std::uint8_t> value_;
public:
void version(std::uint16_t version)
{
version_ = version;
}
[[nodiscard]] const std::string& key() const
{
return empty_string;
}
[[nodiscard]] const std::vector<std::uint8_t>& framing_extras() const
{
return empty_buffer;
}
[[nodiscard]] const std::vector<std::uint8_t>& extras() const
{
return empty_buffer;
}
[[nodiscard]] const std::vector<std::uint8_t>& value()
{
if (value_.empty()) {
fill_body();
}
return value_;
}
[[nodiscard]] std::size_t size()
{
if (value_.empty()) {
fill_body();
}
return value_.size();
}
private:
void fill_body();
};
} // namespace couchbase::protocol
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <wallet/db.h>
#include <addrman.h>
#include <hash.h>
#include <protocol.h>
#include <util.h>
#include <utilstrencodings.h>
#include <wallet/walletutil.h>
#include <stdint.h>
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/thread.hpp>
namespace {
//! Make sure database has a unique fileid within the environment. If it
//! doesn't, throw an error. BDB caches do not work properly when more than one
//! open database has the same fileid (values written to one database may show
//! up in reads to other databases).
//!
//! BerkeleyDB generates unique fileids by default
//! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html),
//! so bitcoin should never create different databases with the same fileid, but
//! this error can be triggered if users manually copy database files.
void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db)
{
if (env.IsMock()) return;
u_int8_t fileid[DB_FILE_ID_LEN];
int ret = db.get_mpf()->get_fileid(fileid);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Can't open database %s (get_fileid failed with %d)", filename, ret));
}
for (const auto& item : env.mapDb) {
u_int8_t item_fileid[DB_FILE_ID_LEN];
if (item.second && item.second->get_mpf()->get_fileid(item_fileid) == 0 &&
memcmp(fileid, item_fileid, sizeof(fileid)) == 0) {
const char* item_filename = nullptr;
item.second->get_dbname(&item_filename, nullptr);
throw std::runtime_error(strprintf("CDB: Can't open database %s (duplicates fileid %s from %s)", filename,
HexStr(std::begin(item_fileid), std::end(item_fileid)),
item_filename ? item_filename : "(unknown database)"));
}
}
}
} // namespace
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv->close(0);
if (ret != 0)
LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv((u_int32_t)0).remove(strPath.c_str(), 0);
}
void CDBEnv::Reset()
{
dbenv.reset(new DbEnv(DB_CXX_NO_EXCEPTIONS));
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::CDBEnv()
{
Reset();
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(const fs::path& pathIn, bool retry)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
strPath = pathIn.string();
if (!LockDirectory(pathIn, ".walletlock")) {
LogPrintf("Cannot obtain a lock on wallet directory %s. Another instance of dommecoin may be using it.\n", strPath);
return false;
}
fs::path pathLogDir = pathIn / "database";
TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
nEnvFlags |= DB_PRIVATE;
dbenv->set_lg_dir(pathLogDir.string().c_str());
dbenv->set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
dbenv->set_lg_bsize(0x10000);
dbenv->set_lg_max(1048576);
dbenv->set_lk_max_locks(40000);
dbenv->set_lk_max_objects(40000);
dbenv->set_errfile(fsbridge::fopen(pathErrorFile, "a")); /// debug
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->set_flags(DB_TXN_WRITE_NOSYNC, 1);
dbenv->log_set_config(DB_LOG_AUTO_REMOVE, 1);
int ret = dbenv->open(strPath.c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0) {
dbenv->close(0);
LogPrintf("CDBEnv::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
if (retry) {
// try moving the database env out of the way
fs::path pathDatabaseBak = pathIn / strprintf("database.%d.bak", GetTime());
try {
fs::rename(pathLogDir, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathLogDir.string(), pathDatabaseBak.string());
} catch (const fs::filesystem_error&) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try opening it again one more time
if (!Open(pathIn, false)) {
// if it still fails, it probably means we can't even create the database env
return false;
}
} else {
return false;
}
}
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw std::runtime_error("CDBEnv::MakeMock: Already initialized");
boost::this_thread::interruption_point();
LogPrint(BCLog::DB, "CDBEnv::MakeMock\n");
dbenv->set_cachesize(1, 0, 1);
dbenv->set_lg_bsize(10485760 * 4);
dbenv->set_lg_max(10485760);
dbenv->set_lk_max_locks(10000);
dbenv->set_lk_max_objects(10000);
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv->open(nullptr,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw std::runtime_error(strprintf("CDBEnv::MakeMock: Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, nullptr, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == nullptr)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(strFile, out_backup_filename);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
{
// Recovery procedure:
// move wallet file to walletfilename.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to fresh wallet file
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
newFilename = strprintf("%s.%d.bak", filename, now);
int result = bitdb.dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool fSuccess = bitdb.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(bitdb.dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
pdbCopy->close(0);
return false;
}
DbTxn* ptxn = bitdb.TxnBegin();
for (CDBEnv::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue))
continue;
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
bool CDB::VerifyEnvironment(const std::string& walletFile, const fs::path& walletDir, std::string& errorStr)
{
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
LogPrintf("Using wallet %s\n", walletFile);
// Wallet file must be a plain filename without a directory
if (walletFile != fs::basename(walletFile) + fs::extension(walletFile))
{
errorStr = strprintf(_("Wallet %s resides outside wallet directory %s"), walletFile, walletDir.string());
return false;
}
if (!bitdb.Open(walletDir, true)) {
errorStr = strprintf(_("Error initializing wallet database environment %s!"), walletDir);
return false;
}
return true;
}
bool CDB::VerifyDatabaseFile(const std::string& walletFile, const fs::path& walletDir, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc)
{
if (fs::exists(walletDir / walletFile))
{
std::string backup_filename;
CDBEnv::VerifyResult r = bitdb.Verify(walletFile, recoverFunc, backup_filename);
if (r == CDBEnv::RECOVER_OK)
{
warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."),
walletFile, backup_filename, walletDir);
}
if (r == CDBEnv::RECOVER_FAIL)
{
errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile);
return false;
}
}
// also return true if files does not exists
return true;
}
/* End of headers, beginning of key/value data */
static const char *HEADER_END = "HEADER=END";
/* End of key/value data */
static const char *DATA_END = "DATA=END";
bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<CDBEnv::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive)
flags |= DB_AGGRESSIVE;
std::stringstream strDump;
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
LogPrintf("CDBEnv::Salvage: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage: Database salvage failed with result %d.\n", result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
std::string strLine;
while (!strDump.eof() && strLine != HEADER_END)
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != DATA_END) {
getline(strDump, keyHex);
if (keyHex != DATA_END) {
if (strDump.eof())
break;
getline(strDump, valueHex);
if (valueHex == DATA_END) {
LogPrintf("CDBEnv::Salvage: WARNING: Number of keys in data does not match number of values.\n");
break;
}
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
}
}
if (keyHex != DATA_END) {
LogPrintf("CDBEnv::Salvage: WARNING: Unexpected end of file while reading salvage output.\n");
return false;
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv->txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv->lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
fFlushOnClose = fFlushOnCloseIn;
env = dbw.env;
if (dbw.IsDummy()) {
return;
}
const std::string &strFilename = dbw.strFile;
bool fCreate = strchr(pszMode, 'c') != nullptr;
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(env->cs_db);
if (!env->Open(GetWalletDir()))
throw std::runtime_error("CDB: Failed to open database environment.");
pdb = env->mapDb[strFilename];
if (pdb == nullptr) {
int ret;
std::unique_ptr<Db> pdb_temp = MakeUnique<Db>(env->dbenv.get(), 0);
bool fMockDb = env->IsMock();
if (fMockDb) {
DbMpoolFile* mpf = pdb_temp->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFilename));
}
}
ret = pdb_temp->open(nullptr, // Txn pointer
fMockDb ? nullptr : strFilename.c_str(), // Filename
fMockDb ? strFilename.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
}
CheckUniqueFileid(*env, strFilename, *pdb_temp);
pdb = pdb_temp.release();
env->mapDb[strFilename] = pdb;
if (fCreate && !Exists(std::string("version"))) {
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
}
++env->mapFileUseCount[strFilename];
strFile = strFilename;
}
}
void CDB::Flush()
{
if (activeTxn)
return;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
void CWalletDBWrapper::IncrementUpdateCounter()
{
++nUpdateCounter;
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = nullptr;
pdb = nullptr;
if (fFlushOnClose)
Flush();
{
LOCK(env->cs_db);
--env->mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const std::string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != nullptr) {
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = nullptr;
}
}
}
bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
{
if (dbw.IsDummy()) {
return true;
}
CDBEnv *env = dbw.env;
const std::string& strFile = dbw.strFile;
while (true) {
{
LOCK(env->cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0) {
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile);
std::string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(dbw, "r");
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("CDB::Rewrite: Can't create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret1 = db.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret1 == DB_NOTFOUND) {
pcursor->close();
break;
} else if (ret1 != 0) {
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(ssKey.data(), pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(ssKey.data(), "\x07version", 8) == 0) {
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(ssKey.data(), ssKey.size());
Dbt datValue(ssValue.data(), ssValue.size());
int ret2 = pdbCopy->put(nullptr, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess) {
db.Close();
env->CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
} else {
pdbCopy->close(0);
}
}
if (fSuccess) {
Db dbA(env->dbenv.get(), 0);
if (dbA.remove(strFile.c_str(), nullptr, 0))
fSuccess = false;
Db dbB(env->dbenv.get(), 0);
if (dbB.rename(strFileRes.c_str(), nullptr, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("CDB::Rewrite: Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
std::map<std::string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) {
std::string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint(BCLog::DB, "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s checkpoint\n", strFile);
dbenv->txn_checkpoint(0, 0, 0);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s detach\n", strFile);
if (!fMockDb)
dbenv->lsn_reset(strFile.c_str(), 0);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
dbenv->log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb)
fs::remove_all(fs::path(strPath) / "database");
}
}
}
}
bool CDB::PeriodicFlush(CWalletDBWrapper& dbw)
{
if (dbw.IsDummy()) {
return true;
}
bool ret = false;
CDBEnv *env = dbw.env;
const std::string& strFile = dbw.strFile;
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
std::map<std::string, int>::iterator mit = env->mapFileUseCount.begin();
while (mit != env->mapFileUseCount.end())
{
nRefCount += (*mit).second;
mit++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
std::map<std::string, int>::iterator mi = env->mapFileUseCount.find(strFile);
if (mi != env->mapFileUseCount.end())
{
LogPrint(BCLog::DB, "Flushing %s\n", strFile);
int64_t nStart = GetTimeMillis();
// Flush wallet file so it's self contained
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(mi++);
LogPrint(BCLog::DB, "Flushed %s %dms\n", strFile, GetTimeMillis() - nStart);
ret = true;
}
}
}
return ret;
}
bool CWalletDBWrapper::Rewrite(const char* pszSkip)
{
return CDB::Rewrite(*this, pszSkip);
}
bool CWalletDBWrapper::Backup(const std::string& strDest)
{
if (IsDummy()) {
return false;
}
while (true)
{
{
LOCK(env->cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0)
{
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
// Copy wallet file
fs::path pathSrc = GetWalletDir() / strFile;
fs::path pathDest(strDest);
if (fs::is_directory(pathDest))
pathDest /= strFile;
try {
if (fs::equivalent(pathSrc, pathDest)) {
LogPrintf("cannot backup to wallet source file %s\n", pathDest.string());
return false;
}
fs::copy_file(pathSrc, pathDest, fs::copy_option::overwrite_if_exists);
LogPrintf("copied %s to %s\n", strFile, pathDest.string());
return true;
} catch (const fs::filesystem_error& e) {
LogPrintf("error copying %s to %s - %s\n", strFile, pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
}
void CWalletDBWrapper::Flush(bool shutdown)
{
if (!IsDummy()) {
env->Flush(shutdown);
}
}
|
// -*- C++ -*-
//
// $Id: Functor_T.inl 2179 2013-05-28 22:16:51Z mesnierp $
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
template<class RECEIVER> ACE_INLINE
ACE_Member_Function_Command<RECEIVER>::
ACE_Member_Function_Command (RECEIVER &recvr, PTMF ptmf)
: receiver_(recvr)
, ptmf_(ptmf)
{
}
template<class RECEIVER> ACE_INLINE
ACE_Member_Function_Command<RECEIVER>::
~ACE_Member_Function_Command (void)
{
}
template<class RECEIVER> ACE_INLINE int
ACE_Member_Function_Command<RECEIVER>::execute (void *)
{
(this->receiver_.*ptmf_)();
return 0;
}
template <class TYPE> ACE_INLINE unsigned long
ACE_Hash<TYPE>::operator () (const TYPE &t) const
{
return t.hash ();
}
template <class TYPE> ACE_INLINE unsigned long
ACE_Pointer_Hash<TYPE>::operator () (TYPE t) const
{
#if defined (ACE_WIN64)
// The cast below is legit... we only want a hash, and need not convert
// the hash back to a pointer.
# pragma warning(push)
# pragma warning(disable : 4311) /* Truncate pointer to unsigned long */
#endif /* ACE_WIN64 */
return ACE_Utils::truncate_cast<unsigned long> ((intptr_t)t);
#if defined (ACE_WIN64)
# pragma warning(pop)
#endif /* ACE_WIN64 */
}
template <class TYPE> ACE_INLINE bool
ACE_Equal_To<TYPE>::operator () (const TYPE &lhs,
const TYPE &rhs) const
{
return lhs == rhs;
}
template <class TYPE> ACE_INLINE bool
ACE_Less_Than<TYPE>::operator () (const TYPE &lhs,
const TYPE &rhs) const
{
return lhs < rhs;
}
ACE_END_VERSIONED_NAMESPACE_DECL
|
/*
* Copyright (c) 2013 - 2018, Hugo Hernan Saez
* 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 Crimild 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 <COPYRIGHT HOLDER> 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.
*/
#include "SDLEventSystem.hpp"
#include "WindowSystem.hpp"
#include <Concurrency/Async.hpp>
#include <Foundation/Profiler.hpp>
#include <Simulation/Simulation.hpp>
#include <Simulation/Input.hpp>
#include <Simulation/Console/Console.hpp>
#include <SDL.h>
using namespace crimild;
using namespace crimild::messaging;
using namespace crimild::sdl;
SDLEventSystem::SDLEventSystem( void )
{
registerMessageHandler< messaging::WindowSystemDidCreateWindow >( [ this ]( messaging::WindowSystemDidCreateWindow const &m ) {
auto window = m.window;
SDL_GetWindowSize( window, &_windowSize[ 0 ], &_windowSize[ 1 ] );
crimild::concurrency::sync_frame( std::bind( &SDLEventSystem::update, this ) );
});
}
SDLEventSystem::~SDLEventSystem( void )
{
}
bool SDLEventSystem::start( void )
{
if ( !System::start() ) {
return false;
}
_keycodes[ SDLK_UNKNOWN ] = CRIMILD_INPUT_KEY_UNKNOWN;
_keycodes[ SDLK_BACKSPACE ] = CRIMILD_INPUT_KEY_BACKSPACE;
_keycodes[ SDLK_TAB ] = CRIMILD_INPUT_KEY_TAB;
_keycodes[ SDLK_RETURN ] = CRIMILD_INPUT_KEY_ENTER;
_keycodes[ SDLK_ESCAPE ] = CRIMILD_INPUT_KEY_ESCAPE;
_keycodes[ SDLK_SPACE ] = CRIMILD_INPUT_KEY_SPACE;
//_keycodes[ SDLK_EXCLAIM ] = CRIMILD_INPUT_KEY_EXCLAIM;
//_keycodes[ SDLK_QUOTEDBL ] = CRIMILD_INPUT_KEY_QUOTEDBL;
//_keycodes[ SDLK_HASH ] = CRIMILD_INPUT_KEY_HASH;
//_keycodes[ SDLK_DOLAR ] = CRIMILD_INPUT_KEY_DOLAR;
//_keycodes[ SDLK_PERCENT ] = CRIMILD_INPUT_KEY_PERCENT;
//_keycodes[ SDLK_AMPERSAND ] = CRIMILD_INPUT_KEY_AMPERSAND;
//_keycodes[ SDLK_QUOTE ] = CRIMILD_INPUT_KEY_QUOTE;
//_keycodes[ SDLK_LEFTPAREN ] = CRIMILD_INPUT_KEY_LEFTPAREN;
//_keycodes[ SDLK_RIGHTPAREN ] = CRIMILD_INPUT_KEY_RIGHTPAREN;
//_keycodes[ SDLK_ASTERISK ] = CRIMILD_INPUT_KEY_ASTERISK;
//_keycodes[ SDLK_PLUS ] = CRIMILD_INPUT_KEY_PLUS;
_keycodes[ SDLK_COMMA ] = CRIMILD_INPUT_KEY_COMMA;
_keycodes[ SDLK_MINUS ] = CRIMILD_INPUT_KEY_MINUS;
_keycodes[ SDLK_PERIOD ] = CRIMILD_INPUT_KEY_PERIOD;
_keycodes[ SDLK_SLASH ] = CRIMILD_INPUT_KEY_SLASH;
_keycodes[ SDLK_0 ] = CRIMILD_INPUT_KEY_0;
_keycodes[ SDLK_1 ] = CRIMILD_INPUT_KEY_1;
_keycodes[ SDLK_2 ] = CRIMILD_INPUT_KEY_2;
_keycodes[ SDLK_3 ] = CRIMILD_INPUT_KEY_3;
_keycodes[ SDLK_4 ] = CRIMILD_INPUT_KEY_4;
_keycodes[ SDLK_5 ] = CRIMILD_INPUT_KEY_5;
_keycodes[ SDLK_6 ] = CRIMILD_INPUT_KEY_6;
_keycodes[ SDLK_7 ] = CRIMILD_INPUT_KEY_7;
_keycodes[ SDLK_8 ] = CRIMILD_INPUT_KEY_8;
_keycodes[ SDLK_9 ] = CRIMILD_INPUT_KEY_9;
//_keycodes[ SDLK_COLON ] = CRIMILD_INPUT_KEY_COLON;
_keycodes[ SDLK_SEMICOLON ] = CRIMILD_INPUT_KEY_SEMICOLON;
//_keycodes[ SDLK_LESS ] = CRIMILD_INPUT_KEY_LESS;
//_keycodes[ SDLK_EQUAL ] = CRIMILD_INPUT_KEY_EQUAL;
//_keycodes[ SDLK_GREATER ] = CRIMILD_INPUT_KEY_GREATER;
//_keycodes[ SDLK_QUESTION ] = CRIMILD_INPUT_KEY_QUESTION;
//_keycodes[ SDLK_AT ] = CRIMILD_INPUT_KEY_AT;
_keycodes[ SDLK_LEFTBRACKET ] = CRIMILD_INPUT_KEY_LEFT_BRACKET;
_keycodes[ SDLK_BACKSLASH ] = CRIMILD_INPUT_KEY_BACKSLASH;
_keycodes[ SDLK_RIGHTBRACKET ] = CRIMILD_INPUT_KEY_RIGHT_BRACKET;
//_keycodes[ SDLK_CARET ] = CRIMILD_INPUT_KEY_CARET;
//_keycodes[ SDLK_UNDERSCORE ] = CRIMILD_INPUT_KEY_UNDERSCORE;
_keycodes[ SDLK_BACKQUOTE ] = CRIMILD_INPUT_KEY_GRAVE_ACCENT;
_keycodes[ SDLK_a ] = CRIMILD_INPUT_KEY_A;
_keycodes[ SDLK_b ] = CRIMILD_INPUT_KEY_B;
_keycodes[ SDLK_c ] = CRIMILD_INPUT_KEY_C;
_keycodes[ SDLK_d ] = CRIMILD_INPUT_KEY_D;
_keycodes[ SDLK_e ] = CRIMILD_INPUT_KEY_E;
_keycodes[ SDLK_f ] = CRIMILD_INPUT_KEY_F;
_keycodes[ SDLK_g ] = CRIMILD_INPUT_KEY_G;
_keycodes[ SDLK_h ] = CRIMILD_INPUT_KEY_H;
_keycodes[ SDLK_i ] = CRIMILD_INPUT_KEY_I;
_keycodes[ SDLK_j ] = CRIMILD_INPUT_KEY_J;
_keycodes[ SDLK_k ] = CRIMILD_INPUT_KEY_K;
_keycodes[ SDLK_l ] = CRIMILD_INPUT_KEY_L;
_keycodes[ SDLK_m ] = CRIMILD_INPUT_KEY_M;
_keycodes[ SDLK_n ] = CRIMILD_INPUT_KEY_N;
_keycodes[ SDLK_o ] = CRIMILD_INPUT_KEY_O;
_keycodes[ SDLK_p ] = CRIMILD_INPUT_KEY_P;
_keycodes[ SDLK_q ] = CRIMILD_INPUT_KEY_Q;
_keycodes[ SDLK_r ] = CRIMILD_INPUT_KEY_R;
_keycodes[ SDLK_s ] = CRIMILD_INPUT_KEY_S;
_keycodes[ SDLK_t ] = CRIMILD_INPUT_KEY_T;
_keycodes[ SDLK_u ] = CRIMILD_INPUT_KEY_U;
_keycodes[ SDLK_v ] = CRIMILD_INPUT_KEY_V;
_keycodes[ SDLK_w ] = CRIMILD_INPUT_KEY_W;
_keycodes[ SDLK_x ] = CRIMILD_INPUT_KEY_X;
_keycodes[ SDLK_y ] = CRIMILD_INPUT_KEY_Y;
_keycodes[ SDLK_z ] = CRIMILD_INPUT_KEY_Z;
_keycodes[ SDLK_DELETE ] = CRIMILD_INPUT_KEY_DELETE;
_keycodes[ SDLK_CAPSLOCK ] = CRIMILD_INPUT_KEY_CAPS_LOCK;
_keycodes[ SDLK_F1 ] = CRIMILD_INPUT_KEY_F1;
_keycodes[ SDLK_F2 ] = CRIMILD_INPUT_KEY_F2;
_keycodes[ SDLK_F3 ] = CRIMILD_INPUT_KEY_F3;
_keycodes[ SDLK_F4 ] = CRIMILD_INPUT_KEY_F4;
_keycodes[ SDLK_F5 ] = CRIMILD_INPUT_KEY_F5;
_keycodes[ SDLK_F6 ] = CRIMILD_INPUT_KEY_F6;
_keycodes[ SDLK_F7 ] = CRIMILD_INPUT_KEY_F7;
_keycodes[ SDLK_F8 ] = CRIMILD_INPUT_KEY_F8;
_keycodes[ SDLK_F9 ] = CRIMILD_INPUT_KEY_F9;
_keycodes[ SDLK_F10 ] = CRIMILD_INPUT_KEY_F10;
_keycodes[ SDLK_F11 ] = CRIMILD_INPUT_KEY_F11;
_keycodes[ SDLK_F12 ] = CRIMILD_INPUT_KEY_F12;
_keycodes[ SDLK_F13 ] = CRIMILD_INPUT_KEY_F13;
_keycodes[ SDLK_F14 ] = CRIMILD_INPUT_KEY_F14;
_keycodes[ SDLK_F15 ] = CRIMILD_INPUT_KEY_F15;
_keycodes[ SDLK_F16 ] = CRIMILD_INPUT_KEY_F16;
_keycodes[ SDLK_F17 ] = CRIMILD_INPUT_KEY_F17;
_keycodes[ SDLK_F18 ] = CRIMILD_INPUT_KEY_F18;
_keycodes[ SDLK_F19 ] = CRIMILD_INPUT_KEY_F19;
_keycodes[ SDLK_F20 ] = CRIMILD_INPUT_KEY_F20;
_keycodes[ SDLK_F21 ] = CRIMILD_INPUT_KEY_F21;
_keycodes[ SDLK_F22 ] = CRIMILD_INPUT_KEY_F22;
_keycodes[ SDLK_F23 ] = CRIMILD_INPUT_KEY_F23;
_keycodes[ SDLK_F24 ] = CRIMILD_INPUT_KEY_F24;
_keycodes[ SDLK_PRINTSCREEN ] = CRIMILD_INPUT_KEY_PRINT_SCREEN;
_keycodes[ SDLK_SCROLLLOCK ] = CRIMILD_INPUT_KEY_SCROLL_LOCK;
_keycodes[ SDLK_PAUSE ] = CRIMILD_INPUT_KEY_PAUSE;
_keycodes[ SDLK_INSERT ] = CRIMILD_INPUT_KEY_INSERT;
_keycodes[ SDLK_HOME ] = CRIMILD_INPUT_KEY_HOME;
_keycodes[ SDLK_PAGEUP ] = CRIMILD_INPUT_KEY_PAGE_UP;
_keycodes[ SDLK_END ] = CRIMILD_INPUT_KEY_END;
_keycodes[ SDLK_PAGEDOWN ] = CRIMILD_INPUT_KEY_PAGE_DOWN;
_keycodes[ SDLK_RIGHT ] = CRIMILD_INPUT_KEY_RIGHT;
_keycodes[ SDLK_DOWN ] = CRIMILD_INPUT_KEY_DOWN;
_keycodes[ SDLK_LEFT ] = CRIMILD_INPUT_KEY_LEFT;
_keycodes[ SDLK_UP ] = CRIMILD_INPUT_KEY_UP;
_keycodes[ SDLK_NUMLOCKCLEAR ] = CRIMILD_INPUT_KEY_NUM_LOCK;
_keycodes[ SDLK_KP_MULTIPLY ] = CRIMILD_INPUT_KEY_KP_MULTIPLY;
_keycodes[ SDLK_KP_MINUS ] = CRIMILD_INPUT_KEY_KP_SUBTRACT;
_keycodes[ SDLK_KP_PLUS ] = CRIMILD_INPUT_KEY_KP_ADD;
_keycodes[ SDLK_KP_ENTER ] = CRIMILD_INPUT_KEY_KP_ENTER;
_keycodes[ SDLK_PERIOD ] = CRIMILD_INPUT_KEY_KP_DECIMAL;
_keycodes[ SDLK_0 ] = CRIMILD_INPUT_KEY_KP_0;
_keycodes[ SDLK_1 ] = CRIMILD_INPUT_KEY_KP_1;
_keycodes[ SDLK_2 ] = CRIMILD_INPUT_KEY_KP_2;
_keycodes[ SDLK_3 ] = CRIMILD_INPUT_KEY_KP_3;
_keycodes[ SDLK_4 ] = CRIMILD_INPUT_KEY_KP_4;
_keycodes[ SDLK_5 ] = CRIMILD_INPUT_KEY_KP_5;
_keycodes[ SDLK_6 ] = CRIMILD_INPUT_KEY_KP_6;
_keycodes[ SDLK_7 ] = CRIMILD_INPUT_KEY_KP_7;
_keycodes[ SDLK_8 ] = CRIMILD_INPUT_KEY_KP_8;
_keycodes[ SDLK_9 ] = CRIMILD_INPUT_KEY_KP_9;
_keycodes[ SDLK_KP_DIVIDE ] = CRIMILD_INPUT_KEY_KP_DIVIDE;
_keycodes[ SDLK_KP_EQUALS ] = CRIMILD_INPUT_KEY_KP_EQUAL;
_keycodes[ SDLK_MENU ] = CRIMILD_INPUT_KEY_MENU;
_keycodes[ SDLK_LSHIFT ] = CRIMILD_INPUT_KEY_LEFT_SHIFT;
_keycodes[ SDLK_LCTRL ] = CRIMILD_INPUT_KEY_LEFT_CONTROL;
_keycodes[ SDLK_LALT ] = CRIMILD_INPUT_KEY_LEFT_ALT;
_keycodes[ SDLK_LGUI ] = CRIMILD_INPUT_KEY_LEFT_SUPER;
_keycodes[ SDLK_RSHIFT ] = CRIMILD_INPUT_KEY_RIGHT_SHIFT;
_keycodes[ SDLK_RCTRL ] = CRIMILD_INPUT_KEY_RIGHT_CONTROL;
_keycodes[ SDLK_RALT ] = CRIMILD_INPUT_KEY_RIGHT_ALT;
_keycodes[ SDLK_RGUI ] = CRIMILD_INPUT_KEY_RIGHT_SUPER;
//_keycodes[ SDLK_ ] = CRIMILD_INPUT_MOD_SHIFT;
//_keycodes[ SDLK_ ] = CRIMILD_INPUT_MOD_CONTROL;
//_keycodes[ SDLK_ ] = CRIMILD_INPUT_MOD_ALT;
//_keycodes[ SDLK_ ] = CRIMILD_INPUT_MOD_SUPER;
_mousecodes[ SDL_BUTTON_LEFT ] = CRIMILD_INPUT_MOUSE_BUTTON_LEFT;
_mousecodes[ SDL_BUTTON_MIDDLE ] = CRIMILD_INPUT_MOUSE_BUTTON_MIDDLE;
_mousecodes[ SDL_BUTTON_RIGHT ] = CRIMILD_INPUT_MOUSE_BUTTON_RIGHT;
return true;
}
void SDLEventSystem::update( void )
{
CRIMILD_PROFILE( "Update Input" )
SDL_Event event;
while ( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_QUIT:
crimild::concurrency::sync_frame( [] {
Simulation::getInstance()->stop();
});
return;
case SDL_WINDOWEVENT_RESIZED:
crimild::Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Window resized to ", event.window.data1, "x", event.window.data2 );
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
crimild::Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Window size changed to ", event.window.data1, "x", event.window.data2 );
break;
case SDL_MOUSEBUTTONDOWN: {
MessageQueue::getInstance()->pushMessage( MouseButtonDown { _mousecodes[ event.button.button ] } );
break;
}
case SDL_MOUSEBUTTONUP: {
MessageQueue::getInstance()->pushMessage( MouseButtonUp { _mousecodes[ event.button.button ] } );
break;
}
case SDL_MOUSEWHEEL: {
MessageQueue::getInstance()->pushMessage( MouseScroll { ( crimild::Real32 ) event.wheel.x, ( crimild::Real32 ) event.wheel.y } );
break;
}
case SDL_KEYDOWN: {
if ( event.key.keysym.sym != SDLK_UNKNOWN ) {
auto key = _keycodes[ event.key.keysym.sym ];
if ( Console::getInstance()->isEnabled() ) {
switch ( key ) {
case CRIMILD_INPUT_KEY_BACKSPACE:
case CRIMILD_INPUT_KEY_UP:
case CRIMILD_INPUT_KEY_DOWN:
case CRIMILD_INPUT_KEY_ENTER:
Console::getInstance()->handleInput( key, 0 );
break;
default:
break;
}
}
if ( !Console::getInstance()->isActive() ) {
MessageQueue::getInstance()->pushMessage( KeyPressed { key } );
}
}
break;
}
case SDL_KEYUP: {
if ( !Console::getInstance()->isActive() ) {
MessageQueue::getInstance()->pushMessage( KeyReleased { _keycodes[ event.key.keysym.sym ] } );
}
break;
}
case SDL_TEXTINPUT: {
if ( Console::getInstance()->isEnabled() ) {
auto text = std::string( event.text.text );
for ( auto c : text ) {
Console::getInstance()->handleInput( c, 0 );
}
}
break;
}
default:
break;
}
}
// trigger MouseMotion in every update to handle cases
// when the mouse is not moving and the delta pos should
// be updated
int mouseX, mouseY;
SDL_GetMouseState( &mouseX, &mouseY );
MessageQueue::getInstance()->pushMessage( MouseMotion {
( crimild::Real32 ) mouseX,
( crimild::Real32 ) mouseY,
( crimild::Real32 ) mouseX / ( crimild::Real32 ) _windowSize.x(),
( crimild::Real32 ) mouseY / ( crimild::Real32 ) _windowSize.y()
});
crimild::concurrency::sync_frame( std::bind( &SDLEventSystem::update, this ) );
}
void SDLEventSystem::stop( void )
{
System::stop();
}
|
#include "ComponentRigidDynamic.h"
#include "Application.h"
#include "ModulePhysics.h"
#include "GameObject.h"
#include "ComponentTransform.h"
#include "ComponentCollider.h"
#include "ComponentBoxCollider.h"
#include "ComponentSphereCollider.h"
#include "ComponentCapsuleCollider.h"
#include "ComponentPlaneCollider.h"
#include "PhysicsConstants.h"
#include "imgui\imgui.h"
ComponentRigidDynamic::ComponentRigidDynamic(GameObject* parent, bool include) : ComponentRigidActor(parent, ComponentTypes::RigidDynamicComponent, include)
{
density = PhysicsConstants::DENSITY;
if (include)
{
physx::PxShape* gShape = nullptr;
if (parent->cmp_collider != nullptr && parent->cmp_collider->GetShape() != nullptr)
gShape = parent->cmp_collider->GetShape();
else if (parent->boundingBox.IsFinite())
gShape = App->physics->CreateShape(physx::PxBoxGeometry(parent->boundingBox.HalfSize().x, parent->boundingBox.HalfSize().y, parent->boundingBox.HalfSize().z), *App->physics->GetDefaultMaterial());
else
gShape = App->physics->CreateShape(physx::PxBoxGeometry(PhysicsConstants::GEOMETRY_HALF_SIZE, PhysicsConstants::GEOMETRY_HALF_SIZE, PhysicsConstants::GEOMETRY_HALF_SIZE), *App->physics->GetDefaultMaterial());
assert(gShape != nullptr);
gActor = App->physics->CreateRigidDynamic(physx::PxTransform(physx::PxIDENTITY()), *gShape, density, isKinematic);
assert(gActor != nullptr);
App->physics->AddActor(*gActor);
gActor->setActorFlag(physx::PxActorFlag::eSEND_SLEEP_NOTIFIES, true);
math::float4x4 globalMatrix = parent->transform->GetGlobalMatrix();
UpdateTransform(globalMatrix);
// -----
UpdateMassAndInertia();
linearDamping = gActor->is<physx::PxRigidDynamic>()->getLinearDamping();
angularDamping = gActor->is<physx::PxRigidDynamic>()->getAngularDamping();
maxLinearVelocity = gActor->is<physx::PxRigidDynamic>()->getMaxLinearVelocity();
maxAngularVelocity = gActor->is<physx::PxRigidDynamic>()->getMaxAngularVelocity();
physx::PxRigidDynamicLockFlags rigidDynamicLockFlags = gActor->is<physx::PxRigidDynamic>()->getRigidDynamicLockFlags();
freezePosition[0] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_X;
freezePosition[1] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Y;
freezePosition[2] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Z;
freezeRotation[0] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_X;
freezeRotation[1] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y;
freezeRotation[2] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z;
physx::PxRigidBodyFlags rigidBodyFlags = gActor->is<physx::PxRigidBody>()->getRigidBodyFlags();
isKinematic = rigidBodyFlags & physx::PxRigidBodyFlag::Enum::eKINEMATIC;
}
rigidActorType = RigidActorTypes::RigidDynamic;
// -----
SetUseGravity(useGravity);
// -----
SetLinearDamping(linearDamping);
SetAngularDamping(angularDamping);
SetMaxLinearVelocity(maxLinearVelocity);
SetMaxAngularVelocity(maxAngularVelocity);
FreezePosition(freezePosition[0], freezePosition[1], freezePosition[2]);
FreezeRotation(freezeRotation[0], freezeRotation[1], freezeRotation[2]);
SetIsKinematic(isKinematic);
}
ComponentRigidDynamic::ComponentRigidDynamic(const ComponentRigidDynamic& componentRigidDynamic, GameObject* parent, bool include) : ComponentRigidActor(componentRigidDynamic, parent, ComponentTypes::RigidDynamicComponent, include)
{
density = componentRigidDynamic.density;
if (include)
{
physx::PxShape* gShape = nullptr;
if (componentRigidDynamic.parent->cmp_collider != nullptr && componentRigidDynamic.parent->cmp_collider->GetShape() != nullptr)
gShape = componentRigidDynamic.parent->cmp_collider->GetShape();
else if (componentRigidDynamic.parent->boundingBox.IsFinite())
gShape = App->physics->CreateShape(physx::PxBoxGeometry(componentRigidDynamic.parent->boundingBox.HalfSize().x, componentRigidDynamic.parent->boundingBox.HalfSize().y, componentRigidDynamic.parent->boundingBox.HalfSize().z), *App->physics->GetDefaultMaterial());
else
gShape = App->physics->CreateShape(physx::PxBoxGeometry(PhysicsConstants::GEOMETRY_HALF_SIZE, PhysicsConstants::GEOMETRY_HALF_SIZE, PhysicsConstants::GEOMETRY_HALF_SIZE), *App->physics->GetDefaultMaterial());
assert(gShape != nullptr);
gActor = App->physics->CreateRigidDynamic(physx::PxTransform(physx::PxIDENTITY()), *gShape, density, isKinematic);
assert(gActor != nullptr);
App->physics->AddActor(*gActor);
gActor->setActorFlag(physx::PxActorFlag::eSEND_SLEEP_NOTIFIES, true);
math::float4x4 globalMatrix = parent->transform->GetGlobalMatrix();
UpdateTransform(globalMatrix);
UpdateMassAndInertia();
linearDamping = gActor->is<physx::PxRigidDynamic>()->getLinearDamping();
angularDamping = gActor->is<physx::PxRigidDynamic>()->getAngularDamping();
maxLinearVelocity = gActor->is<physx::PxRigidDynamic>()->getMaxLinearVelocity();
maxAngularVelocity = gActor->is<physx::PxRigidDynamic>()->getMaxAngularVelocity();
physx::PxRigidDynamicLockFlags rigidDynamicLockFlags = gActor->is<physx::PxRigidDynamic>()->getRigidDynamicLockFlags();
freezePosition[0] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_X;
freezePosition[1] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Y;
freezePosition[2] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Z;
freezeRotation[0] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_X;
freezeRotation[1] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y;
freezeRotation[2] = rigidDynamicLockFlags & physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z;
physx::PxRigidBodyFlags rigidBodyFlags = gActor->is<physx::PxRigidBody>()->getRigidBodyFlags();
isKinematic = rigidBodyFlags & physx::PxRigidBodyFlag::Enum::eKINEMATIC;
}
rigidActorType = componentRigidDynamic.rigidActorType;
// -----
SetUseGravity(componentRigidDynamic.useGravity);
// -----
SetLinearDamping(componentRigidDynamic.linearDamping);
SetAngularDamping(componentRigidDynamic.angularDamping);
SetMaxLinearVelocity(componentRigidDynamic.maxLinearVelocity);
SetMaxAngularVelocity(componentRigidDynamic.maxAngularVelocity);
FreezePosition(componentRigidDynamic.freezePosition[0], componentRigidDynamic.freezePosition[1], componentRigidDynamic.freezePosition[2]);
FreezeRotation(componentRigidDynamic.freezeRotation[0], componentRigidDynamic.freezeRotation[1], componentRigidDynamic.freezeRotation[2]);
SetIsKinematic(componentRigidDynamic.isKinematic);
}
ComponentRigidDynamic::~ComponentRigidDynamic() {}
// ----------------------------------------------------------------------------------------------------
void ComponentRigidDynamic::OnUniqueEditor()
{
#ifndef GAMEMODE
if (ImGui::CollapsingHeader("Rigid Dynamic", ImGuiTreeNodeFlags_DefaultOpen))
{
ComponentRigidActor::OnUniqueEditor();
ImGui::AlignTextToFramePadding();
ImGui::Text("Density"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##Density", &density, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetDensity(density);
ImGui::PopItemWidth();
ImGui::PushID("DensityButton");
if (ImGui::SmallButton("Update mass and inertia"))
UpdateMassAndInertia();
ImGui::PopID();
// -----
ImGui::AlignTextToFramePadding();
ImGui::Text("Mass"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##Mass", &mass, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetMass(mass);
ImGui::PopItemWidth();
// -----
ImGui::Text("Center of mass");
ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##CMassX", &cMass.x, 0.01f, -FLT_MAX, FLT_MAX, "%.2f", 1.0f))
SetCMass(cMass);
ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##CMassY", &cMass.y, 0.01f, -FLT_MAX, FLT_MAX, "%.2f", 1.0f))
SetCMass(cMass);
ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##CMassZ", &cMass.z, 0.01f, -FLT_MAX, FLT_MAX, "%.2f", 1.0f))
SetCMass(cMass);
ImGui::PopItemWidth();
// -----
ImGui::Text("Moment of inertia");
ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##InertiaX", &inertia.x, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetInertia(inertia);
ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##InertiaY", &inertia.y, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetInertia(inertia);
ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##InertiaZ", &inertia.z, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetInertia(inertia);
ImGui::PopItemWidth();
// -----
ImGui::AlignTextToFramePadding();
ImGui::Text("Linear damping"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##LinearDamping", &linearDamping, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetLinearDamping(linearDamping);
ImGui::PopItemWidth();
// -----
ImGui::AlignTextToFramePadding();
ImGui::Text("Angular damping"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##AngularDamping", &angularDamping, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetAngularDamping(angularDamping);
ImGui::PopItemWidth();
// -----
ImGui::AlignTextToFramePadding();
ImGui::Text("Max linear velocity"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##MaxLinearVelocity", &maxLinearVelocity, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetMaxLinearVelocity(maxLinearVelocity);
ImGui::PopItemWidth();
// -----
ImGui::AlignTextToFramePadding();
ImGui::Text("Max angular velocity"); ImGui::SameLine(); ImGui::PushItemWidth(50.0f);
if (ImGui::DragFloat("##MaxAngularVelocity", &maxAngularVelocity, 0.01f, 0.0f, FLT_MAX, "%.2f", 1.0f))
SetMaxAngularVelocity(maxAngularVelocity);
ImGui::PopItemWidth();
// -----
if (ImGui::TreeNodeEx("Constraints", ImGuiTreeNodeFlags_OpenOnArrow))
{
ImGui::Text("Freeze Position");
if (ImGui::Checkbox("X##FreezePositionX", &freezePosition[0]))
FreezePosition(freezePosition[0], freezePosition[1], freezePosition[2]);
ImGui::SameLine();
if (ImGui::Checkbox("Y##FreezePositionY", &freezePosition[1]))
FreezePosition(freezePosition[0], freezePosition[1], freezePosition[2]);
ImGui::SameLine();
if (ImGui::Checkbox("Z##FreezePositionZ", &freezePosition[2]))
FreezePosition(freezePosition[0], freezePosition[1], freezePosition[2]);
ImGui::Text("Freeze Rotation");
if (ImGui::Checkbox("X##FreezeRotationX", &freezeRotation[0]))
FreezeRotation(freezeRotation[0], freezeRotation[1], freezeRotation[2]);
ImGui::SameLine();
if (ImGui::Checkbox("Y##FreezeRotationY", &freezeRotation[1]))
FreezeRotation(freezeRotation[0], freezeRotation[1], freezeRotation[2]);
ImGui::SameLine();
if (ImGui::Checkbox("Z##FreezeRotationZ", &freezeRotation[2]))
FreezeRotation(freezeRotation[0], freezeRotation[1], freezeRotation[2]);
ImGui::TreePop();
}
// -----
if (ImGui::Checkbox("Is Kinematic", &isKinematic))
SetIsKinematic(isKinematic);
}
#endif
}
// ----------------------------------------------------------------------------------------------------
void ComponentRigidDynamic::Update()
{
if (!IsSleeping())
UpdateGameObjectTransform();
}
uint ComponentRigidDynamic::GetInternalSerializationBytes()
{
return ComponentRigidActor::GetInternalSerializationBytes() +
sizeof(float) +
sizeof(float) +
sizeof(math::float3) +
sizeof(math::float3) +
sizeof(float) +
sizeof(float) +
sizeof(float) +
sizeof(float) +
sizeof(bool) * 3 +
sizeof(bool) * 3 +
sizeof(bool);
}
void ComponentRigidDynamic::OnInternalSave(char*& cursor)
{
ComponentRigidActor::OnInternalSave(cursor);
size_t bytes = sizeof(float);
memcpy(cursor, &density, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(cursor, &mass, bytes);
cursor += bytes;
bytes = sizeof(math::float3);
memcpy(cursor, &cMass, bytes);
cursor += bytes;
bytes = sizeof(math::float3);
memcpy(cursor, &inertia, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(cursor, &linearDamping, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(cursor, &angularDamping, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(cursor, &maxLinearVelocity, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(cursor, &maxAngularVelocity, bytes);
cursor += bytes;
bytes = sizeof(bool) * 3;
memcpy(cursor, &freezePosition[0], bytes);
cursor += bytes;
bytes = sizeof(bool) * 3;
memcpy(cursor, &freezeRotation[0], bytes);
cursor += bytes;
bytes = sizeof(bool);
memcpy(cursor, &isKinematic, bytes);
cursor += bytes;
}
void ComponentRigidDynamic::OnInternalLoad(char*& cursor)
{
ComponentRigidActor::OnInternalLoad(cursor);
size_t bytes = sizeof(float);
memcpy(&density, cursor, bytes);
cursor += bytes;
bytes = sizeof(float);
memcpy(&mass, cursor, bytes);
cursor += bytes;
bytes = sizeof(math::float3);
memcpy(&cMass, cursor, bytes);
cursor += bytes;
bytes = sizeof(math::float3);
memcpy(&inertia, cursor, bytes);
cursor += bytes;
UpdateMassAndInertia();
bytes = sizeof(float);
memcpy(&linearDamping, cursor, bytes);
SetLinearDamping(linearDamping);
cursor += bytes;
bytes = sizeof(float);
memcpy(&angularDamping, cursor, bytes);
SetAngularDamping(angularDamping);
cursor += bytes;
bytes = sizeof(float);
memcpy(&maxLinearVelocity, cursor, bytes);
SetMaxLinearVelocity(maxLinearVelocity);
cursor += bytes;
bytes = sizeof(float);
memcpy(&maxAngularVelocity, cursor, bytes);
SetMaxAngularVelocity(maxAngularVelocity);
cursor += bytes;
bytes = sizeof(bool) * 3;
memcpy(&freezePosition[0], cursor, bytes);
FreezePosition(freezePosition[0], freezePosition[1], freezePosition[2]);
cursor += bytes;
bytes = sizeof(bool) * 3;
memcpy(&freezeRotation[0], cursor, bytes);
FreezeRotation(freezeRotation[0], freezeRotation[1], freezeRotation[2]);
cursor += bytes;
bytes = sizeof(bool);
memcpy(&isKinematic, cursor, bytes);
SetIsKinematic(isKinematic);
cursor += bytes;
}
// ----------------------------------------------------------------------------------------------------
void ComponentRigidDynamic::SetDensity(float density)
{
this->density = density;
}
// Sets the mass, center of mass, and inertia tensor
void ComponentRigidDynamic::UpdateMassAndInertia()
{
if (gActor != nullptr)
{
physx::PxRigidBodyExt::updateMassAndInertia(*gActor->is<physx::PxRigidBody>(), density);
mass = gActor->is<physx::PxRigidDynamic>()->getMass();
physx::PxVec3 gCMass = gActor->is<physx::PxRigidDynamic>()->getCMassLocalPose().p;
cMass = math::float3(gCMass.x, gCMass.y, gCMass.z);
physx::PxVec3 gInertia = gActor->is<physx::PxRigidDynamic>()->getMassSpaceInertiaTensor();
inertia = math::float3(gInertia.x, gInertia.y, gInertia.z);
}
}
void ComponentRigidDynamic::SetMass(float mass)
{
// mass = 0.0f equals infinite mass
// infinite mass: the linear velocity of the body cannot be changed by any constraints
this->mass = mass;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setMass(mass);
}
void ComponentRigidDynamic::SetCMass(const math::float3& cMass)
{
assert(cMass.IsFinite());
this->cMass = cMass;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setCMassLocalPose(physx::PxTransform(physx::PxVec3(cMass.x, cMass.y, cMass.z)));
}
void ComponentRigidDynamic::SetInertia(const math::float3& inertia)
{
assert(inertia.IsFinite());
// inertia = math::float3(0.0f, 0.0f, 0.0f) equals infinite inertia
this->inertia = inertia;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setMassSpaceInertiaTensor(physx::PxVec3(inertia.x, inertia.y, inertia.z));
}
void ComponentRigidDynamic::SetLinearDamping(float linearDamping)
{
this->linearDamping = linearDamping;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setLinearDamping(linearDamping);
}
void ComponentRigidDynamic::SetAngularDamping(float angularDamping)
{
this->angularDamping = angularDamping;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setAngularDamping(angularDamping);
}
void ComponentRigidDynamic::SetMaxLinearVelocity(float maxLinearVelocity)
{
this->maxLinearVelocity = maxLinearVelocity;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setMaxLinearVelocity(maxLinearVelocity);
}
void ComponentRigidDynamic::SetMaxAngularVelocity(float maxAngularVelocity)
{
this->maxAngularVelocity = maxAngularVelocity;
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setMaxAngularVelocity(maxAngularVelocity);
}
void ComponentRigidDynamic::FreezePosition(bool x, bool y, bool z)
{
freezePosition[0] = x;
freezePosition[1] = y;
freezePosition[2] = z;
if (gActor != nullptr)
{
physx::PxRigidDynamicLockFlags flags;
if (x)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_X;
if (y)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Y;
if (z)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Z;
gActor->is<physx::PxRigidDynamic>()->setRigidDynamicLockFlags(flags);
}
}
void ComponentRigidDynamic::FreezeRotation(bool x, bool y, bool z)
{
freezeRotation[0] = x;
freezeRotation[1] = y;
freezeRotation[2] = z;
if (gActor != nullptr)
{
physx::PxRigidDynamicLockFlags flags;
if (x)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_X;
if (y)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y;
if (z)
flags |= physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z;
gActor->is<physx::PxRigidDynamic>()->setRigidDynamicLockFlags(flags);
}
}
void ComponentRigidDynamic::SetIsKinematic(bool isKinematic)
{
this->isKinematic = isKinematic;
if (gActor != nullptr)
{
gActor->is<physx::PxRigidBody>()->setRigidBodyFlag(physx::PxRigidBodyFlag::Enum::eKINEMATIC, isKinematic);
UpdateTransform(parent->transform->GetGlobalMatrix());
}
}
// ----------------------------------------------------------------------------------------------------
void ComponentRigidDynamic::SetLinearVelocity(math::float3& linearVelocity)
{
assert(linearVelocity.IsFinite());
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setLinearVelocity(physx::PxVec3(linearVelocity.x, linearVelocity.y, linearVelocity.z));
}
void ComponentRigidDynamic::SetAngularVelocity(math::float3& angularVelocity)
{
assert(angularVelocity.IsFinite());
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->setAngularVelocity(physx::PxVec3(angularVelocity.x, angularVelocity.y, angularVelocity.z));
}
void ComponentRigidDynamic::AddForce(math::float3& force, physx::PxForceMode::Enum forceMode)
{
assert(force.IsFinite());
// f = m*a (force = mass * acceleration)
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->addForce(physx::PxVec3(force.x, force.y, force.z), forceMode);
}
void ComponentRigidDynamic::ClearForce() const
{
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->clearForce();
}
void ComponentRigidDynamic::AddTorque(math::float3& torque, physx::PxForceMode::Enum forceMode)
{
assert(torque.IsFinite());
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->addTorque(physx::PxVec3(torque.x, torque.y, torque.z), forceMode);
}
void ComponentRigidDynamic::ClearTorque() const
{
if (gActor != nullptr)
gActor->is<physx::PxRigidDynamic>()->clearTorque();
}
bool ComponentRigidDynamic::IsSleeping() const
{
if (gActor != nullptr)
return gActor->is<physx::PxRigidDynamic>()->isSleeping();
else
return true;
}
math::float3 ComponentRigidDynamic::GetLinearVelocity() const
{
if (gActor != nullptr)
{
physx::PxVec3 gLinearVelocity = gActor->is<physx::PxRigidDynamic>()->getLinearVelocity();
return math::float3(gLinearVelocity.x, gLinearVelocity.y, gLinearVelocity.z);
}
else
return math::float3::zero;
}
math::float3 ComponentRigidDynamic::GetAngularVelocity() const
{
if (gActor != nullptr)
{
physx::PxVec3 gAngularVelocity = gActor->is<physx::PxRigidDynamic>()->getAngularVelocity();
return math::float3(gAngularVelocity.x, gAngularVelocity.y, gAngularVelocity.z);
}
else
return math::float3::zero;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 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 "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
if (pwalletMain)
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
if (pwalletMain)
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Summitzcoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" summitzcoind [options] " + "\n" +
" summitzcoind [options] <command> [params] " + _("Send command to -server or summitzcoind") + "\n" +
" summitzcoind [options] help " + _("List commands") + "\n" +
" summitzcoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "summitzcoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: summitzcoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: summitzcoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 3872 or testnet: 13872)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
" -bloomfilters " + _("Allow peers to set bloom filters (default: 1)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.0001)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 3871 or testnet: 13871)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -maxorphantx=<n> " + _("Keep at most <n> unconnectable transactions in memory (default: 25)") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Summitzcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
fBloomFilters = GetBoolArg("-bloomfilters", true);
if (fBloomFilters)
nLocalServices |= NODE_BLOOM;
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
bSpendZeroConfChange = GetArg("-spendzeroconfchange", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Summitzcoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Summitzcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Summitzcoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
#if defined(USE_SSE2)
scrypt_detect_sse2();
#endif
// ********************************************************* Step 5: verify wallet database integrity
if (!fDisableWallet) {
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
if (fDisableWallet) {
printf("Wallet disabled!\n");
pwalletMain = NULL;
} else {
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Summitzcoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Summitzcoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
} // (!fDisableWallet)
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
return !fRequestShutdown;
}
|
/**
* @file methods/neighbor_search/sort_policies/nearest_neighbor_sort.hpp
* @author Ryan Curtin
*
* Implementation of the SortPolicy class for NeighborSearch; in this case, the
* nearest neighbors are those that are most important.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_SORT_HPP
#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_SORT_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace neighbor {
/**
* This class implements the necessary methods for the SortPolicy template
* parameter of the NeighborSearch class. The sorting policy here is that the
* minimum distance is the best (so, when used with NeighborSearch, the output
* is nearest neighbors).
*
* This class is also meant to serve as a guide to implement a custom
* SortPolicy. All of the methods implemented here must be implemented by any
* other SortPolicy classes.
*/
class NearestNS
{
public:
/**
* Return whether or not value is "better" than ref. In this case, that means
* that the value is less than or equal to the reference.
*
* @param value Value to compare
* @param ref Value to compare with
*
* @return bool indicating whether or not (value <= ref).
*/
static inline bool IsBetter(const double value, const double ref)
{
return (value <= ref);
}
/**
* Return the best possible distance between two nodes. In our case, this is
* the minimum distance between the two tree nodes using the given distance
* function.
*/
template<typename TreeType>
static double BestNodeToNodeDistance(const TreeType* queryNode,
const TreeType* referenceNode);
/**
* Return the best possible distance between two nodes, given that the
* distance between the centers of the two nodes has already been calculated.
* This is used in conjunction with trees that have self-children (like cover
* trees).
*/
template<typename TreeType>
static double BestNodeToNodeDistance(const TreeType* queryNode,
const TreeType* referenceNode,
const double centerToCenterDistance);
/**
* Return the best possible distance between the query node and the reference
* child node given the base case distance between the query node and the
* reference node. TreeType::ParentDistance() must be implemented to use
* this.
*
* @param queryNode Query node.
* @param referenceNode Reference node.
* @param referenceChildNode Child of reference node which is being inspected.
* @param centerToCenterDistance Distance between centers of query node and
* reference node.
*/
template<typename TreeType>
static double BestNodeToNodeDistance(const TreeType* queryNode,
const TreeType* referenceNode,
const TreeType* referenceChildNode,
const double centerToCenterDistance);
/**
* Return the best possible distance between a node and a point. In our case,
* this is the minimum distance between the tree node and the point using the
* given distance function.
*/
template<typename VecType, typename TreeType>
static double BestPointToNodeDistance(const VecType& queryPoint,
const TreeType* referenceNode);
/**
* Return the best possible distance between a point and a node, given that
* the distance between the point and the center of the node has already been
* calculated. This is used in conjunction with trees that have
* self-children (like cover trees).
*/
template<typename VecType, typename TreeType>
static double BestPointToNodeDistance(const VecType& queryPoint,
const TreeType* referenceNode,
const double pointToCenterDistance);
/**
* Return the best child according to this sort policy. In this case it will
* return the one with the minimum distance.
*/
template<typename VecType, typename TreeType>
static size_t GetBestChild(const VecType& queryPoint, TreeType& referenceNode)
{
return referenceNode.GetNearestChild(queryPoint);
};
/**
* Return the best child according to this sort policy. In this case it will
* return the one with the minimum distance.
*/
template<typename TreeType>
static size_t GetBestChild(const TreeType& queryNode, TreeType& referenceNode)
{
return referenceNode.GetNearestChild(queryNode);
};
/**
* Return what should represent the worst possible distance with this
* particular sort policy. In our case, this should be the maximum possible
* distance, DBL_MAX.
*
* @return DBL_MAX
*/
static inline double WorstDistance() { return DBL_MAX; }
/**
* Return what should represent the best possible distance with this
* particular sort policy. In our case, this should be the minimum possible
* distance, 0.0.
*
* @return 0.0
*/
static inline double BestDistance() { return 0.0; }
/**
* Return the best combination of the two distances.
*/
static inline double CombineBest(const double a, const double b)
{
return std::max(a - b, 0.0);
}
/**
* Return the worst combination of the two distances.
*/
static inline double CombineWorst(const double a, const double b)
{
if (a == DBL_MAX || b == DBL_MAX)
return DBL_MAX;
return a + b;
}
/**
* Return the given value relaxed.
*
* @param value Value to relax.
* @param epsilon Relative error (non-negative).
*
* @return double Value relaxed.
*/
static inline double Relax(const double value, const double epsilon)
{
if (value == DBL_MAX)
return DBL_MAX;
return (1 / (1 + epsilon)) * value;
}
/**
* Convert the given distance into a score. Lower scores are better, so in
* the case of nearest neighbor sort where lower distances are better, we just
* return the distance.
*/
static inline double ConvertToScore(const double distance)
{
return distance;
}
/**
* Convert the given score to a distance. This is the inverse of the
* operation provided by ConvertToScore(). For nearest neighbor search, there
* is no need for any change.
*/
static inline double ConvertToDistance(const double score)
{
return score;
}
};
// Due to an internal MinGW compiler bug (string table overflow) we have to
// truncate the class name. For backward compatibility we setup an alias here.
using NearestNeighborSort = NearestNS;
} // namespace neighbor
} // namespace mlpack
// Include implementation of templated functions.
#include "nearest_neighbor_sort_impl.hpp"
#endif
|
#ifndef PCS_HPP
#define PCS_HPP
#include <string>
#include <vector>
#include <memory>
#include <random>
#include "warped.hpp"
WARPED_DEFINE_LP_STATE_STRUCT(PcsState) {
unsigned int idle_channel_cnt_;
unsigned int call_attempts_;
unsigned int channel_blocks_;
unsigned int handoff_blocks_;
};
enum method_t {
NEXT_CALL_METHOD,
COMPLETE_CALL_METHOD,
MOVE_CALL_IN_METHOD,
MOVE_CALL_OUT_METHOD
};
enum action_t {
NEXTCALL,
COMPLETECALL,
MOVECALL
};
enum direction_t {
LEFT,
RIGHT,
DOWN,
UP
};
class PcsEvent : public warped::Event {
public:
PcsEvent() = default;
PcsEvent( const std::string receiver_name,
unsigned int event_ts,
unsigned int complete_call_ts,
unsigned int next_call_ts,
unsigned int move_call_ts,
method_t method )
: receiver_name_(receiver_name),
event_ts_(event_ts),
complete_call_ts_(complete_call_ts),
next_call_ts_(next_call_ts),
move_call_ts_(move_call_ts),
method_(method) {}
const std::string& receiverName() const { return receiver_name_; }
unsigned int timestamp() const { return event_ts_; }
unsigned int size() const {
return receiver_name_.length() +
sizeof(event_ts_) +
sizeof(complete_call_ts_) +
sizeof(next_call_ts_) +
sizeof(move_call_ts_) +
sizeof(method_);
}
std::string receiver_name_;
unsigned int event_ts_;
unsigned int complete_call_ts_;
unsigned int next_call_ts_;
unsigned int move_call_ts_;
method_t method_;
WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this),
receiver_name_, event_ts_, complete_call_ts_,
next_call_ts_, move_call_ts_, method_)
};
class PcsCell : public warped::LogicalProcess {
public:
PcsCell( const std::string& name,
unsigned int num_cells_x,
unsigned int num_cells_y,
unsigned int max_channel_cnt,
unsigned int call_interval_mean,
unsigned int call_duration_mean,
unsigned int move_interval_mean,
unsigned int portable_cnt,
unsigned int index )
: LogicalProcess(name),
state_(),
num_cells_x_(num_cells_x),
num_cells_y_(num_cells_y),
max_channel_cnt_(max_channel_cnt),
call_interval_mean_(call_interval_mean),
call_duration_mean_(call_duration_mean),
move_interval_mean_(move_interval_mean),
portable_init_cnt_(portable_cnt),
index_(index),
rng_(new std::default_random_engine(index)) {
// Update the state variables
state_.idle_channel_cnt_ = max_channel_cnt_;
state_.call_attempts_ = 0;
state_.channel_blocks_ = 0;
state_.handoff_blocks_ = 0;
}
virtual warped::LPState& getState() override { return state_; }
virtual std::vector<std::shared_ptr<warped::Event> > initializeLP() override;
virtual std::vector<std::shared_ptr<warped::Event> > receiveEvent(const warped::Event&) override;
PcsState state_;
protected:
unsigned int num_cells_x_;
unsigned int num_cells_y_;
unsigned int max_channel_cnt_;
unsigned int call_interval_mean_;
unsigned int call_duration_mean_;
unsigned int move_interval_mean_;
unsigned int portable_init_cnt_;
unsigned int index_;
std::shared_ptr<std::default_random_engine> rng_;
unsigned int random_move(unsigned int index);
action_t min_ts(unsigned int complete_call_ts,
unsigned int next_call_ts,
unsigned int move_call_ts);
};
#endif
|
/*!
@file
Defines `boost::hana::detail::index_if`.
@copyright Louis Dionne 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_DETAIL_INDEX_IF_HPP
#define BOOST_HANA_DETAIL_INDEX_IF_HPP
#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>
#include <cstddef>
#include <utility>
BOOST_HANA_NAMESPACE_BEGIN namespace detail {
template <typename ...T>
struct pack {
static constexpr std::size_t length = sizeof...(T);
};
template <typename T>
struct make_pack;
template <template <typename...> class Template, typename ...T>
struct make_pack<Template<T...>> {
using type = pack<T...>;
};
template <typename T> struct make_pack<T const> : make_pack<T> { };
template <typename T> struct make_pack<T&> : make_pack<T> { };
template <typename T> struct make_pack<T&&> : make_pack<T> { };
//! @ingroup group-details
//! Returns the index of the first element of the `pack<>` that satisfies
//! the predicate, or the size of the pack if there is no such element.
//!
//! @note
//! The predicate must return an `IntegralConstant` that can be explicitly
//! converted to `bool`.
template <typename Pred, typename Ts, typename = when<true>>
struct index_if;
//! @cond
template <typename Pred, typename T, typename ...Ts>
struct index_if<Pred, pack<T, Ts...>, when<static_cast<bool>(decltype(
std::declval<Pred>()(std::declval<T>())
)::value)>> {
static constexpr std::size_t value = 0;
};
template <typename Pred, typename T, typename ...Ts>
struct index_if<Pred, pack<T, Ts...>, when<!static_cast<bool>(decltype(
std::declval<Pred>()(std::declval<T>())
)::value)>> {
static constexpr std::size_t value = 1 + index_if<Pred, pack<Ts...>>::value;
};
template <typename Pred>
struct index_if<Pred, pack<>> {
static constexpr std::size_t value = 0;
};
//! @endcond
} BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_DETAIL_INDEX_IF_HPP
|
/*
* (c) Copyright 2011-2013, Hewlett-Packard Development Company, LP
*/
#include "w_defines.h"
/* -- do not edit anything above this line -- </std-header>*/
#define SM_SOURCE
#define SMTHREAD_C
#include <sm_base.h>
#include <w_strstream.h>
SmthreadFunc::~SmthreadFunc()
{
}
/*
* Thread map that will contain OR of all the smthread thread maps.
* This is so that we can determine if we have got too dense and have
* to change the number of bits in the map and recompile.
*/
static atomic_thread_map_t all_fingerprints;
// number of threads that are assigned fingerprints.
// used for a trivial optimization to assign better fingerprints
int s_num_assigned_threads = 0;
queue_based_lock_t s_num_assigned_threads_lock; // to protect s_num_assigned_threads
extern "C"
void clear_all_fingerprints()
{
// called from smsh because smsh has points at which
// this is safe to do, and because it forks off so many threads;
// it can't really create a pool of smthreads.
smthread_t::init_fingerprint_map() ;
}
/**\brief Called on tcb_t constructor.
*/
void
smthread_t::tcb_t::create_TL_stats() {
_TL_stats = new sm_stats_info_t;
// These things have no constructor
clear_TL_stats();
}
/**\brief Called on tcb_t destructor.
*/
void
smthread_t::tcb_t::destroy_TL_stats() {
if(_TL_stats) {
if (smlevel_0::statistics_enabled) {
// Global stats are protected by a mutex
smlevel_0::add_to_global_stats(TL_stats()); // before detaching them
}
delete _TL_stats;
_TL_stats = NULL;
}
}
static smthread_init_t smthread_init;
int smthread_init_t::count = 0;
/*
* smthread_init_t::smthread_init_t()
*/
smthread_init_t::smthread_init_t()
{
}
/*
* smthread_init_t::~smthread_init_t()
*/
smthread_init_t::~smthread_init_t()
{
}
/*********************************************************************
*
* Constructor and destructor for smthread_t::tcb_t
*
*********************************************************************/
void
smthread_t::tcb_t::clear_TL_stats()
{
// Global stats are protected by a mutex
smlevel_0::add_to_global_stats(TL_stats()); // before clearing them
memset(&TL_stats(),0, sizeof(sm_stats_info_t));
}
/* Non-thread-safe add from the per-thread copy to another struct.
* The caller must ensure thread-safety.
* As it turns out, this gets called only from ss_m::gather_stats, which
* assumes that the sm_stats_info_t structure passed in is local or
* proteded by the vas, so the safety of argument w is ok, but
* the thread_local stats might be being updated while this is
* going on.
*/
void
smthread_t::add_from_TL_stats(sm_stats_info_t &w) const
{
const sm_stats_info_t &x = tcb().TL_stats_const();
w += x;
// pick these up from the sthread_t stats structure:
w.sm.rwlock_r_waits += this->SthreadStats.rwlock_r_wait;
w.sm.rwlock_w_waits += this->SthreadStats.rwlock_w_wait;
w.sm.need_latch_condl += this->SthreadStats.needs_latch_condl;
w.sm.latch_condl_nowaits += this->SthreadStats.latch_condl_nowait;
w.sm.need_latch_uncondl += this->SthreadStats.needs_latch_uncondl;
w.sm.latch_uncondl_nowaits += this->SthreadStats.latch_uncondl_nowait;
}
/*********************************************************************
*
* smthread_t::smthread_t
*
* Create an smthread_t.
*
*********************************************************************/
smthread_t::smthread_t(
st_proc_t* f,
void* arg,
priority_t priority,
const char* name,
timeout_in_ms lockto,
unsigned stack_size)
: sthread_t(priority, name, stack_size),
_proc(f),
_arg(arg),
_gen_log_warnings(true)
{
tcb_t *empty_tcb = new tcb_t(NULL);
w_assert1 (empty_tcb != NULL);
_tcb_tail = empty_tcb;
// For now, user pointing to this object
// indicates that the sthread is an smthread. Grot.
user = (void *)&smthread_init;
lock_timeout(lockto);
if(lockto > WAIT_NOT_USED) _initialize_fingerprint();
}
// Used by internal sm threads, e.g., bf_prefetch_thread.
// Uses run() method instead of a method given as argument.
// Does NOT acquire a fingerprint so it cannot acquire locks.
smthread_t::smthread_t(
priority_t priority,
const char* name,
timeout_in_ms lockto,
unsigned stack_size
)
: sthread_t(priority, name, stack_size),
_proc(0),
_arg(0),
_gen_log_warnings(true)
{
tcb_t *empty_tcb = new tcb_t(NULL);
w_assert1 (empty_tcb != NULL);
_tcb_tail = empty_tcb;
// For now, user pointing to this object
// indicates that the sthread is an smthread. Grot.
user =(void *) &smthread_init;
lock_timeout(lockto);
if(lockto > WAIT_NOT_USED) _initialize_fingerprint();
}
void smthread_t::_initialize_fingerprint()
{
// We can see if we might be getting false positives here.
// If we make the finger print maps unique, we can eliminate that
// possibility.
#define DEBUG_FINGERPRINTS 0
#if DEBUG_FINGERPRINTS
int tries=0;
const int trylimit = 50;
bool bad=true;
while ( (bad = _try_initialize_fingerprint()) )
{
_uninitialize_fingerprint();
if(++tries > trylimit) {
fprintf(stderr,
"Could not make non-overlapping fingerprint after %d tries; %d out of %d bits are inuse\n",
tries, all_fingerprints.num_bits_set(), all_fingerprints.num_bits());
// note: there's a race here but if servers are
// creating a pool of threads at start-up, this
// is still useful info:
if(all_fingerprints.is_full()) {
fprintf(stderr,
"collective thread map is full: increase #bits an recompile.\n");
}
W_FATAL(eTHREADMAPFULL);
}
}
#else
(void) _try_initialize_fingerprint();
#endif
}
bool smthread_t::_try_initialize_fingerprint()
{
int copied_num_assigned_threads;
{
CRITICAL_SECTION(cs, s_num_assigned_threads_lock);
copied_num_assigned_threads = s_num_assigned_threads;
++s_num_assigned_threads;
}
if (copied_num_assigned_threads < SM_DREADLOCK_BITCOUNT / FINGER_BITS) {
// if s_num_assigned_threads is enough large, just assign a sequence
for(int i = 0; i < FINGER_BITS; ++i) {
_fingerprint_map.set_bit(FINGER_BITS * copied_num_assigned_threads + i);
}
} else {
/*
Initialize the random fingerprint for this lock_info.
It consists of FINGER_BITS selected uniformly without
replacement from the possible bits in the thread_map.
*/
for( int i=0; i < FINGER_BITS; i++) {
retry:
int rval = me()->randn(atomic_thread_map_t::BITS);
for(int j=0; j < i; j++) {
if(rval == _fingerprint[j])
goto retry;
}
_fingerprint[i] = rval;
}
// Initialize this thread's _fingerprint_map
for(int i=0; i < FINGER_BITS; i++) {
_fingerprint_map.set_bit(_fingerprint[i]);
}
}
#ifndef PROHIBIT_FALSE_POSITIVES
return false;
#else
// This uniqueness check is left in for possible turning on
// when debugging deadlocks; it is so that we can tell if
// we are getting duplicated bits and thus possibly false-positives.
// As long as we are running tests
// that pass this check, we know that we don't have false-positives.
// To turn it on, define PROHIBIT_FALSE_POSITIVES above.
/* Note also that the global map is unable to recycle
fingerprints, putting a hard limit on the number of threads the
system can ever spawn when using this restrictive check.
*/
all_fingerprints.lock_for_write();
atomic_thread_map_t _tmp;
bool first_time = all_fingerprints.is_empty();
int matches = _fingerprint_map.words_overlap(_tmp, all_fingerprints);
bool nonunique = (matches == _fingerprint_map.num_words());
bool failure = (nonunique && !first_time);
if(!failure) {
all_fingerprints.copy(_tmp);
}
all_fingerprints.unlock_writer();
if(failure) {
// INC_TSTAT(nonunique_fingerprints);
tcb()._TL_stats->sm.nonunique_fingerprints++;
// fprintf(stderr,
// "Phooey! overlapping fingerprint map : %d bits used\n",
// all_fingerprints.num_bits_set());
} else {
// INC_TSTAT(unique_fingerprints);
tcb()._TL_stats->sm.unique_fingerprints++;
}
#define DEBUG_DEADLOCK 0
#if DEBUG_DEADLOCK
{
short a=_fingerprint[0];
short b=_fingerprint[1];
short c=_fingerprint[2];
w_ostrstream s;
s << "all_fingerprints " ;
all_fingerprints.print(s);
s << endl;
s << "num_bits_set " << all_fingerprints.num_bits_set() << endl;
if(all_fingerprints.is_full()) {
s << " FULL! " << endl;
}
s
<< "matches=" << matches
<< " num_words()=" << all_fingerprints.num_words()
<< " nonunique=" << nonunique
<< " first_time=" << first_time
<< " failure=" << failure << endl;
s << "_fingerprint_map " ;
_fingerprint_map.print(s) ;
s << endl;
fprintf(stderr,
"%s ------ fingerprint %d.%d.%d\n", s.c_str(), a,b,c);
}
#endif
return failure;
#endif
}
// called from constructor
void smthread_t::init_fingerprint_map()
{
//all_fingerprints.lock_for_write();
all_fingerprints.clear();
//all_fingerprints.unlock_writer();
{
//CRITICAL_SECTION(cs, s_num_assigned_threads_lock);
//s_num_assigned_threads = 0;
}
}
void smthread_t::_uninitialize_fingerprint()
{
_fingerprint_map.clear();
}
/*********************************************************************
*
* smthread_t::join()
*
* invoke sthread_t::join if it's safe to do so
*
*********************************************************************/
w_rc_t
smthread_t::join(timeout_in_ms timeout)
{
w_rc_t rc = this->sthread_t::join(timeout);
if(tcb().xct != NULL) {
return RC(eINTRANS);
}
if(tcb().pin_count != 0)
{
return RC(ePINACTIVE);
}
if( tcb()._xct_log != NULL ) {
fprintf(stderr, "non-null _xct_log on join\n");
return RC(eINTRANS);
}
return rc;
}
/*********************************************************************
*
* smthread_t::~smthread_t()
*
* Destroy smthread. Thread is already defunct the object is
* destroyed.
*
*********************************************************************/
smthread_t::~smthread_t()
{
user = NULL;
if(lock_timeout() > WAIT_NOT_USED) {
_uninitialize_fingerprint();
}
// revoke transaction objects
w_assert2( get_tcb_depth() == 1); // otherwise some transaction is running!
while (_tcb_tail) {
// this should be the empty tcb_t as dummy!
w_assert2( _tcb_tail->xct == NULL);
w_assert2( _tcb_tail->pin_count == 0);
w_assert2( _tcb_tail->_xct_log == 0 );
tcb_t* old = _tcb_tail;
_tcb_tail = _tcb_tail->_outer;
delete old;
}
}
// There's something to be said for having the smthread_unblock
// unblock only those threads that blocked with smthread_block.
// This is to deal with races in the deadlock detection.
// It's possible that a thread that blocked this way will be awakened
// by another force such as timeout, but we need to be sure that we don't
// try here to unblock a thread that didn't block via smthread_block
w_error_codes smthread_t::_smthread_block(
timeout_in_ms timeout,
const char * const W_IFDEBUG9(blockname))
{
_waiting = true;
// rval is set by the unblocker
w_error_codes rval = sthread_t::block(timeout);
_waiting = false;
return rval;
}
w_rc_t smthread_t::_smthread_unblock(w_error_codes e)
{
// We should never be unblocking ourselves.
w_assert1(me() != this);
// tried to unblock the wrong thread
if(!_waiting) {
return RC(eNOTBLOCKED);
}
return this->sthread_t::unblock(e); // should return RCOK to the caller
}
/* thread-compatability block() and unblock. Use the per-smthread _block
as the synchronization primitive. */
w_error_codes smthread_t::smthread_block(timeout_in_ms timeout,
const char * const caller,
const void *)
{
return _smthread_block(timeout, caller);
}
w_rc_t smthread_t::smthread_unblock(w_error_codes e)
{
return _smthread_unblock(e);
}
void smthread_t::before_run() {
sthread_t::before_run();
latch_t::on_thread_init(this); // called after constructor
}
void smthread_t::after_run() { // called before destructor
latch_t::on_thread_destroy(this);
sthread_t::after_run();
}
smthread_t*
smthread_t::dynamic_cast_to_smthread()
{
if(user == (void *)&smthread_init) return this;
return NULL;
}
const smthread_t*
smthread_t::dynamic_cast_to_const_smthread() const
{
if(user == (void *)&smthread_init) return this;
return NULL;
}
class SelectSmthreadsFunc : public ThreadFunc
{
public:
SelectSmthreadsFunc(SmthreadFunc& func) : f(func) {};
void operator()(const sthread_t& thread) {
if (const smthread_t* smthread = thread.dynamic_cast_to_const_smthread())
{
f(*smthread);
}
}
private:
SmthreadFunc& f;
};
void
smthread_t::for_each_smthread(SmthreadFunc& f)
{
SelectSmthreadsFunc g(f);
for_each_thread(g);
}
void
smthread_t::attach_xct(xct_t* x)
{
w_assert0(get_tcb_depth() == 1 || x->is_sys_xct()); // only system transactions can be nested
// add the given transaction as top (outmost) transaction
tcb_t *new_outmost = new tcb_t(_tcb_tail);
w_assert0(new_outmost != NULL);
_tcb_tail = new_outmost;
new_outmost->xct = x;
w_assert0(me()->xct() != NULL);
w_assert0(me()->xct() == x);
x->attach_thread();
// descends to xct_impl::attach_thread()
// which grabs the 1thread mutex, calls new_xct, releases the mutex.
}
void
smthread_t::detach_xct(xct_t* x)
{
// removes the top (outmost) transaction from this thread
if (x != _tcb_tail->xct) {
// are you removing something else??
W_FATAL(eNOTRANS);
}
// descends to xct_impl::detach_thread()
// which grabs the 1thread mutex, calls no_xct, releases the mutex.
x->detach_thread();
// pop the outmost tcb_t after the above which cleans up some property of tcb_t
tcb_t *outmost = _tcb_tail;
_tcb_tail = _tcb_tail->_outer;
delete outmost;
w_assert0(get_tcb_depth() >= 1);
}
/*
* We're attaching x to this thread
*/
void
smthread_t::new_xct(xct_t *x)
{
w_assert1(x);
/* Get the three caches. If the xct doesn't have these stashed,
* it will malloc them for us.
*/
DBG(<<"new_xct: id=" << me()->id);
x->steal(tcb()._xct_log);
}
/**\brief Called to effect a detach_xct().
*
* \details
* N Threads point to 1 xct_t; xct_ts do not point to threads because
* of the 1:N relationship.
*
* A thread holds some cached info on behalf of a transaction.
* This is in 3 structures. If a thread were attached to a transaction
* for the transaction's duration, we wouldn't go to this trouble, but
* because threads attach/detach, reattach/detach and perhaps several
* threads act for an xct at once, we try to avoid the excess heap
* activity and cache-repopulation that would result.
*
* When a thread/xct relationship is broken, the thread tries to stash
* its caches in the xct_t structure. If the xct subsequently goes
* away, the xct deletes these caches and returns them to the global heap.
* If another thread attaches to the xct, it will grab these structures
* from the xct at attach-time.
*
* This smthread can only stash these caches in the xct_t if the xct_t
* doesn't already have some stashed. In other words, if 3 threads
* detach from the same xct in succession, the first thread's caches will
* be stashed in the xct and the other 2 will be returned to the heap.
* If these 3 sthreads subsequently reattach to the same xct, the first
* one to attach will steal back the caches and the next two will
* allocate from the heap.
*
* In addition to these 3 caches, the thread holds statistics for
* an instrumented transaction.
*/
void
smthread_t::no_xct(xct_t *x)
{
w_assert3(x);
/* collect summary statistics */
// Don't collect again if we already detached. If we did
// already detach, the stats values should be 0 to it would
// be correct if we did this, but it's needless work.
//
if(tcb().xct == x)
{
if(x->is_instrumented())
{
// NOTE: thread-safety comes from the fact that this is called from
// xct_impl::detach_thread, which first grabs the 1thread-at-a-time
// mutex.
sm_stats_info_t &s = x->stats_ref();
/*
* s refers to the __stats passed in on begin_xct() for an
* instrumented transaction.
* We add in the per-thread stats and zero out the per-thread copy.
* This means that if we are collecting stats on a per-xct basis,
* these stats don't get counted in the global stats.
*
* Note also that this is a non-atomic add.
*/
s += TL_stats(); // sm_stats_info_t
/*
* The stats have been added into the xct's structure,
* so they must be cleared for the thread.
*/
tcb().clear_TL_stats();
}
/* See comments in smthread_t::new_xct() */
x->stash(tcb()._xct_log);
}
}
void
smthread_t::_dump(ostream &o) const
{
sthread_t *t = (sthread_t *)this;
t->sthread_t::_dump(o);
o << "smthread_t: " << (char *)(is_in_sm()?"in sm ":"") << endl;
o << "transactions in this thread (from bottom):" << endl;
for (tcb_t* tcb = _tcb_tail; tcb != NULL; tcb = tcb->_outer) {
o << "xct ";
if (tcb->xct) {
o << tcb->xct->tid() << (tcb->xct->is_sys_xct() ? "(sys_xct)" : "(usr_xct)");
} else {
o << "<NULL xct>";
}
o << endl;
}
}
class PrintBlockedThread : public ThreadFunc
{
public:
PrintBlockedThread(ostream& o) : out(o) {};
~PrintBlockedThread() {};
void operator()(const sthread_t& thread)
{
if (thread.status() == sthread_t::t_blocked) {
out << "*******" << endl;
thread._dump(out);
}
};
private:
ostream& out;
};
void
DumpBlockedThreads(ostream& o)
{
PrintBlockedThread f(o);
sthread_t::for_each_thread(f);
}
|
#include <stdio.h>
#include "ServoController.h"
// Array for iterating over all servo locations.
ServoController::servoLocation servoLocations[12] = {
ServoController::kServoLocationFrontRightTip,
ServoController::kServoLocationFrontRightMiddle,
ServoController::kServoLocationFrontRightBase,
ServoController::kServoLocationFrontLeftTip,
ServoController::kServoLocationFrontLeftMiddle,
ServoController::kServoLocationFrontLeftBase,
ServoController::kServoLocationBackRightTip,
ServoController::kServoLocationBackRightMiddle,
ServoController::kServoLocationBackRightBase,
ServoController::kServoLocationBackLeftTip,
ServoController::kServoLocationBackLeftMiddle,
ServoController::kServoLocationBackLeftBase};
int main(){
const int controllerAddress = 0x40;
ServoController servoController = ServoController();
servoController.connectToAddress(controllerAddress);
servoController.setupServoController();
for (ServoController::servoLocation servo : servoLocations){
servoController.setServoAmount(0,servo);
}
}
|
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#include "Test.h"
#include "GrContextPriv.h"
#include "GrDeinstantiateProxyTracker.h"
#include "GrGpu.h"
#include "GrProxyProvider.h"
#include "GrResourceAllocator.h"
#include "GrResourceProvider.h"
#include "GrSurfaceProxyPriv.h"
#include "GrTexture.h"
#include "GrTextureProxy.h"
#include "SkSurface.h"
struct ProxyParams {
int fSize;
bool fIsRT;
SkColorType fColorType;
SkBackingFit fFit;
int fSampleCnt;
GrSurfaceOrigin fOrigin;
// TODO: do we care about mipmapping
};
static GrSurfaceProxy* make_deferred(GrProxyProvider* proxyProvider, const GrCaps* caps,
const ProxyParams& p) {
GrColorType grCT = SkColorTypeToGrColorType(p.fColorType);
GrPixelConfig config = GrColorTypeToPixelConfig(grCT, GrSRGBEncoded::kNo);
GrSurfaceDesc desc;
desc.fFlags = p.fIsRT ? kRenderTarget_GrSurfaceFlag : kNone_GrSurfaceFlags;
desc.fWidth = p.fSize;
desc.fHeight = p.fSize;
desc.fConfig = config;
desc.fSampleCnt = p.fSampleCnt;
const GrBackendFormat format = caps->getBackendFormatFromColorType(p.fColorType);
auto tmp = proxyProvider->createProxy(format, desc, p.fOrigin, p.fFit, SkBudgeted::kNo);
if (!tmp) {
return nullptr;
}
GrSurfaceProxy* ret = tmp.release();
// Add a read to keep the proxy around but unref it so its backing surfaces can be recycled
ret->addPendingRead();
ret->unref();
return ret;
}
static GrSurfaceProxy* make_backend(GrContext* context, const ProxyParams& p,
GrBackendTexture* backendTex) {
GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider();
GrGpu* gpu = context->contextPriv().getGpu();
*backendTex = gpu->createTestingOnlyBackendTexture(nullptr, p.fSize, p.fSize,
p.fColorType, false,
GrMipMapped::kNo);
if (!backendTex->isValid()) {
return nullptr;
}
auto tmp = proxyProvider->wrapBackendTexture(*backendTex, p.fOrigin, kBorrow_GrWrapOwnership,
GrWrapCacheable::kNo, kRead_GrIOType);
if (!tmp) {
return nullptr;
}
GrSurfaceProxy* ret = tmp.release();
// Add a read to keep the proxy around but unref it so its backing surfaces can be recycled
ret->addPendingRead();
ret->unref();
return ret;
}
static void cleanup_backend(GrContext* context, const GrBackendTexture& backendTex) {
context->contextPriv().getGpu()->deleteTestingOnlyBackendTexture(backendTex);
}
// Basic test that two proxies with overlapping intervals and compatible descriptors are
// assigned different GrSurfaces.
static void overlap_test(skiatest::Reporter* reporter, GrResourceProvider* resourceProvider,
GrSurfaceProxy* p1, GrSurfaceProxy* p2, bool expectedResult) {
GrDeinstantiateProxyTracker deinstantiateTracker;
GrResourceAllocator alloc(resourceProvider, &deinstantiateTracker);
alloc.addInterval(p1, 0, 4);
alloc.addInterval(p2, 1, 2);
alloc.markEndOfOpList(0);
int startIndex, stopIndex;
GrResourceAllocator::AssignError error;
alloc.assign(&startIndex, &stopIndex, &error);
REPORTER_ASSERT(reporter, GrResourceAllocator::AssignError::kNoError == error);
REPORTER_ASSERT(reporter, p1->peekSurface());
REPORTER_ASSERT(reporter, p2->peekSurface());
bool doTheBackingStoresMatch = p1->underlyingUniqueID() == p2->underlyingUniqueID();
REPORTER_ASSERT(reporter, expectedResult == doTheBackingStoresMatch);
}
// Test various cases when two proxies do not have overlapping intervals.
// This mainly acts as a test of the ResourceAllocator's free pool.
static void non_overlap_test(skiatest::Reporter* reporter, GrResourceProvider* resourceProvider,
GrSurfaceProxy* p1, GrSurfaceProxy* p2,
bool expectedResult) {
GrDeinstantiateProxyTracker deinstantiateTracker;
GrResourceAllocator alloc(resourceProvider, &deinstantiateTracker);
alloc.addInterval(p1, 0, 2);
alloc.addInterval(p2, 3, 5);
alloc.markEndOfOpList(0);
int startIndex, stopIndex;
GrResourceAllocator::AssignError error;
alloc.assign(&startIndex, &stopIndex, &error);
REPORTER_ASSERT(reporter, GrResourceAllocator::AssignError::kNoError == error);
REPORTER_ASSERT(reporter, p1->peekSurface());
REPORTER_ASSERT(reporter, p2->peekSurface());
bool doTheBackingStoresMatch = p1->underlyingUniqueID() == p2->underlyingUniqueID();
REPORTER_ASSERT(reporter, expectedResult == doTheBackingStoresMatch);
}
bool GrResourceProvider::testingOnly_setExplicitlyAllocateGPUResources(bool newValue) {
bool oldValue = fExplicitlyAllocateGPUResources;
fExplicitlyAllocateGPUResources = newValue;
return oldValue;
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ResourceAllocatorTest, reporter, ctxInfo) {
const GrCaps* caps = ctxInfo.grContext()->contextPriv().caps();
GrProxyProvider* proxyProvider = ctxInfo.grContext()->contextPriv().proxyProvider();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
bool orig = resourceProvider->testingOnly_setExplicitlyAllocateGPUResources(true);
struct TestCase {
ProxyParams fP1;
ProxyParams fP2;
bool fExpectation;
};
constexpr bool kRT = true;
constexpr bool kNotRT = false;
constexpr bool kShare = true;
constexpr bool kDontShare = false;
// Non-RT GrSurfaces are never recycled on some platforms.
bool kConditionallyShare = resourceProvider->caps()->reuseScratchTextures();
const SkColorType kRGBA = kRGBA_8888_SkColorType;
const SkColorType kBGRA = kBGRA_8888_SkColorType;
const SkBackingFit kE = SkBackingFit::kExact;
const SkBackingFit kA = SkBackingFit::kApprox;
const GrSurfaceOrigin kTL = kTopLeft_GrSurfaceOrigin;
const GrSurfaceOrigin kBL = kBottomLeft_GrSurfaceOrigin;
//--------------------------------------------------------------------------------------------
TestCase gOverlappingTests[] = {
//----------------------------------------------------------------------------------------
// Two proxies with overlapping intervals and compatible descriptors should never share
// RT version
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 64, kRT, kRGBA, kA, 0, kTL }, kDontShare },
// non-RT version
{ { 64, kNotRT, kRGBA, kA, 0, kTL }, { 64, kNotRT, kRGBA, kA, 0, kTL }, kDontShare },
};
for (auto test : gOverlappingTests) {
GrSurfaceProxy* p1 = make_deferred(proxyProvider, caps, test.fP1);
GrSurfaceProxy* p2 = make_deferred(proxyProvider, caps, test.fP2);
overlap_test(reporter, resourceProvider, p1, p2, test.fExpectation);
p1->completedRead();
p2->completedRead();
}
int k2 = ctxInfo.grContext()->contextPriv().caps()->getRenderTargetSampleCount(
2, kRGBA_8888_GrPixelConfig);
int k4 = ctxInfo.grContext()->contextPriv().caps()->getRenderTargetSampleCount(
4, kRGBA_8888_GrPixelConfig);
//--------------------------------------------------------------------------------------------
TestCase gNonOverlappingTests[] = {
//----------------------------------------------------------------------------------------
// Two non-overlapping intervals w/ compatible proxies should share
// both same size & approx
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 64, kRT, kRGBA, kA, 0, kTL }, kShare },
{ { 64, kNotRT, kRGBA, kA, 0, kTL }, { 64, kNotRT, kRGBA, kA, 0, kTL }, kConditionallyShare },
// diffs sizes but still approx
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 50, kRT, kRGBA, kA, 0, kTL }, kShare },
{ { 64, kNotRT, kRGBA, kA, 0, kTL }, { 50, kNotRT, kRGBA, kA, 0, kTL }, kConditionallyShare },
// sames sizes but exact
{ { 64, kRT, kRGBA, kE, 0, kTL }, { 64, kRT, kRGBA, kE, 0, kTL }, kShare },
{ { 64, kNotRT, kRGBA, kE, 0, kTL }, { 64, kNotRT, kRGBA, kE, 0, kTL }, kConditionallyShare },
//----------------------------------------------------------------------------------------
// Two non-overlapping intervals w/ different exact sizes should not share
{ { 56, kRT, kRGBA, kE, 0, kTL }, { 54, kRT, kRGBA, kE, 0, kTL }, kDontShare },
// Two non-overlapping intervals w/ _very different_ approx sizes should not share
{ { 255, kRT, kRGBA, kA, 0, kTL }, { 127, kRT, kRGBA, kA, 0, kTL }, kDontShare },
// Two non-overlapping intervals w/ different MSAA sample counts should not share
{ { 64, kRT, kRGBA, kA, k2, kTL },{ 64, kRT, kRGBA, kA, k4, kTL}, k2 == k4 },
// Two non-overlapping intervals w/ different configs should not share
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 64, kRT, kBGRA, kA, 0, kTL }, kDontShare },
// Two non-overlapping intervals w/ different RT classifications should never share
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 64, kNotRT, kRGBA, kA, 0, kTL }, kDontShare },
{ { 64, kNotRT, kRGBA, kA, 0, kTL }, { 64, kRT, kRGBA, kA, 0, kTL }, kDontShare },
// Two non-overlapping intervals w/ different origins should share
{ { 64, kRT, kRGBA, kA, 0, kTL }, { 64, kRT, kRGBA, kA, 0, kBL }, kShare },
};
for (auto test : gNonOverlappingTests) {
GrSurfaceProxy* p1 = make_deferred(proxyProvider, caps, test.fP1);
GrSurfaceProxy* p2 = make_deferred(proxyProvider, caps, test.fP2);
if (!p1 || !p2) {
continue; // creation can fail (i.e., for msaa4 on iOS)
}
non_overlap_test(reporter, resourceProvider, p1, p2, test.fExpectation);
p1->completedRead();
p2->completedRead();
}
{
// Wrapped backend textures should never be reused
TestCase t[1] = {
{ { 64, kNotRT, kRGBA, kE, 0, kTL }, { 64, kNotRT, kRGBA, kE, 0, kTL }, kDontShare }
};
GrBackendTexture backEndTex;
GrSurfaceProxy* p1 = make_backend(ctxInfo.grContext(), t[0].fP1, &backEndTex);
GrSurfaceProxy* p2 = make_deferred(proxyProvider, caps, t[0].fP2);
non_overlap_test(reporter, resourceProvider, p1, p2, t[0].fExpectation);
p1->completedRead();
p2->completedRead();
cleanup_backend(ctxInfo.grContext(), backEndTex);
}
resourceProvider->testingOnly_setExplicitlyAllocateGPUResources(orig);
}
static void draw(GrContext* context) {
SkImageInfo ii = SkImageInfo::Make(1024, 1024, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
sk_sp<SkSurface> s = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes,
ii, 1, kTopLeft_GrSurfaceOrigin, nullptr);
SkCanvas* c = s->getCanvas();
c->clear(SK_ColorBLACK);
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ResourceAllocatorStressTest, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
int maxNum;
size_t maxBytes;
context->getResourceCacheLimits(&maxNum, &maxBytes);
bool orig = resourceProvider->testingOnly_setExplicitlyAllocateGPUResources(true);
context->setResourceCacheLimits(0, 0); // We'll always be overbudget
draw(context);
draw(context);
draw(context);
draw(context);
context->flush();
context->setResourceCacheLimits(maxNum, maxBytes);
resourceProvider->testingOnly_setExplicitlyAllocateGPUResources(orig);
}
sk_sp<GrSurfaceProxy> make_lazy(GrProxyProvider* proxyProvider, const GrCaps* caps,
const ProxyParams& p, bool deinstantiate) {
GrColorType grCT = SkColorTypeToGrColorType(p.fColorType);
GrPixelConfig config = GrColorTypeToPixelConfig(grCT, GrSRGBEncoded::kNo);
GrSurfaceDesc desc;
desc.fFlags = p.fIsRT ? kRenderTarget_GrSurfaceFlag : kNone_GrSurfaceFlags;
desc.fWidth = p.fSize;
desc.fHeight = p.fSize;
desc.fConfig = config;
desc.fSampleCnt = p.fSampleCnt;
SkBackingFit fit = p.fFit;
auto callback = [fit, desc](GrResourceProvider* resourceProvider) -> sk_sp<GrSurface> {
if (!resourceProvider) {
return nullptr;
}
if (fit == SkBackingFit::kApprox) {
return resourceProvider->createApproxTexture(desc, GrResourceProvider::Flags::kNone);
} else {
return resourceProvider->createTexture(desc, SkBudgeted::kNo);
}
};
const GrBackendFormat format = caps->getBackendFormatFromColorType(p.fColorType);
auto lazyType = deinstantiate ? GrSurfaceProxy::LazyInstantiationType ::kDeinstantiate
: GrSurfaceProxy::LazyInstantiationType ::kSingleUse;
GrInternalSurfaceFlags flags = GrInternalSurfaceFlags::kNone;
return proxyProvider->createLazyProxy(callback, format, desc, p.fOrigin, GrMipMapped::kNo,
flags, p.fFit, SkBudgeted::kNo, lazyType);
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(LazyDeinstantiation, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
for (auto explicitlyAllocating : {false, true}) {
resourceProvider->testingOnly_setExplicitlyAllocateGPUResources(explicitlyAllocating);
ProxyParams texParams;
texParams.fFit = SkBackingFit::kExact;
texParams.fOrigin = kTopLeft_GrSurfaceOrigin;
texParams.fColorType = kRGBA_8888_SkColorType;
texParams.fIsRT = false;
texParams.fSampleCnt = 1;
texParams.fSize = 100;
ProxyParams rtParams = texParams;
rtParams.fIsRT = true;
auto proxyProvider = context->contextPriv().proxyProvider();
auto caps = context->contextPriv().caps();
auto p0 = make_lazy(proxyProvider, caps, texParams, true);
auto p1 = make_lazy(proxyProvider, caps, texParams, false);
texParams.fFit = rtParams.fFit = SkBackingFit::kApprox;
auto p2 = make_lazy(proxyProvider, caps, rtParams, true);
auto p3 = make_lazy(proxyProvider, caps, rtParams, false);
GrDeinstantiateProxyTracker deinstantiateTracker;
{
GrResourceAllocator alloc(resourceProvider, &deinstantiateTracker);
alloc.addInterval(p0.get(), 0, 1);
alloc.addInterval(p1.get(), 0, 1);
alloc.addInterval(p2.get(), 0, 1);
alloc.addInterval(p3.get(), 0, 1);
alloc.markEndOfOpList(0);
int startIndex, stopIndex;
GrResourceAllocator::AssignError error;
alloc.assign(&startIndex, &stopIndex, &error);
}
deinstantiateTracker.deinstantiateAllProxies();
REPORTER_ASSERT(reporter, !p0->isInstantiated());
REPORTER_ASSERT(reporter, p1->isInstantiated());
REPORTER_ASSERT(reporter, !p2->isInstantiated());
REPORTER_ASSERT(reporter, p3->isInstantiated());
}
}
|
// 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.
#include "arrow/json/converter.h"
#include <memory>
#include <utility>
#include "arrow/array.h"
#include "arrow/array/builder_binary.h"
#include "arrow/array/builder_primitive.h"
#include "arrow/array/builder_time.h"
#include "arrow/json/parser.h"
#include "arrow/type.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/logging.h"
#include "arrow/util/string_view.h"
#include "arrow/util/value_parsing.h"
namespace arrow {
namespace json {
using internal::checked_cast;
using util::string_view;
template <typename... Args>
Status GenericConversionError(const DataType& type, Args&&... args) {
return Status::Invalid("Failed of conversion of JSON to ", type,
std::forward<Args>(args)...);
}
namespace {
const DictionaryArray& GetDictionaryArray(const std::shared_ptr<Array>& in) {
DCHECK_EQ(in->type_id(), Type::DICTIONARY);
auto dict_type = static_cast<const DictionaryType*>(in->type().get());
DCHECK_EQ(dict_type->index_type()->id(), Type::INT32);
DCHECK_EQ(dict_type->value_type()->id(), Type::STRING);
return static_cast<const DictionaryArray&>(*in);
}
template <typename ValidVisitor, typename NullVisitor>
Status VisitDictionaryEntries(const DictionaryArray& dict_array,
ValidVisitor&& visit_valid, NullVisitor&& visit_null) {
const StringArray& dict = static_cast<const StringArray&>(*dict_array.dictionary());
const Int32Array& indices = static_cast<const Int32Array&>(*dict_array.indices());
for (int64_t i = 0; i < indices.length(); ++i) {
if (indices.IsValid(i)) {
RETURN_NOT_OK(visit_valid(dict.GetView(indices.GetView(i))));
} else {
RETURN_NOT_OK(visit_null());
}
}
return Status::OK();
}
} // namespace
// base class for types which accept and output non-nested types
class PrimitiveConverter : public Converter {
public:
PrimitiveConverter(MemoryPool* pool, std::shared_ptr<DataType> out_type)
: Converter(pool, out_type) {}
};
class NullConverter : public PrimitiveConverter {
public:
using PrimitiveConverter::PrimitiveConverter;
Status Convert(const std::shared_ptr<Array>& in, std::shared_ptr<Array>* out) override {
if (in->type_id() != Type::NA) {
return GenericConversionError(*out_type_, " from ", *in->type());
}
*out = in;
return Status::OK();
}
};
class BooleanConverter : public PrimitiveConverter {
public:
using PrimitiveConverter::PrimitiveConverter;
Status Convert(const std::shared_ptr<Array>& in, std::shared_ptr<Array>* out) override {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(boolean(), in->length(), pool_).Value(out);
}
if (in->type_id() != Type::BOOL) {
return GenericConversionError(*out_type_, " from ", *in->type());
}
*out = in;
return Status::OK();
}
};
template <typename T>
class NumericConverter : public PrimitiveConverter {
public:
using value_type = typename T::c_type;
NumericConverter(MemoryPool* pool, const std::shared_ptr<DataType>& type)
: PrimitiveConverter(pool, type), numeric_type_(checked_cast<const T&>(*type)) {}
Status Convert(const std::shared_ptr<Array>& in, std::shared_ptr<Array>* out) override {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
const auto& dict_array = GetDictionaryArray(in);
using Builder = typename TypeTraits<T>::BuilderType;
Builder builder(out_type_, pool_);
RETURN_NOT_OK(builder.Resize(dict_array.indices()->length()));
auto visit_valid = [&](string_view repr) {
value_type value;
if (!internal::ParseValue(numeric_type_, repr.data(), repr.size(), &value)) {
return GenericConversionError(*out_type_, ", couldn't parse:", repr);
}
builder.UnsafeAppend(value);
return Status::OK();
};
auto visit_null = [&]() {
builder.UnsafeAppendNull();
return Status::OK();
};
RETURN_NOT_OK(VisitDictionaryEntries(dict_array, visit_valid, visit_null));
return builder.Finish(out);
}
const T& numeric_type_;
};
template <typename DateTimeType>
class DateTimeConverter : public PrimitiveConverter {
public:
DateTimeConverter(MemoryPool* pool, const std::shared_ptr<DataType>& type)
: PrimitiveConverter(pool, type), converter_(pool, repr_type()) {}
Status Convert(const std::shared_ptr<Array>& in, std::shared_ptr<Array>* out) override {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
std::shared_ptr<Array> repr;
RETURN_NOT_OK(converter_.Convert(in, &repr));
auto out_data = repr->data()->Copy();
out_data->type = out_type_;
*out = MakeArray(out_data);
return Status::OK();
}
private:
using ReprType = typename CTypeTraits<typename DateTimeType::c_type>::ArrowType;
static std::shared_ptr<DataType> repr_type() {
return TypeTraits<ReprType>::type_singleton();
}
NumericConverter<ReprType> converter_;
};
template <typename T>
class BinaryConverter : public PrimitiveConverter {
public:
using PrimitiveConverter::PrimitiveConverter;
Status Convert(const std::shared_ptr<Array>& in, std::shared_ptr<Array>* out) override {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
const auto& dict_array = GetDictionaryArray(in);
using Builder = typename TypeTraits<T>::BuilderType;
Builder builder(out_type_, pool_);
RETURN_NOT_OK(builder.Resize(dict_array.indices()->length()));
// TODO(bkietz) this can be computed during parsing at low cost
int64_t data_length = 0;
auto visit_lengths_valid = [&](string_view value) {
data_length += value.size();
return Status::OK();
};
auto visit_lengths_null = [&]() {
// no-op
return Status::OK();
};
RETURN_NOT_OK(
VisitDictionaryEntries(dict_array, visit_lengths_valid, visit_lengths_null));
RETURN_NOT_OK(builder.ReserveData(data_length));
auto visit_valid = [&](string_view value) {
builder.UnsafeAppend(value);
return Status::OK();
};
auto visit_null = [&]() {
builder.UnsafeAppendNull();
return Status::OK();
};
RETURN_NOT_OK(VisitDictionaryEntries(dict_array, visit_valid, visit_null));
return builder.Finish(out);
}
};
Status MakeConverter(const std::shared_ptr<DataType>& out_type, MemoryPool* pool,
std::shared_ptr<Converter>* out) {
switch (out_type->id()) {
#define CONVERTER_CASE(TYPE_ID, CONVERTER_TYPE) \
case TYPE_ID: \
*out = std::make_shared<CONVERTER_TYPE>(pool, out_type); \
break
CONVERTER_CASE(Type::NA, NullConverter);
CONVERTER_CASE(Type::BOOL, BooleanConverter);
CONVERTER_CASE(Type::INT8, NumericConverter<Int8Type>);
CONVERTER_CASE(Type::INT16, NumericConverter<Int16Type>);
CONVERTER_CASE(Type::INT32, NumericConverter<Int32Type>);
CONVERTER_CASE(Type::INT64, NumericConverter<Int64Type>);
CONVERTER_CASE(Type::UINT8, NumericConverter<UInt8Type>);
CONVERTER_CASE(Type::UINT16, NumericConverter<UInt16Type>);
CONVERTER_CASE(Type::UINT32, NumericConverter<UInt32Type>);
CONVERTER_CASE(Type::UINT64, NumericConverter<UInt64Type>);
CONVERTER_CASE(Type::FLOAT, NumericConverter<FloatType>);
CONVERTER_CASE(Type::DOUBLE, NumericConverter<DoubleType>);
CONVERTER_CASE(Type::TIMESTAMP, NumericConverter<TimestampType>);
CONVERTER_CASE(Type::TIME32, DateTimeConverter<Time32Type>);
CONVERTER_CASE(Type::TIME64, DateTimeConverter<Time64Type>);
CONVERTER_CASE(Type::DATE32, DateTimeConverter<Date32Type>);
CONVERTER_CASE(Type::DATE64, DateTimeConverter<Date64Type>);
CONVERTER_CASE(Type::BINARY, BinaryConverter<BinaryType>);
CONVERTER_CASE(Type::STRING, BinaryConverter<StringType>);
CONVERTER_CASE(Type::LARGE_BINARY, BinaryConverter<LargeBinaryType>);
CONVERTER_CASE(Type::LARGE_STRING, BinaryConverter<LargeStringType>);
default:
return Status::NotImplemented("JSON conversion to ", *out_type,
" is not supported");
#undef CONVERTER_CASE
}
return Status::OK();
}
const PromotionGraph* GetPromotionGraph() {
static struct : PromotionGraph {
std::shared_ptr<Field> Null(const std::string& name) const override {
return field(name, null(), true, Kind::Tag(Kind::kNull));
}
std::shared_ptr<DataType> Infer(
const std::shared_ptr<Field>& unexpected_field) const override {
auto kind = Kind::FromTag(unexpected_field->metadata());
switch (kind) {
case Kind::kNull:
return null();
case Kind::kBoolean:
return boolean();
case Kind::kNumber:
return int64();
case Kind::kString:
return timestamp(TimeUnit::SECOND);
case Kind::kArray: {
auto type = static_cast<const ListType*>(unexpected_field->type().get());
auto value_field = type->value_field();
return list(value_field->WithType(Infer(value_field)));
}
case Kind::kObject: {
auto fields = unexpected_field->type()->fields();
for (auto& field : fields) {
field = field->WithType(Infer(field));
}
return struct_(std::move(fields));
}
default:
return nullptr;
}
}
std::shared_ptr<DataType> Promote(
const std::shared_ptr<DataType>& failed,
const std::shared_ptr<Field>& unexpected_field) const override {
switch (failed->id()) {
case Type::NA:
return Infer(unexpected_field);
case Type::TIMESTAMP:
return utf8();
case Type::INT64:
return float64();
default:
return nullptr;
}
}
} impl;
return &impl;
}
} // namespace json
} // namespace arrow
|
// license:BSD-3-Clause
// copyright-holders:Miodrag Milanovic
/***************************************************************************
Elektronika MK-85
12/05/2009 Skeleton driver.
http://www.taswegian.com/MOSCOW/mk-85.html
This is a Soviet computer-calculator, very similar in looks to the Sharp.
It has a LCD display.
Models:
MK-85: 2K of RAM
MK-85M: 6K of RAM
MK-85C: Military cryptographic device. Typing text into it produces
a string of numbers.
****************************************************************************/
#include "emu.h"
#include "cpu/t11/t11.h"
#include "screen.h"
class mk85_state : public driver_device
{
public:
mk85_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
{
}
virtual void machine_reset() override;
virtual void video_start() override;
uint32_t screen_update_mk85(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
required_device<cpu_device> m_maincpu;
void mk85(machine_config &config);
void mk85_mem(address_map &map);
};
void mk85_state::mk85_mem(address_map &map)
{
map.unmap_value_high();
map(0x0000, 0x3fff).rom().mirror(0x4000);
map(0x8000, 0xffff).ram();
}
/* Input ports */
static INPUT_PORTS_START( mk85 )
INPUT_PORTS_END
void mk85_state::machine_reset()
{
}
void mk85_state::video_start()
{
}
uint32_t mk85_state::screen_update_mk85(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
return 0;
}
MACHINE_CONFIG_START(mk85_state::mk85)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", K1801VM2, XTAL(4'000'000))
MCFG_T11_INITIAL_MODE(0)
MCFG_CPU_PROGRAM_MAP(mk85_mem)
/* video hardware */
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */
MCFG_SCREEN_SIZE(640, 480)
MCFG_SCREEN_VISIBLE_AREA(0, 640-1, 0, 480-1)
MCFG_SCREEN_UPDATE_DRIVER(mk85_state, screen_update_mk85)
MCFG_SCREEN_PALETTE("palette")
MCFG_PALETTE_ADD_MONOCHROME("palette")
MACHINE_CONFIG_END
/* ROM definition */
ROM_START( mk85 )
ROM_REGION( 0x10000, "maincpu", ROMREGION_ERASEFF )
ROM_LOAD( "mk85.rom", 0x0000, 0x4000, CRC(398e4fd1) SHA1(5e2f877d0f451b46840f01190004552bad5248c8))
ROM_END
/* Driver */
/* YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS */
COMP( 1986, mk85, 0, 0, mk85, mk85, mk85_state, 0, "Elektronika", "MK-85", MACHINE_NOT_WORKING | MACHINE_NO_SOUND)
|
#include "Callclient.h"
#include "cems_net.h"
#define CEMS_CLIENT_UDP 22116
#define BUFFER_SIZE 1024*5
//#define MAX_UDP_CODE 0x10100
//#define MIN_UDP_CODE 0x4
using namespace std;
MCallClient::MCallClient(void)
{
}
MCallClient::~MCallClient(void)
{
}
std::string MCallClient::Read(std::string szKey)
{
BOOL bRet = FALSE;
std::string szValue;
return szValue;
}
std::string MCallClient::ReadXml(std::string szElementName, std::string szKey, std::string szXml)
{
std::string szReadValue;
return szReadValue;
}
DWORD MCallClient::GetLocalUdpPort()
{
DWORD dwPort = CEMS_CLIENT_UDP;
std::string szXml = Read("NetConfig");
if(!szXml.empty())
{
dwPort = atoi(ReadXml("udpServer", "Port", szXml).c_str());
if(dwPort == 0)
{
dwPort = CEMS_CLIENT_UDP;
}
}
return dwPort;
}
std::string MCallClient::GetHostName()
{
char name[MAX_PATH] = {0};
int iLen = MAX_PATH;
std::string szName;
if(gethostname(name, iLen) == 0)
{
szName = name;
}
return szName;
}
extern unsigned int crc32(unsigned int crc, const void *buf, unsigned int size);
//udpP2p
bool MCallClient::Call(DWORD & dwBegin, DWORD & dwEnd)
{
m_vResult.clear();
SOCKET SendSocket;
sockaddr_in toAddr;
string szHeader;
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == SendSocket)
{
return false;
}
toAddr.sin_family = AF_INET;
//emsstore.dat 读取CEMS_TRAY;netconfig udp port
toAddr.sin_port = htons(GetLocalUdpPort());
struct timeval tv_out = {2, 0};
//recvfrom 设置超时
setsockopt(SendSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv_out, sizeof(tv_out));
//组包
Json::Value root;
Json::FastWriter writer;
char name[MAX_PATH] = {0};
hostent *phostinfo;
std::string szCurrentIp;
if( gethostname ( name, sizeof(name)) == 0)
{
if((phostinfo = gethostbyname(name)))
{
szCurrentIp = inet_ntoa(*(struct in_addr *)phostinfo->h_addr_list);
}
}
root["ip"] = szCurrentIp;
std::string szQueryJson = writer.write(root);
_CEMS_NET_HEAD header = {0};
DWORD dwJsonSize = (DWORD)szQueryJson.size();
DWORD dwCrc = 0xffffffff;
header.dwFlag = 'pde_';
header.dwVersion = (1);
header.dwDataSize = dwJsonSize;
header.dwCrc = crc32(dwCrc, (void*)szQueryJson.c_str(), szQueryJson.size());
//header.szSessionId = {0};
header.dwMsgCode = (1);
header.dwMaxCode = ((unsigned long)CEMS_MAXCODE_SCAN);
header.dwMinCode = ((unsigned long)CEMS_MINCODE_SCAN_TASK);
header.wHeadSize = sizeof(header);
header.wType = (0);
header.wCount = (1);
header.wIndex = (1);
DWORD dwSize = sizeof(header) + dwJsonSize;
char * pbuffer = new char[dwSize];
memcpy(pbuffer, &header, sizeof(header));
memcpy(pbuffer + sizeof(header), szQueryJson.c_str(),szQueryJson.size());
DWORD dwSendLen = sizeof(header) + dwJsonSize;
for(ULONG uip = dwBegin; uip <= dwEnd; uip ++)
{
toAddr.sin_addr.s_addr = htonl(uip);
int sent = sendto(SendSocket, pbuffer, dwSendLen, 0, (const struct sockaddr*) &toAddr, sizeof(toAddr));
if(sent == SOCKET_ERROR)
{
printf("sendto fail.\n");
}
}
delete []pbuffer;
RecvUdp(SendSocket);
close(SendSocket);
return true;
}
void MCallClient::RecvUdp(SOCKET& sock)
{
sockaddr_in fromAddr;
int ReceiveAddrSize = sizeof(fromAddr);
static int nRecvConut = 0;
while(1)
{
int ret;
fd_set fst;
FD_ZERO(&fst);
FD_SET(sock, &fst);
struct timeval tm_out = {4, 0};
ret = select((int)(sock + 1), &fst, NULL, NULL, &tm_out);
if(ret == 0 || ret == -1)
{
break;
}
char RecvBuf[BUFFER_SIZE] = {0};
ret = recvfrom(sock, RecvBuf, BUFFER_SIZE, 0, (sockaddr*)&fromAddr, (socklen_t*)&ReceiveAddrSize);
if(ret != SOCKET_ERROR)
{
_CEMS_NET_HEAD* pHead = (_CEMS_NET_HEAD*)RecvBuf;
std::string szReceive;
DWORD dwSize = (pHead->dwDataSize);
szReceive.append((char*)(RecvBuf + pHead->wHeadSize), dwSize);
m_vResult.push_back(szReceive);
char ip[INET6_ADDRSTRLEN] = {0};
if (inet_ntop(AF_INET, &(((struct sockaddr_in *)&fromAddr)->sin_addr), ip, sizeof ip) == NULL) //vracia adresu interf
{
perror("inet_ntop");
continue;
}
else
{
// printf("respon client ipaddr: %s\n", ip);
}
struct tm st;
GetLocalTime(&st);
// printf("receive from client : %s time : %04d-%02d-%02d %02d:%02d:%02d \n", szReceive.c_str(),
// st.tm_year, st.tm_mon, st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec);
nRecvConut++;
}
}
printf("recv %d client response.\n", nRecvConut);
}
void MCallClient::GetResult(VECTOR_RESULT & vResult)
{
m_vResult.swap(vResult);
}
void GetLocalTime(struct tm *ptm)
{
time_t curTime = time(NULL);
tm * loc = localtime(&curTime);
*ptm = *loc;
ptm->tm_mon++;
ptm->tm_year += 1900;
}
|
/**
@file FirstBossLifeScript.hpp
@brief Manage the first boss life.
@copyright MIT License.
*/
#ifndef __FIRST_BOSS_LIFE_SCRIPT__
#define __FIRST_BOSS_LIFE_SCRIPT__
#include "Engine/InputSystem.hpp"
#include "Engine/GameObject.hpp"
#include "Engine/SceneManager.hpp"
#include "Engine/CameraSystem.hpp"
#include "Components/RectangleRenderer.hpp"
#include "Customs/FirstBossController.hpp"
#include "Components/UIText.hpp"
#include "Components/Script.hpp"
#include "Components/Animator.hpp"
#include "Customs/NakedManScript.hpp"
#include "Math/Vector.hpp"
#include <string>
class FirstBossLifeScript : public Script {
public:
FirstBossLifeScript(GameObject *owner);
// Get the component name and replace it by returning its string name.
std::string GetComponentName() override {
return "FirstBossLifeScript";
};
void FixedComponentUpdate() override;
void Start() override;
// Boolean variable that is responsible for saying whether or not.
bool hit = false;
private:
// Pointer position that stores the vector position of the boss's attack.
Vector *position = nullptr;
protected:
void ComponentUpdate() override;
};
#endif
|
/*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* 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.
*/
#pragma once
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/device_buffer.hpp>
#include <cudf/column/column.hpp>
#include <thrust/distance.h>
namespace detail {
template <typename Element, typename InputIterator>
rmm::device_buffer make_elements(InputIterator begin, InputIterator end)
{
static_assert(cudf::is_fixed_width<Element>(), "Unexpected non-fixed width type.");
std::vector<Element> elements(begin, end);
return rmm::device_buffer{elements.data(), elements.size() * sizeof(Element)};
}
template <typename Element, typename iterator_t>
std::unique_ptr<cudf::column> create_column(iterator_t begin, iterator_t end)
{
cudf::size_type size = thrust::distance(begin, end);
return std::unique_ptr<cudf::column>(
new cudf::column{cudf::data_type{cudf::experimental::type_to_id<Element>()},
size,
detail::make_elements<Element>(begin, end)});
}
} // namespace detail
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under 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/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_TEST_VECTOR_TEST_HEADER
#define BOOST_INTERPROCESS_TEST_VECTOR_TEST_HEADER
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/interprocess/detail/mpl.hpp>
#include "print_container.hpp"
#include "check_equal_containers.hpp"
#include "movable_int.hpp"
#include "get_process_id_name.hpp"
#include "emplace_test.hpp"
#include <vector>
#include <list>
#include <string>
#include <iostream>
#include <cstddef>
namespace boost{
namespace interprocess{
namespace test{
template<class V1, class V2>
bool copyable_only(V1 *, V2 *, boost::interprocess::ipcdetail::false_type)
{
return true;
}
//Function to check if both sets are equal
template<class V1, class V2>
bool copyable_only(V1 *shmvector, V2 *stdvector, boost::interprocess::ipcdetail::true_type)
{
typedef typename V1::value_type IntType;
std::size_t size = shmvector->size();
stdvector->insert(stdvector->end(), 50, 1);
shmvector->insert(shmvector->end(), 50, IntType(1));
if(!test::CheckEqualContainers(shmvector, stdvector)) return false;
{
IntType move_me(1);
stdvector->insert(stdvector->begin()+size/2, 50, 1);
shmvector->insert(shmvector->begin()+size/2, 50, boost::move(move_me));
if(!test::CheckEqualContainers(shmvector, stdvector)) return false;
}
{
IntType move_me(2);
shmvector->assign(shmvector->size()/2, boost::move(move_me));
stdvector->assign(stdvector->size()/2, 2);
if(!test::CheckEqualContainers(shmvector, stdvector)) return false;
}
{
IntType move_me(3);
shmvector->assign(shmvector->size()*3-1, boost::move(move_me));
stdvector->assign(stdvector->size()*3-1, 3);
if(!test::CheckEqualContainers(shmvector, stdvector)) return false;
}
return true;
}
template<class ManagedSharedMemory
,class MyShmVector>
int vector_test()
{
typedef std::vector<int> MyStdVector;
typedef typename MyShmVector::value_type IntType;
std::string process_name;
test::get_process_id_name(process_name);
const int Memsize = 65536;
const char *const shMemName = process_name.c_str();
const int max = 100;
{
//Compare several shared memory vector operations with std::vector
//Create shared memory
shared_memory_object::remove(shMemName);
try{
ManagedSharedMemory segment(create_only, shMemName, Memsize);
segment.reserve_named_objects(100);
//Shared memory allocator must be always be initialized
//since it has no default constructor
MyShmVector *shmvector = segment.template construct<MyShmVector>("MyShmVector")
(segment.get_segment_manager());
MyStdVector *stdvector = new MyStdVector;
shmvector->resize(100);
stdvector->resize(100);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->resize(200);
stdvector->resize(200);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->resize(0);
stdvector->resize(0);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
for(int i = 0; i < max; ++i){
IntType new_int(i);
shmvector->insert(shmvector->end(), boost::move(new_int));
stdvector->insert(stdvector->end(), i);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
}
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
typename MyShmVector::iterator shmit(shmvector->begin());
typename MyStdVector::iterator stdit(stdvector->begin());
typename MyShmVector::const_iterator cshmit = shmit;
(void)cshmit;
++shmit; ++stdit;
shmvector->erase(shmit);
stdvector->erase(stdit);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->erase(shmvector->begin());
stdvector->erase(stdvector->begin());
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
{
//Initialize values
IntType aux_vect[50];
for(int i = 0; i < 50; ++i){
IntType new_int(-1);
//BOOST_STATIC_ASSERT((::boost::move_ipcdetail::is_copy_constructible<boost::interprocess::test::movable_int>::value == false));
aux_vect[i] = boost::move(new_int);
}
int aux_vect2[50];
for(int i = 0; i < 50; ++i){
aux_vect2[i] = -1;
}
shmvector->insert(shmvector->end()
,::boost::make_move_iterator(&aux_vect[0])
,::boost::make_move_iterator(aux_vect + 50));
stdvector->insert(stdvector->end(), aux_vect2, aux_vect2 + 50);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
for(int i = 0, j = static_cast<int>(shmvector->size()); i < j; ++i){
shmvector->erase(shmvector->begin());
stdvector->erase(stdvector->begin());
}
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
}
{
IntType aux_vect[50];
for(int i = 0; i < 50; ++i){
IntType new_int(-1);
aux_vect[i] = boost::move(new_int);
}
int aux_vect2[50];
for(int i = 0; i < 50; ++i){
aux_vect2[i] = -1;
}
shmvector->insert(shmvector->begin()
,::boost::make_move_iterator(&aux_vect[0])
,::boost::make_move_iterator(aux_vect + 50));
stdvector->insert(stdvector->begin(), aux_vect2, aux_vect2 + 50);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
}
shmvector->reserve(shmvector->size()*2);
stdvector->reserve(stdvector->size()*2);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
IntType push_back_this(1);
shmvector->push_back(boost::move(push_back_this));
stdvector->push_back(int(1));
shmvector->push_back(IntType(1));
stdvector->push_back(int(1));
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
if(!copyable_only(shmvector, stdvector
,ipcdetail::bool_<!ipcdetail::is_same<IntType, test::movable_int>::value>())){
return 1;
}
shmvector->erase(shmvector->begin());
stdvector->erase(stdvector->begin());
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
for(int i = 0; i < max; ++i){
IntType insert_this(i);
shmvector->insert(shmvector->begin(), boost::move(insert_this));
stdvector->insert(stdvector->begin(), i);
shmvector->insert(shmvector->begin(), IntType(i));
stdvector->insert(stdvector->begin(), int(i));
}
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
//Test insertion from list
{
std::list<int> l(50, int(1));
shmvector->insert(shmvector->begin(), l.begin(), l.end());
stdvector->insert(stdvector->begin(), l.begin(), l.end());
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->assign(l.begin(), l.end());
stdvector->assign(l.begin(), l.end());
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
}
/*
std::size_t cap = shmvector->capacity();
shmvector->reserve(cap*2);
stdvector->reserve(cap*2);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->resize(0);
stdvector->resize(0);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
shmvector->resize(cap*2);
stdvector->resize(cap*2);
if(!test::CheckEqualContainers(shmvector, stdvector)) return 1;
*/
delete stdvector;
segment.template destroy<MyShmVector>("MyShmVector");
segment.shrink_to_fit_indexes();
if(!segment.all_memory_deallocated())
return 1;
}
catch(std::exception &ex){
shared_memory_object::remove(shMemName);
std::cout << ex.what() << std::endl;
return 1;
}
}
shared_memory_object::remove(shMemName);
std::cout << std::endl << "Test OK!" << std::endl;
return 0;
}
} //namespace test{
} //namespace interprocess{
} //namespace boost{
#include <boost/interprocess/detail/config_end.hpp>
#endif
|
// Copyright 2018 The Dawn Authors
//
// 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.
#include "dawn_native/ObjectBase.h"
namespace dawn_native {
static constexpr uint64_t kErrorPayload = 0;
static constexpr uint64_t kNotErrorPayload = 1;
ObjectBase::ObjectBase(DeviceBase* device, const char* label)
: RefCounted(kNotErrorPayload), mDevice(device) {
if (label) {
mLabel = label;
}
}
ObjectBase::ObjectBase(DeviceBase* device, ErrorTag)
: RefCounted(kErrorPayload), mDevice(device) {
}
ObjectBase::ObjectBase(DeviceBase* device, LabelNotImplementedTag)
: RefCounted(kNotErrorPayload), mDevice(device) {
}
const std::string& ObjectBase::GetLabel() {
return mLabel;
}
DeviceBase* ObjectBase::GetDevice() const {
return mDevice;
}
bool ObjectBase::IsError() const {
return GetRefCountPayload() == kErrorPayload;
}
void ObjectBase::APISetLabel(const char* label) {
mLabel = label;
SetLabelImpl();
}
void ObjectBase::SetLabelImpl() {
}
} // namespace dawn_native
|
/*
* Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
* All rights reserved.
*
* 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.
*
* 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.
*/
#include <LibJS/Runtime/ErrorTypes.h>
namespace JS {
#define __ENUMERATE_JS_ERROR(name, message) \
const ErrorType ErrorType::name = ErrorType(message);
JS_ENUMERATE_ERROR_TYPES(__ENUMERATE_JS_ERROR)
#undef __ENUMERATE_JS_ERROR
}
|
// Copyright 2020 The TensorFlow Runtime Authors
//
// 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.
// This file defines the kernels for string host tensors.
#include "tfrt/tensor/string_host_tensor_kernels.h"
#include "tfrt/host_context/kernel_utils.h"
#include "tfrt/host_context/sync_kernel_utils.h"
#include "tfrt/support/error_util.h"
#include "tfrt/tensor/string_host_tensor.h"
namespace tfrt {
namespace {
llvm::Expected<StringHostTensor> CreateStringTensor(
ArrayAttribute<Index> shape, AggregateAttr values,
const ExecutionContext& exec_ctx) {
auto result = StringHostTensor::CreateUninitialized(
TensorMetadata(DType(DType::String), shape.data()), exec_ctx.host());
if (!result) {
return MakeStringError("Failed to create SHT");
}
auto strings = result->strings();
if (strings.size() != values.GetNumElements()) {
return MakeStringError("Shape mismatch");
}
for (int i = 0, e = values.GetNumElements(); i != e; ++i) {
strings[i] = values.GetAttributeOfType<StringAttr>(i).GetValue().str();
}
return std::move(result).getValue();
}
static Expected<StringHostTensor> CreateUninitializedStringTensor(
ArrayAttribute<Index> shape_in, const ExecutionContext& exec_ctx) {
auto result = StringHostTensor::CreateUninitialized(
TensorShape(shape_in.data()), exec_ctx.host());
if (!result.hasValue()) {
return MakeStringError("Cannot allocate tensor");
}
return std::move(*result);
}
} // namespace
void RegisterStringHostTensorKernels(KernelRegistry* registry) {
registry->AddKernel("tfrt_sht.create_tensor",
TFRT_KERNEL(CreateStringTensor));
registry->AddSyncKernel("tfrt_sht_sync.create_tensor",
TFRT_SYNC_KERNEL(CreateStringTensor));
registry->AddSyncKernel("tfrt_sht_sync.create_uninitialized_tensor",
TFRT_SYNC_KERNEL(CreateUninitializedStringTensor));
}
} // namespace tfrt
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================
**
** Source: virtualalloc.c
**
** Purpose: Positive test the VirtualAlloc API.
** Call VirtualAlloc with MEM_COMMIT allocation type
** and PAGE_READONLY access protection
**
**============================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char *argv[])
{
int err;
LPVOID lpVirtualAddress;
//Initialize the PAL environment
err = PAL_Initialize(argc, argv);
if(0 != err)
{
ExitProcess(FAIL);
}
//Allocate the physical storage in memory or in the paging file on disk
lpVirtualAddress = VirtualAlloc(NULL,//system determine where to allocate the region
1024, //specify the size
MEM_COMMIT, //allocation type
PAGE_READONLY); //access protection
if(NULL == lpVirtualAddress)
{
Fail("\nFailed to call VirtualAlloc API!\n");
}
//decommit the specified region
err = VirtualFree(lpVirtualAddress,1024,MEM_DECOMMIT);
if(0 == err)
{
Fail("\nFailed to call VirtualFree API!\n");
}
PAL_Terminate();
return PASS;
}
|
/*!
* @copyright
* Copyright (c) 2015, Tymoteusz Blazejczyk
*
* @copyright
* All rights reserved.
*
* @copyright
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* @copyright
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* @copyright
* * 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.
*
* @copyright
* * Neither the name of json-cxx nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* @copyright
* 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.
*
* @file writter.cpp
*
* @brief JSON writter implementation
* */
#include "json/writter.hpp"
using namespace json;
Writter::~Writter() { }
|
#include "pch.h"
#include "CppUnitTest.h"
#include "leetcode-cpp/p1232/p1232_solution.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace tests
{
TEST_CLASS(p1232_test)
{
public:
TEST_METHOD(test1) {
auto solution{ leetcode::p1232::Solution() };
auto result{ solution.checkStraightLine(std::vector<std::vector<int>>{
{ {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}}}) };
Assert::IsTrue(result);
}
TEST_METHOD(test2) {
auto solution{ leetcode::p1232::Solution() };
auto result{ solution.checkStraightLine(std::vector<std::vector<int>>{
{ {1, 1}, {2, 2}, {3, 4}, {4, 5}, {5, 6}, {7, 7}}}) };
Assert::IsFalse(result);
}
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.