text
stringlengths
5
1.04M
/** _______________________________________________________________________ * * RDPARM/PTRAJ: 2008 * _______________________________________________________________________ * * This file is part of rdparm/ptraj. * * rdparm/ptraj 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. * * rdparm/ptraj 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 can receive a copy of the GNU General Public License from * http://www.gnu.org or by writing to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ________________________________________________________________________ * * CVS tracking: * * $Header: /storage/disk2/case/cvsroot/amber11/src/ptraj/rms.h,v 10.0 2008/04/15 23:24:11 case Exp $ * * Revision: $Revision: 10.0 $ * Date: $Date: 2008/04/15 23:24:11 $ * Last checked in by $Author: case $ * ________________________________________________________________________ * * * CONTACT INFO: To learn who the code developers are, who to contact for * more information, and to know what version of the code this is, refer * to the CVS information and the include files (contributors.h && version.h) * * * * ________________________________________________________________________ * * code modified for usage in megamol 0.3 (date: 2009/03/03) * */ #include "stdafx.h" #include "RMS.h" #include <cmath> #include "vislib/sys/Log.h" using namespace megamol; /* * protein::Normalize */ void protein::Normalize(double a[3]) { double b; b = 1.0/sqrt((double)(a[0]*a[0] + a[1]*a[1] + a[2]*a[2])); a[0] *= b; a[1] *= b; a[2] *= b; } /* * protein::DiagEsort */ int protein::DiagEsort(double *mat, double *Emat, double *Evec[], double *Eigenvalue) { int njrot; int i, j, k, i3; double eigenvector[9], *eA, v; if(!Jacobi3(mat, Eigenvalue, eigenvector, &njrot)) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "RMS: DiagEsort - convergence failed! \n"); return(0); } for(i = i3 = 0; i < 3; i++, i3 += 3) for (j=0; j<3; j++) Emat[i3+j] = eigenvector[j*3+i]; for(i = 0; i < 3; i++) Evec[i] = (double *) &Emat[i*3]; for(i = 0; i < 2; i++) { v = Eigenvalue[k=i]; for(j = i+1; j < 3; j++) if(Eigenvalue[j] > v) v = Eigenvalue[k=j]; if(k != i) { Eigenvalue[k] = Eigenvalue[i]; Eigenvalue[i] = v; eA = Evec[i]; Evec[i] = Evec[k]; Evec[k] = eA; } } return(1); } /* * protein::Jacobi3 */ int protein::Jacobi3(double *a, double *d, double *v, int *nrot) { int i, j, ip, iq, p3, j3; double tresh, theta, tau, t, sm, s, h, g, c, b[3], z[3]; for(ip = p3=0; ip < 3; ip++, p3 += 3) { /* * initialize the identity matrix */ for(iq = 0; iq < 3; iq++) v[p3 + iq] = 0.0; v[p3 + ip] = 1.0; /* * initialize b and d to diagonal of a */ b[ip] = d[ip] = a[p3 + ip]; z[ip] = 0.0; } *nrot = 0; for(i = 0; i < 50; i++) { sm = 0.0; for(ip = p3 = 0; ip < 2; ip++, p3 += 3) { for(iq = ip+1; iq < 3; iq++) sm += fabs(a[p3 + iq]); } if(sm == 0.0) { return(1); } if(i < 3) tresh = sm * 0.2 / 9.0; /* on 1st three sweeps... */ else tresh = 0.0; /* thereafter... */ for(ip = p3 = 0; ip < 2; ip++, p3 += 3) { for(iq = ip+1; iq < 3; iq++) { g = 100.0 * fabs(a[p3 + iq]); if((i > 3) && (fabs(d[ip])+g == fabs(d[ip])) && (fabs(d[iq])+g == fabs(d[iq]))) { a[p3 + iq] = 0.0; } else if(fabs(a[p3 + iq]) > tresh) { h = d[iq]-d[ip]; if(fabs(h)+g == fabs(h)) t = a[p3 + iq] / h; else { theta = 0.5 * h / a[p3 + iq]; t = 1.0 / (fabs(theta)+(double)sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; } c = 1.0 / (double)sqrt(1.0 + t*t); s = t * c; tau = s / (1.0 + c); h = t * a[p3 + iq]; z[ip] -= h; z[iq] += h; d[ip] -= h; d[iq] += h; a[p3 + iq] = 0.0; for(j = j3 = 0; j <= ip-1; j++, j3 += 3) ROTATE_JACOBI3(a,j3,ip,j3,iq) for(j = ip+1; j <= iq-1; j++) ROTATE_JACOBI3(a,p3,j,j*3,iq) for(j = iq+1; j < 3; j++) ROTATE_JACOBI3(a,p3,j,iq*3,j) for(j3 = 0; j3 < 9; j3 += 3) ROTATE_JACOBI3(v,j3,ip,j3,iq) ++(*nrot); } } } for(ip = 0; ip < 3; ip++) { b[ip] += z[ip]; d[ip] = b[ip]; z[ip] = 0.0; } } vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "RMS: Jacobi3 - there are too many iterations! \n"); return(0); } /* * protein::CalculateRMS */ float protein::CalculateRMS(unsigned int n, bool fit, unsigned int mode, float *mass, int *mask, float *toFitVec, float *Vec, float rotation[3][3], float translation[3]) { int ierr=0; unsigned int i, j, k, modifiedCount; const char *err; double rms_return = 0.0; // do not know. however, better than uninitialized double *weights; double rot[9], rtr[9]; int i3, k3; double mwss; double b[9], U[9]; double *Evector[3], Eigenvalue[3], Emat[9]; double x, y, z, xx, yy, zz; double total_mass; double sig3; double cp[3]; double cofmX, cofmY, cofmZ; double cofmX1, cofmY1, cofmZ1; float xtemp, ytemp, ztemp; weights = new double[n]; total_mass = 0.0; if(!fit) { /* * Don't do the fit, just calculate rmsd: don't calculate * any translation/rotation */ rms_return = 0.0; for(i = 0; i < n; i++) { if (mask != NULL && mask[i] == 1) { if (mass != NULL) weights[i] = mass[i]; else weights[i] = 1.0; total_mass += weights[i]; xx = Vec[3*i] - toFitVec[3*i]; yy = Vec[3*i+1] - toFitVec[3*i+1]; zz = Vec[3*i+2] - toFitVec[3*i+2]; rms_return += weights[i]*(xx*xx + yy*yy + zz*zz); } } rms_return = sqrt(rms_return / total_mass); delete []weights; return (float) rms_return; } /* * the rest below is for fit=1, i.e. calculate translation and * rotation matrix as well as rmsd value of the fitted region */ for(i = 0, modifiedCount = n; i < n; i++) { if((mask != NULL) && (mask[i] == 0)) { weights[i] = 0.0; modifiedCount--; } else { if(mass != NULL) weights[i] = mass[i]; else weights[i] = 1.0; total_mass += weights[i]; } } if((mode == 1) || (mode == 2)) { if((rotation == NULL) || (translation == NULL)) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "RMS: CalculateRMS - rotation matrix and translation vector are NULL ? \n"); } } if(modifiedCount > 2) { memset(rot, 0, sizeof(double) * 9); memset(rtr, 0, sizeof(double) * 9); memset(U, 0, sizeof(double) * 9); cofmX = 0.0; cofmY = 0.0; cofmZ = 0.0; cofmX1 = 0.0; cofmY1 = 0.0; cofmZ1 = 0.0; /* * First shift the center of mass of all the atoms to be fit to * the origin for both trajectory and reference coordinates. */ for(k = 0; k < n; k++) { cofmX += weights[k] * toFitVec[3*k]; cofmY += weights[k] * toFitVec[3*k+1]; cofmZ += weights[k] * toFitVec[3*k+2]; cofmX1 += weights[k] * Vec[3*k]; cofmY1 += weights[k] * Vec[3*k+1]; cofmZ1 += weights[k] * Vec[3*k+2]; // printf("RMS %f %f %f\n", Vec[3*k], Vec[3*k+1], Vec[3*k+2]); } cofmX /= total_mass; cofmY /= total_mass; cofmZ /= total_mass; cofmX1 /= total_mass; cofmY1 /= total_mass; cofmZ1 /= total_mass; for(k = 0; k < n; k++) { toFitVec[3*k] -= (float)cofmX; toFitVec[3*k+1] -= (float)cofmY; toFitVec[3*k+2] -= (float)cofmZ; Vec[3*k] -= (float)cofmX1; Vec[3*k+1] -= (float)cofmY1; Vec[3*k+2] -= (float)cofmZ1; } mwss = 0.0; for (k = 0; k < n; k++) { x = toFitVec[3*k]; y = toFitVec[3*k+1]; z = toFitVec[3*k+2]; xx = Vec[3*k]; yy = Vec[3*k+1]; zz = Vec[3*k+2]; mwss += weights[k] * ( x*x + y*y + z*z + xx*xx + yy*yy + zz*zz ); /* * calculate the Kabsch matrix: R = (rij) = Sum(wn*yni*xnj) */ rot[0] += weights[k] * x * xx; rot[1] += weights[k] * x * yy; rot[2] += weights[k] * x * zz; rot[3] += weights[k] * y * xx; rot[4] += weights[k] * y * yy; rot[5] += weights[k] * y * zz; rot[6] += weights[k] * z * xx; rot[7] += weights[k] * z * yy; rot[8] += weights[k] * z * zz; } mwss *= 0.5f; /* E0 = 0.5*Sum(wn*(xn^2+yn^2)) */ /* * calculate Kabsch multiplied by its transpose: RtR */ rtr[0] = rot[0]*rot[0] + rot[1]*rot[1] + rot[2]*rot[2]; rtr[1] = rot[0]*rot[3] + rot[1]*rot[4] + rot[2]*rot[5]; rtr[2] = rot[0]*rot[6] + rot[1]*rot[7] + rot[2]*rot[8]; rtr[3] = rot[3]*rot[0] + rot[4]*rot[1] + rot[5]*rot[2]; rtr[4] = rot[3]*rot[3] + rot[4]*rot[4] + rot[5]*rot[5]; rtr[5] = rot[3]*rot[6] + rot[4]*rot[7] + rot[5]*rot[8]; rtr[6] = rot[6]*rot[0] + rot[7]*rot[1] + rot[8]*rot[2]; rtr[7] = rot[6]*rot[3] + rot[7]*rot[4] + rot[8]*rot[5]; rtr[8] = rot[6]*rot[6] + rot[7]*rot[7] + rot[8]*rot[8]; if(!DiagEsort(rtr, Emat, Evector, Eigenvalue)) return(0.0f); /* * a3 = a1 x a2 */ /*VOP_3D_COORDS_CROSS_PRODUCT(Evector[2][0], Evector[2][1], Evector[2][2], Evector[0][0], Evector[0][1], Evector[0][2], Evector[1][0], Evector[1][1], Evector[1][2]);*/ Evector[2][0] = (Evector[0][1] * Evector[1][2]) - (Evector[0][2] * Evector[1][1]); Evector[2][1] = (Evector[0][2] * Evector[1][0]) - (Evector[0][0] * Evector[1][2]); Evector[2][2] = (Evector[0][0] * Evector[1][1]) - (Evector[0][1] * Evector[1][0]); /* * Evector dot transpose rot: b = R.ak */ b[0] = Evector[0][0] * rot[0] + Evector[0][1] * rot[3] + Evector[0][2] * rot[6]; b[1] = Evector[0][0] * rot[1] + Evector[0][1] * rot[4] + Evector[0][2] * rot[7]; b[2] = Evector[0][0] * rot[2] + Evector[0][1] * rot[5] + Evector[0][2] * rot[8]; Normalize(&b[0]); b[3] = Evector[1][0] * rot[0] + Evector[1][1] * rot[3] + Evector[1][2] * rot[6]; b[4] = Evector[1][0] * rot[1] + Evector[1][1] * rot[4] + Evector[1][2] * rot[7]; b[5] = Evector[1][0] * rot[2] + Evector[1][1] * rot[5] + Evector[1][2] * rot[8]; Normalize(&b[3]); b[6] = Evector[2][0] * rot[0] + Evector[2][1] * rot[3] + Evector[2][2] * rot[6]; b[7] = Evector[2][0] * rot[1] + Evector[2][1] * rot[4] + Evector[2][2] * rot[7]; b[8] = Evector[2][0] * rot[2] + Evector[2][1] * rot[5] + Evector[2][2] * rot[8]; Normalize(&b[6]); /* * b3 = b1 x b2 */ /*VOP_3D_COORDS_CROSS_PRODUCT(cp[0], cp[1], cp[2], b[0], b[1], b[2], b[3], b[4], b[5]);*/ cp[0] = (b[1] * b[5]) - (b[2] * b[4]); cp[1] = (b[2] * b[3]) - (b[0] * b[5]); cp[2] = (b[0] * b[4]) - (b[1] * b[3]); if((cp[0] * b[6] + cp[1] * b[7] + cp[2] * b[8]) < 0.0f) sig3 = -1.0f; else sig3 = 1.0f; b[6] = cp[0]; b[7] = cp[1]; b[8] = cp[2]; /* * U has the best rotation */ for(k=k3=0; k<3; k++,k3+=3) for(i=i3=0;i<3; i++,i3+=3) for(j=0; j<3; j++) { U[i3 + j] += Evector[k][j] * b[k3 + i]; } /* * E = E0 - sqrt(mu1) - sqrt(mu2) - sig3*sqrt(mu3) */ rms_return = mwss - sqrt(fabs(Eigenvalue[0])) - sqrt(fabs(Eigenvalue[1])) - sig3 * sqrt(fabs(Eigenvalue[2])); if(rms_return < 0.0f) { rms_return = 0.0f; } else { rms_return = sqrt( (2.0f * rms_return) / total_mass); } /* * Move the reference back so that it stays unchanged. This is * necessary to preserve the meaning of CM shift on next frame * iteration. */ for(k = 0; k < n; k++) { Vec[3*k] += (float)cofmX1; Vec[3*k+1] += (float)cofmY1; Vec[3*k+2] += (float)cofmZ1; } if(mode == 2) { /* * Save rotation matrix which does the best overlap of trajectory * coordinates to reference coordinates when they are both centered * on their CMs. The actual modification (=rotation) of trajectory * coords happens in the calling routine (actions.c::transformRMS()) */ rotation[0][0] = (float)U[0]; rotation[0][1] = (float)U[1]; rotation[0][2] = (float)U[2]; rotation[1][0] = (float)U[3]; rotation[1][1] = (float)U[4]; rotation[1][2] = (float)U[5]; rotation[2][0] = (float)U[6]; rotation[2][1] = (float)U[7]; rotation[2][2] = (float)U[8]; /* * Once the reference coords are shifted back to its original * position (the for-cycle above), we need to shift trajectory * coordinates by the same amount (i.e. CM of the reference) * to get them overlapped with the reference. The actual * translation of trajectory coordinates happens in the calling * routine (actions.c::transformRMS() ) */ translation[0] = (float)cofmX1; translation[1] = (float)cofmY1; translation[2] = (float)cofmZ1; /* First apply the rotation (which was calculated for both trajectory and reference coords shifted to their CMs). The order (first rotation, then translation) is important.*/ for (k=0; k < n; k++) { /*VOP_3x3_TIMES_COORDS(rotation, toFitX[k], toFitY[k], toFitZ[k], xtemp, ytemp, ztemp);*/ xtemp = rotation[0][0] * toFitVec[3*k] + rotation[0][1] * toFitVec[3*k+1] + rotation[0][2] * toFitVec[3*k+2]; ytemp = rotation[1][0] * toFitVec[3*k] + rotation[1][1] * toFitVec[3*k+1] + rotation[1][2] * toFitVec[3*k+2]; ztemp = rotation[2][0] * toFitVec[3*k] + rotation[2][1] * toFitVec[3*k+1] + rotation[2][2] * toFitVec[3*k+2]; toFitVec[3*k] = xtemp; toFitVec[3*k+1] = ytemp; toFitVec[3*k+2] = ztemp; toFitVec[3*k] += (float)cofmX1; toFitVec[3*k+1] += (float)cofmY1; toFitVec[3*k+2] += (float)cofmZ1; } } else if(mode == 1) { /* Nothing. XYZ moved back. ToFitXYZ moved to (0,0,0) */ } else if(mode == 0) { /* Or just move them back to their original position */ for(k = 0; k < n; k++) { toFitVec[3*k] += (float)cofmX; toFitVec[3*k+1] += (float)cofmY; toFitVec[3*k+2] += (float)cofmZ; } } } else { ierr = -1; } if (ierr != 0) { switch (ierr) { case -1: err = "Number of atoms less than 2"; break; case -2: /* ierr is never set to -2 previously ?? */ err = "Illegal weights"; break; default: err = "Unknown error"; break; } vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "RMS: CalculateRMS - error: %s\n", err); } delete []weights; return (float) rms_return; }
#include "ZFUINativeViewWrapper.h" #include "protocol/ZFProtocolZFUIView.h" ZF_NAMESPACE_GLOBAL_BEGIN ZFOBJECT_REGISTER(ZFUINativeViewWrapper) ZFOBJECT_ON_INIT_DEFINE_1(ZFUINativeViewWrapper, ZFMP_IN(void *, wrappedNativeView)) { this->objectOnInit(); zfself::wrappedNativeView(wrappedNativeView); } void ZFUINativeViewWrapper::objectInfoOnAppend(ZF_IN_OUT zfstring &ret) { zfsuper::objectInfoOnAppend(ret); if(this->wrappedNativeView() != zfnull) { ret += " "; zfsFromPointerT(ret, this->wrappedNativeView()); } } ZFMETHOD_DEFINE_1(ZFUINativeViewWrapper, void, wrappedNativeView, ZFMP_IN(void *, wrappedNativeView)) { zfclassNotPOD _ZFP_ZFUINativeViewWrapper_nativeImplViewDestroy { public: static void action(ZF_IN ZFUIView *view, ZF_IN void *nativeImplView) { // nothing to do } }; this->nativeImplView(wrappedNativeView, _ZFP_ZFUINativeViewWrapper_nativeImplViewDestroy::action); } ZFMETHOD_DEFINE_0(ZFUINativeViewWrapper, void *, wrappedNativeView) { return this->nativeImplView(); } ZFMETHOD_DEFINE_2(ZFUINativeViewWrapper, void, measureNativeView, ZFMP_OUT(ZFUISize &, ret), ZFMP_IN_OPT(const ZFUISize &, sizeHint, ZFUISizeInvalid())) { const ZFUIMargin &nativeImplViewMargin = this->nativeImplViewMargin(); ZFPROTOCOL_ACCESS(ZFUIView)->measureNativeView( ret, this->wrappedNativeView(), ZFUISizeApplyScale( ZFUILayoutParam::sizeHintOffset(sizeHint, ZFUISizeMake( 0 - ZFUIMarginGetWidth(nativeImplViewMargin), 0 - ZFUIMarginGetHeight(nativeImplViewMargin) )), this->UIScaleFixed())); ZFUISizeApplyScaleReversely(ret, ret, this->UIScaleFixed()); ZFUISizeApplyMarginReversely(ret, ret, nativeImplViewMargin); } void ZFUINativeViewWrapper::layoutOnMeasure(ZF_OUT ZFUISize &ret, ZF_IN const ZFUISize &sizeHint, ZF_IN const ZFUISizeParam &sizeParam) { this->measureNativeView(ret, sizeHint); } ZF_NAMESPACE_GLOBAL_END
#include <AK/HashTable.h> #include <AK/StringBuilder.h> #include <Kernel/FileSystem/Custody.h> #include <Kernel/FileSystem/Inode.h> #include <Kernel/Lock.h> static Lockable<HashTable<Custody*>>& all_custodies() { static Lockable<HashTable<Custody*>>* table; if (!table) table = new Lockable<HashTable<Custody*>>; return *table; } Custody* Custody::get_if_cached(Custody* parent, const String& name) { LOCKER(all_custodies().lock()); for (auto& custody : all_custodies().resource()) { if (custody->is_deleted()) continue; if (custody->is_mounted_on()) continue; if (custody->parent() == parent && custody->name() == name) return custody; } return nullptr; } Retained<Custody> Custody::get_or_create(Custody* parent, const String& name, Inode& inode) { if (RetainPtr<Custody> cached_custody = get_if_cached(parent, name)) { if (&cached_custody->inode() != &inode) { dbgprintf("WTF! cached custody for name '%s' has inode=%s, new inode=%s\n", name.characters(), cached_custody->inode().identifier().to_string().characters(), inode.identifier().to_string().characters()); } ASSERT(&cached_custody->inode() == &inode); return *cached_custody; } return create(parent, name, inode); } Custody::Custody(Custody* parent, const String& name, Inode& inode) : m_parent(parent) , m_name(name) , m_inode(inode) { LOCKER(all_custodies().lock()); all_custodies().resource().set(this); } Custody::~Custody() { LOCKER(all_custodies().lock()); all_custodies().resource().remove(this); } String Custody::absolute_path() const { Vector<const Custody*, 32> custody_chain; for (auto* custody = this; custody; custody = custody->parent()) custody_chain.append(custody); StringBuilder builder; for (int i = custody_chain.size() - 2; i >= 0; --i) { builder.append('/'); builder.append(custody_chain[i]->name().characters()); } return builder.to_string(); } void Custody::did_delete(Badge<VFS>) { m_deleted = true; } void Custody::did_mount_on(Badge<VFS>) { m_mounted_on = true; } void Custody::did_rename(Badge<VFS>, const String& name) { m_name = name; }
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_CHRID.hpp> START_ATF_NAMESPACE struct _robed_hp_inform_zocl { _CHRID idDster; _CHRID idPerformer; unsigned __int16 wRobedHP; }; END_ATF_NAMESPACE
#ifndef PIPES_SET_AGGREGATOR_HPP #define PIPES_SET_AGGREGATOR_HPP #include "pipes/operator.hpp" #include "pipes/pipeline_base.hpp" #include "pipes/helpers/assignable.hpp" #include "pipes/helpers/warnings.hpp" #include <functional> #include <iterator> PIPES_DISABLE_WARNING_PUSH PIPES_DISABLE_WARNING_MULTIPLE_ASSIGNMENT_OPERATORS_SPECIFIED namespace pipes { template<typename Set, typename Function> class set_aggregate_iterator : public pipeline_base<set_aggregate_iterator<Set, Function>> { public: template<typename T> void onReceive(T&& value) { auto position = set_.get().find(FWD(value)); if (position != set_.get().end()) { auto containedValue = *position; position = set_.get().erase(position); set_.get().insert(position, aggregator_(FWD(value), containedValue)); } else { set_.get().insert(position, value); } } using container_type = Set; set_aggregate_iterator(Set& set, Function aggregator) : set_(set), aggregator_(aggregator) {} private: std::reference_wrapper<Set> set_; detail::assignable<Function> aggregator_; public: // but technical using base = pipeline_base<set_aggregate_iterator<Set, Function>>; using base::operator=; set_aggregate_iterator& operator=(set_aggregate_iterator const& other) { set_ = other.set_; aggregator_ = other.aggregator_; return *this; } set_aggregate_iterator& operator=(set_aggregate_iterator& other) { *this = const_cast<set_aggregate_iterator const&>(other); return *this; } }; template<typename Set, typename Function> set_aggregate_iterator<Set, Function> set_aggregator(Set& set, Function aggregator) { return set_aggregate_iterator<Set, Function>(set, aggregator); } } // namespace pipes PIPES_DISABLE_WARNING_POP #endif // PIPES_SET_AGGREGATOR_HPP
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #include <doctest/doctest.h> #include "core/dataset.hpp" #include "core/format.hpp" #include "core/pset.hpp" #include "operators/creator.hpp" #include "operators/crossover.hpp" #include "operators/mutation.hpp" namespace Operon::Test { TEST_CASE("InsertSubtreeMutation") { auto target = "Y"; auto ds = Dataset("../data/Poly-10.csv", true); auto variables = ds.Variables(); std::vector<Variable> inputs; std::copy_if(variables.begin(), variables.end(), std::back_inserter(inputs), [&](auto& v) { return v.Name != target; }); size_t maxDepth = 1000, maxLength = 100; Range range { 0, 250 }; PrimitiveSet grammar; grammar.SetConfig(PrimitiveSet::Arithmetic | NodeType::Log | NodeType::Exp); grammar.SetFrequency(Node(NodeType::Add).HashValue, 1); grammar.SetFrequency(Node(NodeType::Mul).HashValue, 1); grammar.SetFrequency(Node(NodeType::Sub).HashValue, 1); grammar.SetFrequency(Node(NodeType::Div).HashValue, 1); BalancedTreeCreator btc { grammar, inputs, /* bias= */ 0.0 }; Operon::RandomGenerator random(std::random_device {}()); auto sizeDistribution = std::uniform_int_distribution<size_t>(1, maxLength); auto targetLen = sizeDistribution(random); auto tree = btc(random, targetLen, 1, maxDepth); fmt::print("{}\n", TreeFormatter::Format(tree, ds)); InsertSubtreeMutation mut(btc, 2 * targetLen, maxDepth, grammar); auto child = mut(random, tree); fmt::print("{}\n", TreeFormatter::Format(child, ds)); } }
/* * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> * 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 <AK/TestSuite.h> #include <math.h> #define EXPECT_CLOSE(a, b) \ { \ EXPECT(fabs(a - b) < 0.000001); \ } TEST_CASE(trig) { EXPECT_CLOSE(sin(1234), 0.601927); EXPECT_CLOSE(cos(1234), -0.798550); EXPECT_CLOSE(tan(1234), -0.753775); EXPECT_CLOSE(sqrt(1234), 35.128336) EXPECT_CLOSE(sin(-1), -0.8414709848078965); EXPECT_CLOSE(cos(-1), 0.5403023058681398); EXPECT_CLOSE(tan(-1), -1.5574077246549023); EXPECT(isnan(sqrt(-1))); EXPECT(isnan(asin(1.1))); EXPECT(isnan(asin(-1.1))); EXPECT_CLOSE(asin(0), 0.0); EXPECT_CLOSE(asin(0.01), 0.01); EXPECT_CLOSE(asin(0.1), 0.100167); EXPECT_CLOSE(asin(0.3), 0.304693); EXPECT_CLOSE(asin(0.499), 0.522444); EXPECT_CLOSE(asin(0.5), 0.523599); EXPECT_CLOSE(asin(0.501), 0.524754); EXPECT_CLOSE(asin(0.9), 1.119770); EXPECT_CLOSE(asin(0.99), 1.429245); EXPECT_CLOSE(asin(1.0), 1.570750); EXPECT_CLOSE(atan(0), 0.0) EXPECT_CLOSE(atan(0.5), 0.463648) EXPECT_CLOSE(atan(-0.5), -0.463648) EXPECT_CLOSE(atan(5.5), 1.390943) EXPECT_CLOSE(atan(-5.5), -1.390943) EXPECT_CLOSE(atan(555.5), 1.568996) } TEST_CASE(other) { EXPECT_EQ(trunc(9999999999999.5), 9999999999999.0); EXPECT_EQ(trunc(-9999999999999.5), -9999999999999.0); } TEST_CASE(exponents) { struct values { double x; double exp; double sinh; double cosh; double tanh; }; values values[8] { { 1.500000, 4.481626, 2.129246, 2.352379, 0.905148 }, { 20.990000, 1304956710.432035, 652478355.216017, 652478355.216017, 1.000000 }, { 20.010000, 490041186.687082, 245020593.343541, 245020593.343541, 1.000000 }, { 0.000000, 1.000000, 0.000000, 1.000000, 0.000000 }, { 0.010000, 1.010050, 0.010000, 1.000050, 0.010000 }, { -0.010000, 0.990050, -0.010000, 1.000050, -0.010000 }, { -1.000000, 0.367879, -1.175201, 1.543081, -0.761594 }, { -17.000000, 0.000000, -12077476.376788, 12077476.376788, -1.000000 }, }; for (auto& v : values) { EXPECT_CLOSE(exp(v.x), v.exp); EXPECT_CLOSE(sinh(v.x), v.sinh); EXPECT_CLOSE(cosh(v.x), v.cosh); EXPECT_CLOSE(tanh(v.x), v.tanh); } EXPECT_EQ(exp(1000), __builtin_huge_val()); } TEST_CASE(logarithms) { EXPECT(isnan(log(-1))); EXPECT(log(0) < -1000000); EXPECT_CLOSE(log(0.5), -0.693233) EXPECT_CLOSE(log(1.1), 0.095310) EXPECT_CLOSE(log(5), 1.609480) EXPECT_CLOSE(log(5.5), 1.704842) EXPECT_CLOSE(log(500), 6.214104) EXPECT_CLOSE(log2(5), 2.321989) EXPECT_CLOSE(log10(5), 0.698988) } union Extractor { explicit Extractor(double d) : d(d) { } Extractor(unsigned sign, unsigned exponent, unsigned long long mantissa) : mantissa(mantissa) , exponent(exponent) , sign(sign) { } struct { unsigned long long mantissa : 52; unsigned exponent : 11; unsigned sign : 1; }; double d; bool operator==(const Extractor& other) const { return other.sign == sign && other.exponent == exponent && other.mantissa == mantissa; } }; namespace AK { template<> struct Formatter<Extractor> : StandardFormatter { void format(FormatBuilder& builder, const Extractor& value) { builder.put_literal("{"); builder.put_u64(value.sign); builder.put_literal(", "); builder.put_u64(value.exponent, 16, true); builder.put_literal(", "); builder.put_u64(value.mantissa, 16, true); builder.put_literal("}"); } }; } static Extractor nextafter_translator(Extractor x, Extractor target) { return Extractor(nextafter(x.d, target.d)); } TEST_CASE(nextafter) { EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x1, 0x0), Extractor(0x0, 0x412, 0xe848000000000)), Extractor(0x0, 0x1, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x3ff, 0x0), Extractor(0x0, 0x412, 0xe848200000000)), Extractor(0x0, 0x3ff, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x0), Extractor(0x0, 0x412, 0xe848000000000)), Extractor(0x0, 0x0, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x0), Extractor(0x0, 0x412, 0xe848000000000)), Extractor(0x0, 0x0, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x3ff, 0x0), Extractor(0x0, 0x412, 0xe847e00000000)), Extractor(0x1, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x1), Extractor(0x0, 0x412, 0xe848000000000)), Extractor(0x0, 0x0, 0x2)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe848000000000), Extractor(0x0, 0x1, 0x0)), Extractor(0x0, 0x412, 0xe847fffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe848200000000), Extractor(0x0, 0x3ff, 0x0)), Extractor(0x0, 0x412, 0xe8481ffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe848000000000), Extractor(0x1, 0x0, 0x0)), Extractor(0x0, 0x412, 0xe847fffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe848000000000), Extractor(0x0, 0x0, 0x0)), Extractor(0x0, 0x412, 0xe847fffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe847e00000000), Extractor(0x1, 0x3ff, 0x0)), Extractor(0x0, 0x412, 0xe847dffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x412, 0xe848000000000), Extractor(0x0, 0x0, 0x1)), Extractor(0x0, 0x412, 0xe847fffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x1, 0x0), Extractor(0x0, 0x1, 0x0)), Extractor(0x0, 0x1, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x3ff, 0x0), Extractor(0x0, 0x3ff, 0x0)), Extractor(0x0, 0x3ff, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x0), Extractor(0x1, 0x0, 0x0)), Extractor(0x1, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x0), Extractor(0x0, 0x0, 0x0)), Extractor(0x0, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x3ff, 0x0), Extractor(0x1, 0x3ff, 0x0)), Extractor(0x1, 0x3ff, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x1), Extractor(0x0, 0x0, 0x1)), Extractor(0x0, 0x0, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x1, 0x7fe, 0xffffffffffffe)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x1, 0x0), Extractor(0x0, 0x1, 0x0)), Extractor(0x1, 0x0, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x3ff, 0x0), Extractor(0x0, 0x3ff, 0x0)), Extractor(0x1, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x0), Extractor(0x1, 0x0, 0x0)), Extractor(0x1, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x0), Extractor(0x0, 0x0, 0x0)), Extractor(0x0, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x3ff, 0x0), Extractor(0x1, 0x3ff, 0x0)), Extractor(0x0, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x1), Extractor(0x0, 0x0, 0x1)), Extractor(0x1, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x1, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xffffffffffffe)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x1, 0x0), Extractor(0x1, 0x1, 0x0)), Extractor(0x0, 0x0, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x3ff, 0x0), Extractor(0x1, 0x3ff, 0x0)), Extractor(0x0, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x0), Extractor(0x0, 0x0, 0x0)), Extractor(0x0, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x0), Extractor(0x1, 0x0, 0x0)), Extractor(0x1, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x3ff, 0x0), Extractor(0x0, 0x3ff, 0x0)), Extractor(0x1, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x1), Extractor(0x1, 0x0, 0x1)), Extractor(0x0, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x1, 0x0), Extractor(0x1, 0x419, 0x7d78400000000)), Extractor(0x0, 0x0, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x3ff, 0x0), Extractor(0x1, 0x419, 0x7d783fc000000)), Extractor(0x0, 0x3fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x0, 0x0), Extractor(0x1, 0x419, 0x7d78400000000)), Extractor(0x1, 0x0, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x0), Extractor(0x1, 0x419, 0x7d78400000000)), Extractor(0x1, 0x0, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x3ff, 0x0), Extractor(0x1, 0x419, 0x7d78404000000)), Extractor(0x1, 0x3ff, 0x1)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x0, 0x1), Extractor(0x1, 0x419, 0x7d78400000000)), Extractor(0x0, 0x0, 0x0)); EXPECT_EQ(nextafter_translator(Extractor(0x0, 0x7fe, 0xfffffffffffff), Extractor(0x0, 0x7fe, 0xfffffffffffff)), Extractor(0x0, 0x7fe, 0xfffffffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d78400000000), Extractor(0x0, 0x1, 0x0)), Extractor(0x1, 0x419, 0x7d783ffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d783fc000000), Extractor(0x0, 0x3ff, 0x0)), Extractor(0x1, 0x419, 0x7d783fbffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d78400000000), Extractor(0x1, 0x0, 0x0)), Extractor(0x1, 0x419, 0x7d783ffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d78400000000), Extractor(0x0, 0x0, 0x0)), Extractor(0x1, 0x419, 0x7d783ffffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d78404000000), Extractor(0x1, 0x3ff, 0x0)), Extractor(0x1, 0x419, 0x7d78403ffffff)); EXPECT_EQ(nextafter_translator(Extractor(0x1, 0x419, 0x7d78400000000), Extractor(0x0, 0x0, 0x1)), Extractor(0x1, 0x419, 0x7d783ffffffff)); } TEST_MAIN(Math)
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/cdn/model/AddLiveAppSnapshotConfigResult.h> #include <json/json.h> using namespace AlibabaCloud::Cdn; using namespace AlibabaCloud::Cdn::Model; AddLiveAppSnapshotConfigResult::AddLiveAppSnapshotConfigResult() : ServiceResult() {} AddLiveAppSnapshotConfigResult::AddLiveAppSnapshotConfigResult(const std::string &payload) : ServiceResult() { parse(payload); } AddLiveAppSnapshotConfigResult::~AddLiveAppSnapshotConfigResult() {} void AddLiveAppSnapshotConfigResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); }
#pragma once #include <ctime> #include "../third_party/pcg32/pcg32.h" #include "../third_party/OptimizedHeaders/mat.hpp" namespace rum { static pcg32 gen(time(NULL) << 8, time(NULL) >> 8); //generator for all rng class RngInit { protected: float lowest = 0, highest = 1; public: RngInit() = default; RngInit(float lowest, float highest) : lowest(lowest), highest(highest) {} virtual void Generator(MLMat &mat) const { for (auto &i : mat) { i = (gen.nextFloat() * this->highest) + this->lowest; } } }; template <typename T> concept RngGen = std::is_base_of_v<T, RngInit>; }; // namespace rum
/** \file HSASegment.hh * * Auto generated C++ code started by /PhD_Accounts/Phd_Accounts/a.monazzah/gem5-PhD/src/mem/slicc/symbols/Type.py:457 */ #ifndef __HSASegment_HH__ #define __HSASegment_HH__ #include <iostream> #include <string> // Class definition /** \enum HSASegment * \brief ... */ enum HSASegment { HSASegment_FIRST, HSASegment_GLOBAL = HSASegment_FIRST, /**< Global segment */ HSASegment_GROUP, /**< Group segment */ HSASegment_PRIVATE, /**< Private segment */ HSASegment_KERNARG, /**< Kernarg segment */ HSASegment_READONLY, /**< Readonly segment */ HSASegment_SPILL, /**< Spill segment */ HSASegment_ARG, /**< Arg segment */ HSASegment_NUM }; // Code to convert from a string to the enumeration HSASegment string_to_HSASegment(const std::string& str); // Code to convert state to a string std::string HSASegment_to_string(const HSASegment& obj); // Code to increment an enumeration type HSASegment &operator++(HSASegment &e); std::ostream& operator<<(std::ostream& out, const HSASegment& obj); #endif // __HSASegment_HH__
// Copyright (c) 2017 The Zcash Core developers // Copyright (c) 2020 The PIVX developers // Copyright (c) 2021-2022 The DECENOMY Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "consensus/upgrades.h" #include "optional.h" #include "test/test_pivx.h" #include <boost/test/unit_test.hpp> struct UpgradesTest : public TestingSetup { int DefaultActivation[Consensus::MAX_NETWORK_UPGRADES]; UpgradesTest() { SelectParams(CBaseChainParams::REGTEST); // Save activation heights in DefaultActivation and set all upgrades to inactive. for (uint32_t idx = Consensus::BASE_NETWORK + 1; idx < Consensus::MAX_NETWORK_UPGRADES; idx++) { DefaultActivation[idx] = Params().GetConsensus().vUpgrades[idx].nActivationHeight; UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(idx), Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT); } } ~UpgradesTest() { // Revert to default for (uint32_t idx = Consensus::BASE_NETWORK + 1; idx < Consensus::MAX_NETWORK_UPGRADES; idx++) { UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(idx), DefaultActivation[idx]); } SelectParams(CBaseChainParams::MAIN); } }; BOOST_FIXTURE_TEST_SUITE(network_upgrades_tests, UpgradesTest) BOOST_AUTO_TEST_CASE(networkUpgradeStateTest) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT BOOST_CHECK_EQUAL( NetworkUpgradeState(0, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_DISABLED); BOOST_CHECK_EQUAL( NetworkUpgradeState(1000000, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_DISABLED); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); BOOST_CHECK_EQUAL( NetworkUpgradeState(0, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_ACTIVE); BOOST_CHECK_EQUAL( NetworkUpgradeState(1000000, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_ACTIVE); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); BOOST_CHECK_EQUAL( NetworkUpgradeState(0, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_PENDING); BOOST_CHECK_EQUAL( NetworkUpgradeState(nActivationHeight - 1, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_PENDING); BOOST_CHECK_EQUAL( NetworkUpgradeState(nActivationHeight, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_ACTIVE); BOOST_CHECK_EQUAL( NetworkUpgradeState(1000000, params, Consensus::UPGRADE_TESTDUMMY), UPGRADE_ACTIVE); } BOOST_AUTO_TEST_CASE(IsActivationHeightTest) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT BOOST_CHECK(!IsActivationHeight(-1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(0, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1000000, params, Consensus::UPGRADE_TESTDUMMY)); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); BOOST_CHECK(!IsActivationHeight(-1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(IsActivationHeight(0, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1000000, params, Consensus::UPGRADE_TESTDUMMY)); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); BOOST_CHECK(!IsActivationHeight(-1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(0, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(nActivationHeight - 1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(IsActivationHeight(nActivationHeight, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(nActivationHeight + 1, params, Consensus::UPGRADE_TESTDUMMY)); BOOST_CHECK(!IsActivationHeight(1000000, params, Consensus::UPGRADE_TESTDUMMY)); } BOOST_AUTO_TEST_CASE(IsActivationHeightForAnyUpgradeTest) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT BOOST_CHECK(!IsActivationHeightForAnyUpgrade(-1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(0, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1000000, params)); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(-1, params)); BOOST_CHECK(IsActivationHeightForAnyUpgrade(0, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1000000, params)); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(-1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(0, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(nActivationHeight - 1, params)); BOOST_CHECK(IsActivationHeightForAnyUpgrade(nActivationHeight, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(nActivationHeight + 1, params)); BOOST_CHECK(!IsActivationHeightForAnyUpgrade(1000000, params)); } BOOST_AUTO_TEST_CASE(NextActivationHeightTest) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT BOOST_CHECK(NextActivationHeight(-1, params) == nullopt); BOOST_CHECK(NextActivationHeight(0, params) == nullopt); BOOST_CHECK(NextActivationHeight(1, params) == nullopt); BOOST_CHECK(NextActivationHeight(1000000, params) == nullopt); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); BOOST_CHECK(NextActivationHeight(-1, params) == nullopt); BOOST_CHECK(NextActivationHeight(0, params) == nullopt); BOOST_CHECK(NextActivationHeight(1, params) == nullopt); BOOST_CHECK(NextActivationHeight(1000000, params) == nullopt); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); BOOST_CHECK(NextActivationHeight(-1, params) == nullopt); BOOST_CHECK(NextActivationHeight(0, params) == nActivationHeight); BOOST_CHECK(NextActivationHeight(1, params) == nActivationHeight); BOOST_CHECK(NextActivationHeight(nActivationHeight - 1, params) == nActivationHeight); BOOST_CHECK(NextActivationHeight(nActivationHeight, params) == nullopt); BOOST_CHECK(NextActivationHeight(nActivationHeight + 1, params) == nullopt); BOOST_CHECK(NextActivationHeight(1000000, params) == nullopt); } BOOST_AUTO_TEST_SUITE_END()
/****************************************************************/ /* */ /* UserAccountsDlg.cpp */ /* */ /* Implementation of the CUserAccountsDlg class. */ /* */ /* Programmed by xingyun86 */ /* Copyright @2017 */ /* http://www.ppsbbs.tech */ /* */ /* Last updated: 10 july 2002 */ /* */ /****************************************************************/ #include "stdafx.h" #include "FTPServerApp.h" #include "UserAccountsDlg.h" #include "AddUserDlg.h" #include "DirectoryDlg.h" #include "WizardPages.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CFTPServerApp theApp; CUserAccountsDlg::CUserAccountsDlg(CWnd* pParent /*=NULL*/) : CDialogResize(CUserAccountsDlg::IDD, pParent) { //{{AFX_DATA_INIT(CUserAccountsDlg) m_strPassword = _T(""); m_bDisableAccount = FALSE; //}}AFX_DATA_INIT m_nPreviousIndex = LB_ERR; m_hIcon = AfxGetApp()->LoadIcon(IDI_FTPSERVER); } CUserAccountsDlg::~CUserAccountsDlg() { } void CUserAccountsDlg::DoDataExchange(CDataExchange* pDX) { CDialogResize::DoDataExchange(pDX); //{{AFX_DATA_MAP(CUserAccountsDlg) DDX_Control(pDX, IDC_USERS, m_UsersList); DDX_Control(pDX, IDC_DIR_LIST, m_DirectoryList); DDX_Text(pDX, IDC_PASSWORD, m_strPassword); DDX_Check(pDX, IDC_DISABLE_ACCOUNT, m_bDisableAccount); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CUserAccountsDlg, CDialogResize) //{{AFX_MSG_MAP(CUserAccountsDlg) ON_LBN_SELCHANGE(IDC_USER_LIST, OnSelchangeUserlist) ON_NOTIFY(NM_DBLCLK, IDC_DIR_LIST, OnDblclkDirlist) ON_BN_CLICKED(IDC_ADD_DIR, OnAddDir) ON_BN_CLICKED(IDC_EDIT_DIR, OnEditDir) ON_BN_CLICKED(IDC_DEL_DIR, OnDelDir) ON_BN_CLICKED(IDC_SET_HOME, OnSetHome) ON_BN_CLICKED(IDC_ADD_USER, OnAddUser) ON_BN_CLICKED(IDC_EDIT_USER, OnEditUser) ON_BN_CLICKED(IDC_DEL_USER, OnDelUser) ON_UPDATE_COMMAND_UI(IDC_EDIT_USER, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_DISABLE_ACCOUNT, OnUpdateDisableAccount) ON_NOTIFY(NM_CLICK, IDC_USERS, OnClickUsers) ON_NOTIFY(LVN_KEYDOWN, IDC_USERS, OnKeydownUsers) ON_BN_CLICKED(IDC_DISABLE_ACCOUNT, OnDisableAccount) ON_UPDATE_COMMAND_UI(IDC_DEL_USER, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_PASSWORD, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_DIR_LIST, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_ADD_DIR, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_EDIT_DIR, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_DEL_DIR, OnUpdateControls) ON_UPDATE_COMMAND_UI(IDC_SET_HOME, OnUpdateControls) ON_BN_CLICKED(IDC_WIZARD, OnWizard) //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DLGRESIZE_MAP(CUserAccountsDlg) DLGRESIZE_CONTROL(IDC_ADD_DIR, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_EDIT_DIR, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_DEL_DIR, DLSZ_MOVE_X | DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_SET_HOME, DLSZ_MOVE_X | DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDCANCEL, DLSZ_MOVE_X | DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X | DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_DIR_LIST, DLSZ_SIZE_X | DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_STATIC3, DLSZ_SIZE_X | DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_STATIC1, DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_STATIC2, DLSZ_SIZE_X) DLGRESIZE_CONTROL(IDC_USERS, DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_ADD_USER, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_EDIT_USER, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_DEL_USER, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_WIZARD, DLSZ_MOVE_Y) END_DLGRESIZE_MAP() /********************************************************************/ /* */ /* Function name : OnInitDialog */ /* Description : Initialize dialog */ /* */ /********************************************************************/ BOOL CUserAccountsDlg::OnInitDialog() { CDialogResize::OnInitDialog(); InitResizing(); // Set the icon for this dialog. SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CRect rc; m_UsersList.GetClientRect(rc); m_UsersList.InsertColumn(0, "Users", LVCFMT_LEFT, rc.Width()-5); // fill user list for (int i=0; i < m_UserArray.GetSize(); i++) { int nIndex = m_UsersList.InsertItem(0, m_UserArray[i].m_strName, 2); m_UsersList.SetItemData(nIndex, i); } // setup directory list m_DirectoryList.InsertColumn(0, "Physical Path", LVCFMT_LEFT, 100); m_DirectoryList.InsertColumn(1, "Virtual Path", LVCFMT_LEFT, 100); m_DirectoryList.InsertColumn(2, "Download", LVCFMT_LEFT, 10); m_DirectoryList.InsertColumn(3, "Upload", LVCFMT_LEFT, 10); m_DirectoryList.InsertColumn(4, "Rename", LVCFMT_LEFT, 10); m_DirectoryList.InsertColumn(5, "Delete", LVCFMT_LEFT, 10); m_DirectoryList.InsertColumn(6, "Create Dir", LVCFMT_LEFT, 10); // create and attach imagelist m_ImageList.Create(16, 16, ILC_MASK, 3, 3); HICON hIcon = AfxGetApp()->LoadIcon(IDI_NONE); m_ImageList.Add(hIcon); DestroyIcon(hIcon); hIcon = AfxGetApp()->LoadIcon(IDI_HOME); m_ImageList.Add(hIcon); DestroyIcon(hIcon); hIcon = AfxGetApp()->LoadIcon(IDI_USER); m_ImageList.Add(hIcon); DestroyIcon(hIcon); m_DirectoryList.SetImageList(&m_ImageList, LVSIL_SMALL); m_UsersList.SetImageList(&m_ImageList, LVSIL_SMALL); // select preferred user ? if (!m_strUserName.IsEmpty()) { LVFINDINFO info; info.flags = LVFI_STRING; info.psz = (LPCTSTR)m_strUserName; int nIndex = m_UsersList.FindItem(&info); m_UsersList.SetItemState(nIndex ,LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } else { m_UsersList.SetItemState(0 ,LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } GetDlgItem(IDC_PASSWORD)->ModifyStyle(NULL, ES_PASSWORD); ((CEdit *)GetDlgItem(IDC_PASSWORD))->SetPasswordChar('*'); OnSelchangeUserlist(); UpdateDialogControls(this, FALSE); AutoSizeColumns(); return TRUE; } /********************************************************************/ /* */ /* Function name : OnClickUsers */ /* Description : Selection in the user listcontrol has changed. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnClickUsers(NMHDR* pNMHDR, LRESULT* pResult) { OnSelchangeUserlist(); *pResult = 0; } /********************************************************************/ /* */ /* Function name : OnKeydownUsers */ /* Description : Selection in the user listcontrol has changed. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnKeydownUsers(NMHDR* pNMHDR, LRESULT* pResult) { LV_KEYDOWN* pLVKeyDow = (LV_KEYDOWN*)pNMHDR; // get index of selected item int nIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nIndex == -1) return; if (pLVKeyDow->wVKey == VK_DOWN) { if (m_UsersList.GetItemCount()-1 > nIndex) { m_UsersList.SetItemState(nIndex + 1, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } } else if (pLVKeyDow->wVKey == VK_UP) { if (nIndex > 0) { m_UsersList.SetItemState(nIndex - 1, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } } else if (pLVKeyDow->wVKey == VK_NEXT) { m_UsersList.SetItemState(m_UsersList.GetItemCount()-1, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } else if (pLVKeyDow->wVKey == VK_PRIOR) { m_UsersList.SetItemState(0, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); } OnSelchangeUserlist(); *pResult = 1; } /********************************************************************/ /* */ /* Function name : OnSelchangeUserlist */ /* Description : Selection in the user listcontrol has changed. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnSelchangeUserlist() { UpdateData(); // save data of previous selected user if (m_nPreviousIndex != -1) { int nOldindex = m_UsersList.GetItemData(m_nPreviousIndex); m_UserArray[nOldindex].m_strPassword = m_strPassword; m_UserArray[nOldindex].m_bAccountDisabled = m_bDisableAccount; } // get selected user int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if (nSelIndex != -1) { int nUserIndex = m_UsersList.GetItemData(nSelIndex); // update dialog variables m_strPassword = m_UserArray[nUserIndex].m_strPassword; m_bDisableAccount = m_UserArray[nUserIndex].m_bAccountDisabled; m_DirectoryList.DeleteAllItems(); // fill the directory list for (int i=0; i < m_UserArray[nUserIndex].m_DirectoryArray.GetSize(); i++) { int nItem = m_DirectoryList.InsertItem(i, m_UserArray[nUserIndex].m_DirectoryArray[i].m_strDir); m_DirectoryList.SetItemText(nItem, 1, m_UserArray[nUserIndex].m_DirectoryArray[i].m_strAlias); m_DirectoryList.SetItemText(nItem, 2, m_UserArray[nUserIndex].m_DirectoryArray[i].m_bAllowDownload ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 3, m_UserArray[nUserIndex].m_DirectoryArray[i].m_bAllowUpload ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 4, m_UserArray[nUserIndex].m_DirectoryArray[i].m_bAllowRename ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 5, m_UserArray[nUserIndex].m_DirectoryArray[i].m_bAllowDelete ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 6, m_UserArray[nUserIndex].m_DirectoryArray[i].m_bAllowCreateDirectory ? "Y" : "N"); LVITEM lvi; ZeroMemory(&lvi, sizeof (LV_ITEM)); lvi.mask = LVIF_IMAGE|LVIF_PARAM; lvi.iItem = nItem; m_DirectoryList.GetItem(&lvi); lvi.lParam = i; lvi.iImage = m_UserArray[nUserIndex].m_DirectoryArray[i].m_bIsHomeDir ? 1 : 0; m_DirectoryList.SetItem(&lvi); } m_nPreviousIndex = nSelIndex; } else { // nothing selected... m_DirectoryList.DeleteAllItems(); m_strPassword = ""; m_bDisableAccount = FALSE; } UpdateData(FALSE); UpdateDialogControls(this, FALSE); AutoSizeColumns(); } /********************************************************************/ /* */ /* Function name : OnOK */ /* Description : Called when the user clicks the OK button. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnOK() { m_UsersList.SetItemState(-1 ,LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); // force update OnSelchangeUserlist(); CDialogResize::OnOK(); } /********************************************************************/ /* */ /* Function name : OnDblclkDirlist */ /* Description : Double clicked a directy item. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnDblclkDirlist(NMHDR* pNMHDR, LRESULT* pResult) { OnEditDir(); *pResult = 0; } /********************************************************************/ /* */ /* Function name : OnAddUser */ /* Description : Add a new user account. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnAddUser() { CAddUserDlg dlg; if (dlg.DoModal() == IDOK) { for (int i=0; i<m_UsersList.GetItemCount(); i++) { CString strName; strName = m_UsersList.GetItemText(i, 0); if (strName.CompareNoCase(dlg.m_strName) == 0) { AfxMessageBox("Sorry, this user already exists!"); return; } } CUser user; user.m_strName = dlg.m_strName; user.m_strPassword = ""; int nItem = m_UsersList.InsertItem(0, user.m_strName, 2); if (nItem <= m_nPreviousIndex) m_nPreviousIndex++; int index = m_UserArray.Add(user); m_UsersList.SetItemData(nItem, index); m_UsersList.SetItemState(nItem, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); OnSelchangeUserlist(); } } /********************************************************************/ /* */ /* Function name : OnEditUser */ /* Description : Edit user account name. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnEditUser() { // get selected user int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nUserIndex = m_UsersList.GetItemData(nSelIndex); CAddUserDlg dlg; dlg.m_strTitle = "Edit User"; dlg.m_strName = m_UserArray[nUserIndex].m_strName; if (dlg.DoModal() == IDOK) { // check if user already exists for (int i=0; i<m_UsersList.GetItemCount(); i++) { if (i != nSelIndex) { CString strName; strName = m_UsersList.GetItemText(i, 0); if (strName.CompareNoCase(dlg.m_strName) == 0) { AfxMessageBox("Sorry, this user already exists!"); return; } } } m_UserArray[nUserIndex].m_strName = dlg.m_strName; m_UsersList.DeleteItem(nSelIndex); nSelIndex = m_UsersList.InsertItem(0, dlg.m_strName, 2); m_UsersList.SetItemData(nSelIndex, nUserIndex); m_UsersList.SetItemState(nSelIndex, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); m_nPreviousIndex = nSelIndex; OnSelchangeUserlist(); } } /********************************************************************/ /* */ /* Function name : OnDelUser */ /* Description : Delete user account. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnDelUser() { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nUserIndex = m_UsersList.GetItemData(nSelIndex); // remove user from listcontrol m_UsersList.DeleteItem(nSelIndex); // remove user from array m_UserArray.RemoveAt(nUserIndex); m_nPreviousIndex = -1; // update item data values for (int i=0; i<m_UsersList.GetItemCount(); i++) { int nItemData = m_UsersList.GetItemData(i); if (nItemData > nSelIndex) m_UsersList.SetItemData(i, nItemData-1); } OnSelchangeUserlist(); } /********************************************************************/ /* */ /* Function name : OnAddDir */ /* Description : Add directory entry to user account. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnAddDir() { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; CDirectoryDlg dlg; dlg.m_bIsHomeDir = m_DirectoryList.GetItemCount() ? FALSE : TRUE; if (dlg.DoModal() == IDOK) { int nUserIndex = m_UsersList.GetItemData(nSelIndex); CDirectory dir; dir.m_bAllowCreateDirectory = dlg.m_bAllowCreateDirectory; dir.m_bAllowDelete = dlg.m_bAllowDelete; dir.m_bAllowDownload = dlg.m_bAllowDownload; dir.m_bAllowRename = dlg.m_bAllowRename; dir.m_bAllowUpload = dlg.m_bAllowUpload; dir.m_bIsHomeDir = FALSE; dir.m_strDir = dlg.m_strPath; dir.m_strAlias = dlg.m_strAlias; dir.m_bIsHomeDir = m_DirectoryList.GetItemCount() ? FALSE : TRUE; int nIndex = m_UserArray[nUserIndex].m_DirectoryArray.Add(dir); int nItem = m_DirectoryList.InsertItem(LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE, 0, dlg.m_strPath, 0, 0, dir.m_bIsHomeDir?1:0, nIndex); m_DirectoryList.SetItemText(nItem, 1, dir.m_strAlias); m_DirectoryList.SetItemText(nItem, 2, dir.m_bAllowDownload ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 3, dir.m_bAllowUpload ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 4, dir.m_bAllowRename ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 5, dir.m_bAllowDelete ? "Y" : "N"); m_DirectoryList.SetItemText(nItem, 6, dir.m_bAllowCreateDirectory ? "Y" : "N"); m_DirectoryList.SetItemState(nItem, LVIS_SELECTED, LVIS_SELECTED); } } /********************************************************************/ /* */ /* Function name : OnEditDir */ /* Description : Edit directory entry properties. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnEditDir() { // get selected user int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nUserIndex = m_UsersList.GetItemData(nSelIndex); // get index of selected directory item nSelIndex = m_DirectoryList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nDirIndex = m_DirectoryList.GetItemData(nSelIndex); CDirectoryDlg dlg; dlg.m_strTitle = "Edit Directory"; dlg.m_bAllowCreateDirectory = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowCreateDirectory; dlg.m_bAllowDelete = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowDelete; dlg.m_bAllowDownload = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowDownload; dlg.m_bAllowRename = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowRename; dlg.m_bAllowUpload = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowUpload; dlg.m_strPath = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_strDir; dlg.m_strAlias = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_strAlias; dlg.m_bIsHomeDir = m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bIsHomeDir; if (!dlg.m_strAlias.IsEmpty()) dlg.m_bVirtualDir = TRUE; if (dlg.DoModal() == IDOK) { m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowCreateDirectory = dlg.m_bAllowCreateDirectory; m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowDelete = dlg.m_bAllowDelete; m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowDownload = dlg.m_bAllowDownload; m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowRename = dlg.m_bAllowRename; m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_bAllowUpload = dlg.m_bAllowUpload; m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_strDir = dlg.m_strPath; if (dlg.m_bVirtualDir) m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_strAlias = dlg.m_strAlias; else m_UserArray[nUserIndex].m_DirectoryArray[nDirIndex].m_strAlias = ""; m_DirectoryList.SetItemText(nDirIndex, 0, dlg.m_strPath); m_DirectoryList.SetItemText(nDirIndex, 1, dlg.m_strAlias); m_DirectoryList.SetItemText(nDirIndex, 2, dlg.m_bAllowDownload ? "Y" : "N"); m_DirectoryList.SetItemText(nDirIndex, 3, dlg.m_bAllowUpload ? "Y" : "N"); m_DirectoryList.SetItemText(nDirIndex, 4, dlg.m_bAllowRename ? "Y" : "N"); m_DirectoryList.SetItemText(nDirIndex, 5, dlg.m_bAllowDelete ? "Y" : "N"); m_DirectoryList.SetItemText(nDirIndex, 6, dlg.m_bAllowCreateDirectory ? "Y" : "N"); OnSelchangeUserlist(); } } /********************************************************************/ /* */ /* Function name : OnDelDir */ /* Description : Delete directory entry from user account. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnDelDir() { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; // get index of selected user item int nUserIndex = m_UsersList.GetItemData(nSelIndex); // get index of selected directory item nSelIndex = m_DirectoryList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nDirIndex = m_DirectoryList.GetItemData(nSelIndex); // delete item from list m_DirectoryList.DeleteItem(nSelIndex); m_UserArray[nUserIndex].m_DirectoryArray.RemoveAt(nDirIndex); for (int i=0; i < m_DirectoryList.GetItemCount(); i++) { int nItemData = m_DirectoryList.GetItemData(i); if (nItemData > nDirIndex) { m_DirectoryList.SetItemData(i, nItemData-1); } } UpdateDialogControls(this, FALSE); } /********************************************************************/ /* */ /* Function name : OnSetHome */ /* Description : Make selected directory the home directory. */ /* */ /********************************************************************/ void CUserAccountsDlg::OnSetHome() { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); if(nSelIndex == -1) return; int nUserIndex = m_UsersList.GetItemData(nSelIndex); // get index of selected directory item POSITION pos; pos = m_DirectoryList.GetFirstSelectedItemPosition(); if (!pos) return; int nDirIndex = m_DirectoryList.GetNextSelectedItem(pos); for (int i=0; i<m_UserArray[nUserIndex].m_DirectoryArray.GetSize(); i++) { LVITEM lvi; ZeroMemory(&lvi, sizeof (LV_ITEM)); lvi.mask = LVIF_IMAGE|LVIF_PARAM; lvi.iItem = i; m_DirectoryList.GetItem(&lvi); if (i == nDirIndex) { // set bIsHome flag for selected directory lvi.iImage = 1; m_UserArray[nUserIndex].m_DirectoryArray[lvi.lParam].m_bIsHomeDir = TRUE; } else { // clear old bIsHomeDir flag lvi.iImage = 0; m_UserArray[nUserIndex].m_DirectoryArray[lvi.lParam].m_bIsHomeDir = FALSE; } m_DirectoryList.SetItem(&lvi); } } void CUserAccountsDlg::OnUpdateControls(CCmdUI* pCmdUI) { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); pCmdUI->Enable(nSelIndex != -1 && !IsDlgButtonChecked(IDC_DISABLE_ACCOUNT)); } void CUserAccountsDlg::OnUpdateDisableAccount(CCmdUI* pCmdUI) { int nSelIndex = m_UsersList.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED); pCmdUI->Enable(nSelIndex != -1); } CString CUserAccountsDlg::GetAttributes(CDirectory &dir) { CString strResult; strResult.Format("%c%c%c%c%c", dir.m_bAllowDownload ? 'Y':'-', dir.m_bAllowUpload ? 'Y':'-', dir.m_bAllowRename ? 'Y':'-', dir.m_bAllowDelete ? 'Y':'-', dir.m_bAllowCreateDirectory ? 'Y':'-'); return strResult; } /********************************************************************/ /* */ /* Function name : AutoSizeColumns */ /* Description : Make all columns fit nicely. */ /* */ /********************************************************************/ void CUserAccountsDlg::AutoSizeColumns() { // Call this after your the control is filled m_DirectoryList.SetRedraw(FALSE); int mincol = 0; int maxcol = m_DirectoryList.GetHeaderCtrl()->GetItemCount()-1; int col; for (col = mincol; col <= maxcol; col++) { m_DirectoryList.SetColumnWidth(col,LVSCW_AUTOSIZE); int wc1 = m_DirectoryList.GetColumnWidth(col); m_DirectoryList.SetColumnWidth(col,LVSCW_AUTOSIZE_USEHEADER); int wc2 = m_DirectoryList.GetColumnWidth(col); // 10 is minumim column width int wc = max(10, max(wc1,wc2)); m_DirectoryList.SetColumnWidth(col,wc); } m_DirectoryList.SetRedraw(TRUE); } /********************************************************************/ /* */ /* Function name : OnDisableAccount */ /* Description : Disable account has been clicked */ /* */ /********************************************************************/ void CUserAccountsDlg::OnDisableAccount() { UpdateDialogControls(this, FALSE); } /********************************************************************/ /* */ /* Function name : OnWizard */ /* Description : Launch New Account Wizard */ /* */ /********************************************************************/ void CUserAccountsDlg::OnWizard() { CBitmap bmpHeader, bmpWatermark; VERIFY(bmpHeader.LoadBitmap(IDB_BANNER)); VERIFY(bmpWatermark.LoadBitmap(IDB_WATERMARK)); // show windows 2000-like wizard CWizardSheet wizSheet("New Account Wizard", this, 0, bmpWatermark, NULL, bmpHeader); wizSheet.m_psh.hInstance = ::GetModuleHandle(NULL); if (wizSheet.DoModal() == ID_WIZFINISH) { int nIndex = -1; int nItem = -1; // existing account ? for (int i=0; i<m_UsersList.GetItemCount(); i++) { CString strName; strName = m_UsersList.GetItemText(i, 0); if (strName.CompareNoCase(wizSheet.m_Page1.m_strAccountName) == 0) { nItem = i; nIndex = m_UsersList.GetItemData(i); break; } } // add new account if (nIndex == -1) { CUser user; int nItem = m_UsersList.InsertItem(0, wizSheet.m_Page1.m_strAccountName, 2); nIndex = m_UserArray.Add(user); m_UsersList.SetItemData(nItem, nIndex); } else { // clear old bIsHomeDir flag for (int i=0; i<m_UserArray[nIndex].m_DirectoryArray.GetSize(); i++) { m_UserArray[nIndex].m_DirectoryArray[i].m_bIsHomeDir = FALSE; } } m_UserArray[nIndex].m_bAccountDisabled = FALSE; m_UserArray[nIndex].m_strName = wizSheet.m_Page1.m_strAccountName; m_UserArray[nIndex].m_strPassword = wizSheet.m_Page2.m_strPassword; // add home directory CDirectory directory; directory.m_strDir = wizSheet.m_Page3.m_strHomeDirectory; directory.m_strAlias = ""; directory.m_bIsHomeDir = TRUE; directory.m_bAllowCreateDirectory = wizSheet.m_Page4.m_bAllowCreateDirectory; directory.m_bAllowDelete = wizSheet.m_Page4.m_bAllowDelete; directory.m_bAllowDownload = wizSheet.m_Page4.m_bAllowDownload; directory.m_bAllowRename = wizSheet.m_Page4.m_bAllowRename; directory.m_bAllowUpload = wizSheet.m_Page4.m_bAllowUpload; directory.m_strAlias = ""; m_UserArray[nIndex].m_DirectoryArray.Add(directory); if (m_nPreviousIndex == nItem) m_nPreviousIndex = -1; // select updated account m_UsersList.SetItemState(nItem, LVIS_SELECTED | LVIS_FOCUSED , LVIS_SELECTED | LVIS_FOCUSED); OnSelchangeUserlist(); } }
#include "src/web_server/http/form_validation.hh" #include "sim/sql_fields/blob.hh" #include "sim/sql_fields/bool.hh" #include "sim/sql_fields/varbinary.hh" #include "simlib/concat_tostr.hh" #include "simlib/enum_with_string_conversions.hh" #include "simlib/random_bytes.hh" #include "simlib/ranges.hh" #include "simlib/result.hh" #include "simlib/string_view.hh" #include "src/web_server/http/form_fields.hh" #include <cassert> #include <cstdint> #include <gtest/gtest.h> #include <initializer_list> #include <limits> #include <optional> #include <string> #include <type_traits> using std::nullopt; using std::optional; using std::string; using std::string_view; using web_server::http::ApiParam; using web_server::http::FormFields; namespace { class ValidationTest { FormFields ff; public: ValidationTest() = default; template <class T, class ResT = T> Result<ResT, string> validate(optional<string> form_field_value) { ff = FormFields{}; if (form_field_value) { ff.add_field("abc", std::move(*form_field_value)); } constexpr ApiParam<T> param_abc{"abc", "ABC"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc) ); static_assert(std::is_same_v<decltype(abc), ResT>); return Ok{abc}; } template <class T, class ResT = T> Result<ResT, string> validate_allow_blank(optional<string> form_field_value) { ff = FormFields{}; if (form_field_value) { ff.add_field("abc", std::move(*form_field_value)); } constexpr ApiParam<T> param_abc{"abc", "ABC"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc, ALLOW_BLANK) ); static_assert(std::is_same_v<decltype(abc), ResT>); return Ok{abc}; } template <class T, class ResT = T> Result<optional<ResT>, string> validate_allow_if(optional<string> form_field_value, bool condition) { ff = FormFields{}; if (form_field_value) { ff.add_field("abc", std::move(*form_field_value)); } constexpr ApiParam<T> param_abc{"abc", "ABC"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc, ALLOW_IF(condition)) ); static_assert(std::is_same_v<decltype(abc), optional<ResT>>); return Ok{abc}; } template <class T, class ResT = T> Result<optional<ResT>, string> validate_allow_blank_allow_if(optional<string> form_field_value, bool condition) { ff = FormFields{}; if (form_field_value) { ff.add_field("abc", std::move(*form_field_value)); } constexpr ApiParam<T> param_abc{"abc", "ABC"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc, ALLOW_BLANK_ALLOW_IF(condition)) ); static_assert(std::is_same_v<decltype(abc), optional<ResT>>); return Ok{abc}; } }; } // namespace constexpr size_t test_str_default_max_len = 70'000; template <class StrType> static void test_str(size_t max_len = test_str_default_max_len) { ValidationTest t; assert(max_len >= strlen("test value")); EXPECT_EQ(t.validate<StrType>("test value"), Ok{"test value"}); EXPECT_EQ(t.validate<StrType>(""), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate<StrType>(nullopt), Err{"abc: ABC is not set"}); auto str = random_bytes(max_len); EXPECT_EQ(t.validate<StrType>(str), Ok{str}); } template <class StrType> static void test_str_allow_blank(size_t max_len = test_str_default_max_len) { ValidationTest t; assert(max_len >= strlen("test value")); EXPECT_EQ(t.validate_allow_blank<StrType>("test value"), Ok{"test value"}); EXPECT_EQ(t.validate_allow_blank<StrType>(""), Ok{""}); EXPECT_EQ(t.validate_allow_blank<StrType>(nullopt), Err{"abc: ABC is not set"}); auto str = random_bytes(max_len); EXPECT_EQ(t.validate<StrType>(str), Ok{str}); } template <class StrType> static void test_str_allow_if(size_t max_len = test_str_default_max_len) { ValidationTest t; assert(max_len >= strlen("test value")); EXPECT_EQ(t.validate_allow_if<StrType>("test value", true), Ok{"test value"}); EXPECT_EQ(t.validate_allow_if<StrType>("", true), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate_allow_if<StrType>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_if<StrType>("test value", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<StrType>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_if<StrType>(nullopt, false), Ok{nullopt}); auto str = random_bytes(max_len); EXPECT_EQ(t.validate_allow_if<StrType>(str, true), Ok{str}); EXPECT_EQ( t.validate_allow_if<StrType>(str, false), Err{"abc: ABC should not be sent within request at all"}); } template <class StrType> static void test_str_allow_blank_allow_if(size_t max_len = test_str_default_max_len) { ValidationTest t; assert(max_len >= strlen("test value")); EXPECT_EQ(t.validate_allow_blank_allow_if<StrType>("test value", true), Ok{"test value"}); EXPECT_EQ(t.validate_allow_blank_allow_if<StrType>("", true), Ok{""}); EXPECT_EQ( t.validate_allow_blank_allow_if<StrType>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_blank_allow_if<StrType>("test value", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<StrType>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_blank_allow_if<StrType>(nullopt, false), Ok{nullopt}); auto str = random_bytes(max_len); EXPECT_EQ(t.validate_allow_if<StrType>(str, true), Ok{str}); EXPECT_EQ( t.validate_allow_if<StrType>(str, false), Err{"abc: ABC should not be sent within request at all"}); } // NOLINTNEXTLINE TEST(form_validation, cstring_view) { test_str<CStringView>(); } // NOLINTNEXTLINE TEST(form_validation, cstring_view_allow_blank) { test_str_allow_blank<CStringView>(); } // NOLINTNEXTLINE TEST(form_validation, cstring_view_allow_if) { test_str_allow_if<CStringView>(); } // NOLINTNEXTLINE TEST(form_validation, cstring_view_allow_blank_allow_if) { test_str_allow_blank_allow_if<CStringView>(); } // NOLINTNEXTLINE TEST(form_validation, sql_blob) { test_str<sim::sql_fields::Blob<>>(); } // NOLINTNEXTLINE TEST(form_validation, sql_blob_allow_blank) { test_str_allow_blank<sim::sql_fields::Blob<>>(); } // NOLINTNEXTLINE TEST(form_validation, sql_blob_allow_if) { test_str_allow_if<sim::sql_fields::Blob<>>(); } // NOLINTNEXTLINE TEST(form_validation, sql_blob_allow_blank_allow_if) { test_str_allow_blank_allow_if<sim::sql_fields::Blob<>>(); } // NOLINTNEXTLINE TEST(form_validation, sql_varbinary) { ValidationTest t; constexpr size_t max_len = 14; using T = sim::sql_fields::Varbinary<max_len>; test_str<T>(max_len); for (size_t len = 1; len < max_len + 5; ++len) { auto str = random_bytes(len); using RT = Result<string, string>; EXPECT_EQ( t.validate<T>(str), len <= max_len ? RT{Ok{str}} : RT{Err{concat_tostr("abc: ABC cannot be longer than ", max_len, " bytes")}}); } } // NOLINTNEXTLINE TEST(form_validation, sql_varbinary_allow_blank) { ValidationTest t; constexpr size_t max_len = 14; using T = sim::sql_fields::Varbinary<max_len>; test_str_allow_blank<T>(max_len); for (size_t len = 1; len < max_len + 5; ++len) { auto str = random_bytes(len); using RT = Result<string, string>; EXPECT_EQ( t.validate_allow_blank<T>(str), len <= max_len ? RT{Ok{str}} : RT{Err{concat_tostr("abc: ABC cannot be longer than ", max_len, " bytes")}}); } } // NOLINTNEXTLINE TEST(form_validation, sql_varbinary_allow_if) { ValidationTest t; constexpr size_t max_len = 14; using T = sim::sql_fields::Varbinary<max_len>; test_str_allow_if<T>(max_len); for (size_t len = 1; len < max_len + 5; ++len) { auto str = random_bytes(len); using RT = Result<string, string>; EXPECT_EQ( t.validate_allow_if<T>(str, true), len <= max_len ? RT{Ok{str}} : RT{Err{concat_tostr("abc: ABC cannot be longer than ", max_len, " bytes")}}); EXPECT_EQ( t.validate_allow_if<T>(str, false), Err{concat_tostr("abc: ABC should not be sent within request at all")}); } } // NOLINTNEXTLINE TEST(form_validation, sql_varbinary_allow_blank_allow_if) { ValidationTest t; constexpr size_t max_len = 14; using T = sim::sql_fields::Varbinary<max_len>; test_str_allow_blank_allow_if<T>(max_len); for (size_t len = 1; len < max_len + 5; ++len) { auto str = random_bytes(len); using RT = Result<string, string>; EXPECT_EQ( t.validate_allow_blank_allow_if<T>(str, true), len <= max_len ? RT{Ok{str}} : RT{Err{concat_tostr("abc: ABC cannot be longer than ", max_len, " bytes")}}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(str, false), Err{concat_tostr("abc: ABC should not be sent within request at all")}); } } template <class Bool, class ResT = Bool> static void test_bool() { ValidationTest t; EXPECT_EQ((t.validate<Bool, ResT>("true")), Ok{true}); EXPECT_EQ((t.validate<Bool, ResT>("false")), Ok{false}); EXPECT_EQ((t.validate<Bool, ResT>("on")), Err{"abc: ABC has invalid value"}); EXPECT_EQ((t.validate<Bool, ResT>("")), Err{"abc: ABC cannot be blank"}); EXPECT_EQ((t.validate<Bool, ResT>(nullopt)), Err{"abc: ABC is not set"}); } template <class Bool, class ResT = Bool> static void test_bool_allow_blank() { ValidationTest t; EXPECT_EQ((t.validate_allow_blank<Bool, ResT>("true")), Ok{true}); EXPECT_EQ((t.validate_allow_blank<Bool, ResT>("false")), Ok{false}); EXPECT_EQ((t.validate_allow_blank<Bool, ResT>("on")), Err{"abc: ABC has invalid value"}); EXPECT_EQ((t.validate_allow_blank<Bool, ResT>("")), Err{"abc: ABC has invalid value"}); EXPECT_EQ((t.validate_allow_blank<Bool, ResT>(nullopt)), Err{"abc: ABC is not set"}); } template <class Bool, class ResT = Bool> static void test_bool_allow_if() { ValidationTest t; EXPECT_EQ((t.validate_allow_if<Bool, ResT>("true", true)), Ok{true}); EXPECT_EQ((t.validate_allow_if<Bool, ResT>("false", true)), Ok{false}); EXPECT_EQ( (t.validate_allow_if<Bool, ResT>("on", true)), Err{"abc: ABC has invalid value"}); EXPECT_EQ((t.validate_allow_if<Bool, ResT>("", true)), Err{"abc: ABC cannot be blank"}); EXPECT_EQ((t.validate_allow_if<Bool, ResT>(nullopt, true)), Err{"abc: ABC is not set"}); EXPECT_EQ( (t.validate_allow_if<Bool, ResT>("true", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_if<Bool, ResT>("false", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_if<Bool, ResT>("on", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_if<Bool, ResT>("", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ((t.validate_allow_if<Bool, ResT>(nullopt, false)), Ok{nullopt}); } template <class Bool, class ResT = Bool> static void test_bool_allow_blank_allow_if() { ValidationTest t; EXPECT_EQ((t.validate_allow_blank_allow_if<Bool, ResT>("true", true)), Ok{true}); EXPECT_EQ((t.validate_allow_blank_allow_if<Bool, ResT>("false", true)), Ok{false}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("on", true)), Err{"abc: ABC has invalid value"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("", true)), Err{"abc: ABC has invalid value"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>(nullopt, true)), Err{"abc: ABC is not set"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("true", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("false", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("on", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( (t.validate_allow_blank_allow_if<Bool, ResT>("", false)), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ((t.validate_allow_blank_allow_if<Bool, ResT>(nullopt, false)), Ok{nullopt}); } // NOLINTNEXTLINE TEST(form_validation, bool) { test_bool<bool>(); } // NOLINTNEXTLINE TEST(form_validation, bool_allow_blank) { test_bool_allow_blank<bool>(); } // NOLINTNEXTLINE TEST(form_validation, bool_allow_if) { test_bool_allow_if<bool>(); } // NOLINTNEXTLINE TEST(form_validation, bool_allow_blank_allow_if) { test_bool_allow_blank_allow_if<bool>(); } // NOLINTNEXTLINE TEST(form_validation, sql_bool) { test_bool<sim::sql_fields::Bool, bool>(); } // NOLINTNEXTLINE TEST(form_validation, sql_bool_allow_blank) { test_bool_allow_blank<sim::sql_fields::Bool, bool>(); } // NOLINTNEXTLINE TEST(form_validation, sql_bool_allow_if) { test_bool_allow_if<sim::sql_fields::Bool, bool>(); } // NOLINTNEXTLINE TEST(form_validation, sql_bool_allow_blank_allow_if) { test_bool_allow_blank_allow_if<sim::sql_fields::Bool, bool>(); } template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0> static void test_int() { ValidationTest t; using nl = std::numeric_limits<T>; auto err_val_str = Err{concat_tostr("abc: ABC is not in range [", nl::min(), ", ", nl::max(), "]")}; EXPECT_EQ(t.validate<T>("0"), Ok{T{}}); EXPECT_EQ(t.validate<T>(std::to_string(nl::min())), Ok{nl::min()}); EXPECT_EQ(t.validate<T>(std::to_string(nl::min() + 1)), Ok{nl::min() + 1}); if constexpr (std::is_signed_v<T>) { EXPECT_EQ(t.validate<T>("-1"), Ok{T{-1}}); EXPECT_EQ(t.validate<T>("-42"), Ok{T{-42}}); } EXPECT_EQ(t.validate<T>(std::to_string(nl::max())), Ok{nl::max()}); EXPECT_EQ(t.validate<T>(std::to_string(nl::max() - 1)), Ok{nl::max() - 1}); EXPECT_EQ(t.validate<T>(""), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate<T>("x"), Err{err_val_str}); EXPECT_EQ(t.validate<T>("abc"), Err{err_val_str}); EXPECT_EQ(t.validate<T>("1-1"), Err{err_val_str}); EXPECT_EQ(t.validate<T>("4.4"), Err{err_val_str}); EXPECT_EQ(t.validate<T>(nullopt), Err{"abc: ABC is not set"}); } template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0> static void test_int_allow_blank() { ValidationTest t; using nl = std::numeric_limits<T>; auto err_val_str = Err{concat_tostr("abc: ABC is not in range [", nl::min(), ", ", nl::max(), "]")}; EXPECT_EQ(t.validate_allow_blank<T>("0"), Ok{T{}}); EXPECT_EQ(t.validate_allow_blank<T>(std::to_string(nl::min())), Ok{nl::min()}); EXPECT_EQ(t.validate_allow_blank<T>(std::to_string(nl::min() + 1)), Ok{nl::min() + 1}); if constexpr (std::is_signed_v<T>) { EXPECT_EQ(t.validate_allow_blank<T>("-1"), Ok{T{-1}}); EXPECT_EQ(t.validate_allow_blank<T>("-42"), Ok{T{-42}}); } EXPECT_EQ(t.validate_allow_blank<T>(std::to_string(nl::max())), Ok{nl::max()}); EXPECT_EQ(t.validate_allow_blank<T>(std::to_string(nl::max() - 1)), Ok{nl::max() - 1}); EXPECT_EQ(t.validate_allow_blank<T>(""), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank<T>("x"), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank<T>("abc"), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank<T>("1-1"), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank<T>("4.4"), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank<T>(nullopt), Err{"abc: ABC is not set"}); } template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0> static void test_int_allow_if() { ValidationTest t; using nl = std::numeric_limits<T>; auto err_val_str = Err{concat_tostr("abc: ABC is not in range [", nl::min(), ", ", nl::max(), "]")}; EXPECT_EQ(t.validate_allow_if<T>("0", true), Ok{T{}}); EXPECT_EQ(t.validate_allow_if<T>(std::to_string(nl::min()), true), Ok{nl::min()}); EXPECT_EQ(t.validate_allow_if<T>(std::to_string(nl::min() + 1), true), Ok{nl::min() + 1}); if constexpr (std::is_signed_v<T>) { EXPECT_EQ(t.validate_allow_if<T>("-1", true), Ok{T{-1}}); EXPECT_EQ(t.validate_allow_if<T>("-42", true), Ok{T{-42}}); } EXPECT_EQ(t.validate_allow_if<T>(std::to_string(nl::max()), true), Ok{nl::max()}); EXPECT_EQ(t.validate_allow_if<T>(std::to_string(nl::max() - 1), true), Ok{nl::max() - 1}); EXPECT_EQ(t.validate_allow_if<T>("", true), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate_allow_if<T>("x", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_if<T>("abc", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_if<T>("1-1", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_if<T>("4.4", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); for (auto field_val : std::initializer_list<string>{ "0", std::to_string(nl::min()), std::to_string(nl::min() + 1), "-1", "-42", std::to_string(nl::max()), std::to_string(nl::max() - 1), "", "x", "abc", "1-1", "4.4"}) { EXPECT_EQ( t.validate_allow_if<T>(field_val, false), Err{"abc: ABC should not be sent within request at all"}); } EXPECT_EQ(t.validate_allow_if<T>(nullopt, false), Ok{nullopt}); } template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0> static void test_int_allow_blank_allow_if() { ValidationTest t; using nl = std::numeric_limits<T>; auto err_val_str = Err{concat_tostr("abc: ABC is not in range [", nl::min(), ", ", nl::max(), "]")}; EXPECT_EQ(t.validate_allow_blank_allow_if<T>("0", true), Ok{T{}}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(std::to_string(nl::min()), true), Ok{nl::min()}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(std::to_string(nl::min() + 1), true), Ok{nl::min() + 1}); if constexpr (std::is_signed_v<T>) { EXPECT_EQ(t.validate_allow_blank_allow_if<T>("-1", true), Ok{T{-1}}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("-42", true), Ok{T{-42}}); } EXPECT_EQ( t.validate_allow_blank_allow_if<T>(std::to_string(nl::max()), true), Ok{nl::max()}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(std::to_string(nl::max() - 1), true), Ok{nl::max() - 1}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("x", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("abc", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("1-1", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("4.4", true), Err{err_val_str}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); for (auto field_val : std::initializer_list<string>{ "0", std::to_string(nl::min()), std::to_string(nl::min() + 1), "-1", "-42", std::to_string(nl::max()), std::to_string(nl::max() - 1), "", "x", "abc", "1-1", "4.4"}) { EXPECT_EQ( t.validate_allow_blank_allow_if<T>(field_val, false), Err{"abc: ABC should not be sent within request at all"}); } EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, false), Ok{nullopt}); } #define test_integers(func) \ func<int>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<ssize_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<int8_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<int16_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<int32_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<int64_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ \ func<unsigned>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<size_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<uint8_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<uint16_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<uint32_t>(); /* NOLINT(bugprone-macro-parentheses) */ \ func<uint64_t>() /* NOLINT(bugprone-macro-parentheses) */ // NOLINTNEXTLINE TEST(form_validation, integers) { test_integers(test_int); } // NOLINTNEXTLINE TEST(form_validation, integers_allow_blank) { test_integers(test_int_allow_blank); } // NOLINTNEXTLINE TEST(form_validation, integers_allow_if) { test_integers(test_int_allow_if); } // NOLINTNEXTLINE TEST(form_validation, integers_allow_blank_allow_if) { test_integers(test_int_allow_blank_allow_if); } static constexpr auto predicate = [](const sim::sql_fields::Varbinary<20>& x) { return x.size % 10 == 7; }; static constexpr char predicate_description[] = "does not have length ending with 7"; // NOLINTNEXTLINE TEST(form_validation, satisfying_predicate) { ValidationTest t; using sim::sql_fields::SatisfyingPredicate; using sim::sql_fields::Varbinary; using T = SatisfyingPredicate<Varbinary<20>, predicate, predicate_description>; EXPECT_EQ(t.validate<T>("1234567"), Ok{"1234567"}); EXPECT_EQ(t.validate<T>("12345678901234567"), Ok{"12345678901234567"}); EXPECT_EQ(t.validate<T>("test"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate<T>("123456789012345678"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate<T>("1234567890123456789"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate<T>("12345678901234567890"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate<T>("123456789012345678901"), Err{"abc: ABC cannot be longer than 20 bytes"}); EXPECT_EQ(t.validate<T>(""), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate<T>(nullopt), Err{"abc: ABC is not set"}); } // NOLINTNEXTLINE TEST(form_validation, satisfying_predicate_allow_blank) { ValidationTest t; using sim::sql_fields::SatisfyingPredicate; using sim::sql_fields::Varbinary; using T = SatisfyingPredicate<Varbinary<20>, predicate, predicate_description>; EXPECT_EQ(t.validate_allow_blank<T>("1234567"), Ok{"1234567"}); EXPECT_EQ(t.validate_allow_blank<T>("12345678901234567"), Ok{"12345678901234567"}); EXPECT_EQ( t.validate_allow_blank<T>("test"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank<T>("123456789012345678"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank<T>("1234567890123456789"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank<T>("12345678901234567890"), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank<T>("123456789012345678901"), Err{"abc: ABC cannot be longer than 20 bytes"}); EXPECT_EQ( t.validate_allow_blank<T>(""), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ(t.validate_allow_blank<T>(nullopt), Err{"abc: ABC is not set"}); } // NOLINTNEXTLINE TEST(form_validation, satisfying_predicate_allow_if) { ValidationTest t; using sim::sql_fields::SatisfyingPredicate; using sim::sql_fields::Varbinary; using T = SatisfyingPredicate<Varbinary<20>, predicate, predicate_description>; EXPECT_EQ(t.validate_allow_if<T>("1234567", true), Ok{"1234567"}); EXPECT_EQ(t.validate_allow_if<T>("12345678901234567", true), Ok{"12345678901234567"}); EXPECT_EQ( t.validate_allow_if<T>("test", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_if<T>("123456789012345678", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_if<T>("1234567890123456789", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_if<T>("12345678901234567890", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_if<T>("123456789012345678901", true), Err{"abc: ABC cannot be longer than 20 bytes"}); EXPECT_EQ(t.validate_allow_if<T>("", true), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_if<T>("1234567", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("12345678901234567", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("test", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("123456789012345678", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("1234567890123456789", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("12345678901234567890", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("123456789012345678901", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_if<T>(nullopt, false), Ok{nullopt}); } // NOLINTNEXTLINE TEST(form_validation, satisfying_predicate_allow_blank_allow_if) { ValidationTest t; using sim::sql_fields::SatisfyingPredicate; using sim::sql_fields::Varbinary; using T = SatisfyingPredicate<Varbinary<20>, predicate, predicate_description>; EXPECT_EQ(t.validate_allow_blank_allow_if<T>("1234567", true), Ok{"1234567"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("12345678901234567", true), Ok{"12345678901234567"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("test", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("123456789012345678", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("1234567890123456789", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("12345678901234567890", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("123456789012345678901", true), Err{"abc: ABC cannot be longer than 20 bytes"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("", true), Err{"abc: ABC does not have length ending with 7"}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("1234567", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("12345678901234567", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("test", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("123456789012345678", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("1234567890123456789", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("12345678901234567890", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("123456789012345678901", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, false), Ok{nullopt}); } ENUM_WITH_STRING_CONVERSIONS(TestEnum, uint16_t, (FIRST, 111, "> 1 <") (SECOND, 222, "> 2 <") (THIRD, 333, "> 3 <") ); // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions) { ValidationTest t; using T = EnumVal<TestEnum>; EXPECT_EQ(t.validate<T>("> 1 <"), Ok{TestEnum::FIRST}); EXPECT_EQ(t.validate<T>("> 2 <"), Ok{TestEnum::SECOND}); EXPECT_EQ(t.validate<T>("> 3 <"), Ok{TestEnum::THIRD}); EXPECT_EQ(t.validate<T>(" > 1 <"), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate<T>("> 1 < "), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate<T>("> 1 <> 1 <"), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate<T>(""), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate<T>(nullopt), Err{"abc: ABC is not set"}); } // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions_allow_blank) { ValidationTest t; using T = EnumVal<TestEnum>; EXPECT_EQ(t.validate_allow_blank<T>("> 1 <"), Ok{TestEnum::FIRST}); EXPECT_EQ(t.validate_allow_blank<T>("> 2 <"), Ok{TestEnum::SECOND}); EXPECT_EQ(t.validate_allow_blank<T>("> 3 <"), Ok{TestEnum::THIRD}); EXPECT_EQ(t.validate_allow_blank<T>(" > 1 <"), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank<T>("> 1 < "), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank<T>("> 1 <> 1 <"), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank<T>(""), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank<T>(nullopt), Err{"abc: ABC is not set"}); } // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions_allow_if) { ValidationTest t; using T = EnumVal<TestEnum>; EXPECT_EQ(t.validate_allow_if<T>("> 1 <", true), Ok{TestEnum::FIRST}); EXPECT_EQ(t.validate_allow_if<T>("> 2 <", true), Ok{TestEnum::SECOND}); EXPECT_EQ(t.validate_allow_if<T>("> 3 <", true), Ok{TestEnum::THIRD}); EXPECT_EQ(t.validate_allow_if<T>(" > 1 <", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_if<T>("> 1 < ", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_if<T>("> 1 <> 1 <", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_if<T>("", true), Err{"abc: ABC cannot be blank"}); EXPECT_EQ(t.validate_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_if<T>("> 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("> 2 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("> 3 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>(" > 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("> 1 < ", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("> 1 <> 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_if<T>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_if<T>(nullopt, false), Ok{nullopt}); } // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions_allow_blank_allow_if) { ValidationTest t; using T = EnumVal<TestEnum>; EXPECT_EQ(t.validate_allow_blank_allow_if<T>("> 1 <", true), Ok{TestEnum::FIRST}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("> 2 <", true), Ok{TestEnum::SECOND}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("> 3 <", true), Ok{TestEnum::THIRD}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(" > 1 <", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 1 < ", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 1 <> 1 <", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>("", true), Err{"abc: ABC has invalid value"}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, true), Err{"abc: ABC is not set"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 2 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 3 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>(" > 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 1 < ", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("> 1 <> 1 <", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ( t.validate_allow_blank_allow_if<T>("", false), Err{"abc: ABC should not be sent within request at all"}); EXPECT_EQ(t.validate_allow_blank_allow_if<T>(nullopt, false), Ok{nullopt}); } // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions_enum_caps) { auto do_validate = [&](optional<string> form_field_value, bool cap1, bool cap2, bool cap3) -> Result<EnumVal<TestEnum>, string> { FormFields ff; if (form_field_value) { ff.add_field("xyz_field", std::move(*form_field_value)); } constexpr ApiParam<EnumVal<TestEnum>> param_abc{"xyz_field", "AXBYCZ"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc, ENUM_CAPS( (FIRST, cap1) (SECOND, cap2) (THIRD, cap3) )) ); static_assert(std::is_same_v<decltype(abc), EnumVal<TestEnum>>); return Ok{abc}; }; for (auto [idx, str] : enumerate_view(std::array{"> 1 <", "> 2 <", "> 3 <"})) { for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { std::array caps = {cap1, cap2, cap3}; std::array variants = {TestEnum::FIRST, TestEnum::SECOND, TestEnum::THIRD}; using RT = Result<TestEnum, const char*>; EXPECT_EQ( do_validate(str, cap1, cap2, cap3), caps[idx] ? RT{Ok{variants[idx]}} : RT{Err{ "xyz_field: AXBYCZ selects option to which you do not have " "permission"}}) << "idx: " << idx << " caps: " << cap1 << ", " << cap2 << ", " << cap3; } } } } for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { EXPECT_EQ( do_validate(" > 1 <", cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("> 1 < ", cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("> 1 <> 1 <", cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("", cap1, cap2, cap3), Err{"xyz_field: AXBYCZ cannot be blank"}); EXPECT_EQ( do_validate(nullopt, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ is not set"}); } } } } // NOLINTNEXTLINE TEST(form_validation, enum_val_with_string_conversions_enum_caps_allow_if) { auto do_validate = [&](optional<string> form_field_value, bool condition, bool cap1, bool cap2, bool cap3) -> Result<optional<EnumVal<TestEnum>>, string> { FormFields ff; if (form_field_value) { ff.add_field("xyz_field", std::move(*form_field_value)); } constexpr ApiParam<EnumVal<TestEnum>> param_abc{"xyz_field", "AXBYCZ"}; VALIDATE(ff, [&](auto&& errors) { return Err{errors}; }, (abc, param_abc, ENUM_CAPS_ALLOW_IF(condition, (FIRST, cap1) (SECOND, cap2) (THIRD, cap3) )) ); static_assert(std::is_same_v<decltype(abc), optional<EnumVal<TestEnum>>>); return Ok{abc}; }; // ALLOW_IF condition == true for (auto [idx, str] : enumerate_view(std::array{"> 1 <", "> 2 <", "> 3 <"})) { for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { std::array caps = {cap1, cap2, cap3}; std::array variants = {TestEnum::FIRST, TestEnum::SECOND, TestEnum::THIRD}; using RT = Result<TestEnum, const char*>; EXPECT_EQ( do_validate(str, true, cap1, cap2, cap3), caps[idx] ? RT{Ok{variants[idx]}} : RT{Err{ "xyz_field: AXBYCZ selects option to which you do not have " "permission"}}) << "idx: " << idx << " caps: " << cap1 << ", " << cap2 << ", " << cap3; } } } } for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { EXPECT_EQ( do_validate(" > 1 <", true, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("> 1 < ", true, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("> 1 <> 1 <", true, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ has invalid value"}); EXPECT_EQ( do_validate("", true, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ cannot be blank"}); EXPECT_EQ( do_validate(nullopt, true, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ is not set"}); } } } // ALLOW_IF condition == false for (auto str : {"> 1 <", "> 2 <", "> 3 <"}) { for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { EXPECT_EQ( do_validate(str, false, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ should not be sent within request at all"}) << "str: " << str << " caps: " << cap1 << ", " << cap2 << ", " << cap3; } } } } for (auto cap1 : {true, false}) { for (auto cap2 : {true, false}) { for (auto cap3 : {true, false}) { EXPECT_EQ( do_validate(" > 1 <", false, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ should not be sent within request at all"}); EXPECT_EQ( do_validate("> 1 < ", false, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ should not be sent within request at all"}); EXPECT_EQ( do_validate("> 1 <> 1 <", false, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ should not be sent within request at all"}); EXPECT_EQ( do_validate("", false, cap1, cap2, cap3), Err{"xyz_field: AXBYCZ should not be sent within request at all"}); EXPECT_EQ(do_validate(nullopt, false, cap1, cap2, cap3), Ok{nullopt}); } } } }
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbListSampleSource_hxx #define otbListSampleSource_hxx #include "otbListSampleSource.h" namespace otb { namespace Statistics { template < class TInputSampleList, class TOutputSampleList > ListSampleSource<TInputSampleList, TOutputSampleList> ::ListSampleSource() { this->SetNumberOfRequiredOutputs(1); // Generate the output sample list typename OutputSampleListType::Pointer outputPtr = static_cast< OutputSampleListType * >(this->MakeOutput(0).GetPointer()); this->ProcessObject::SetNthOutput(0, outputPtr.GetPointer()); } template < class TInputSampleList, class TOutputSampleList > typename ListSampleSource<TInputSampleList, TOutputSampleList> ::DataObjectPointer ListSampleSource<TInputSampleList, TOutputSampleList> ::MakeOutput(DataObjectPointerArraySizeType) { OutputSampleListPointer outputSampleList = OutputSampleListType::New(); return static_cast<DataObjectPointer>(outputSampleList); } template < class TInputSampleList, class TOutputSampleList > typename ListSampleSource<TInputSampleList, TOutputSampleList> ::OutputSampleListType * ListSampleSource<TInputSampleList, TOutputSampleList> ::GetOutput() { return static_cast<OutputSampleListType * > (this->ProcessObject::GetOutput(0) ); } template < class TInputSampleList, class TOutputSampleList > void ListSampleSource<TInputSampleList, TOutputSampleList> ::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } // End namespace Statistics } // End namespace otb #endif
#include "Perceptron.h" Perceptron::Perceptron(int weights) { _neuron = std::make_unique<Neuron>(weights); } double Perceptron::feedforward(const std::vector<double> inputs) { double output = _neuron->feedforward(inputs, _bias); return output; } void Perceptron::train(const std::vector<double> inputs, double target, double learningRate) { double output = feedforward(inputs); double error = (target - output); std::vector<double> weights = _neuron->getWeights(); for (int c = 0; c < weights.size(); ++c) { weights[c] += inputs[c] * error * learningRate; } _neuron->setWeights(weights); _bias += error; } void Perceptron::serialize(std::ostream &stream) const { stream << std::hex; stream << _bias << std::endl; _neuron->serialize(stream); } void Perceptron::deserialize(std::istream &stream) { stream >> _bias; _neuron->deserialize(stream); } void Perceptron::setActivationFunction(activationfunction::function activationFunction) { _neuron->setActivationFunction(activationFunction); } void Perceptron::randomizeWeights() { _neuron->randomizeWeights(); _bias = random::range(-0.1,0.1); }
#include <slam/occupancy_grid.hpp> #include <algorithm> const float kGridWidth = 15.0f; const float kGridHeight = 15.0f; const float kMetersPerCell = 0.05f; OccupancyGrid generate_uniform_grid(int8_t logOdds); OccupancyGrid generate_constricted_grid(double openingWidth); int main(int argc, char** argv) { // Create four grids needed for astar_test: // An empty grid OccupancyGrid emptyGrid = generate_uniform_grid(-10); emptyGrid.saveToFile("../data/empty.map"); // A filled grid OccupancyGrid filledGrid = generate_uniform_grid(10); filledGrid.saveToFile("../data/filled.map"); // A narrow constriction that the robot can't fit through OccupancyGrid narrowGrid = generate_constricted_grid(0.1); narrowGrid.saveToFile("../data/narrow.map"); // A wide constriction that the robot can fit through OccupancyGrid wideGrid = generate_constricted_grid(0.5); wideGrid.saveToFile("../data/wide.map"); return 0; } OccupancyGrid generate_uniform_grid(int8_t logOdds) { OccupancyGrid grid(kGridWidth, kGridHeight, kMetersPerCell); for(int y = 0; y < grid.heightInCells(); ++y) { for(int x = 0; x < grid.widthInCells(); ++x) { grid(x, y) = logOdds; } } return grid; } OccupancyGrid generate_constricted_grid(double openingWidth) { OccupancyGrid grid = generate_uniform_grid(-10); // Draw a line right through the middle of the grid. Have the line start after the opening. int openingCellY = grid.heightInCells() / 2; int openingWidthInCells = std::max(static_cast<int>(openingWidth * grid.cellsPerMeter()), 1); for(int x = openingWidthInCells; x < grid.widthInCells(); ++x) { grid(x, openingCellY) = 10; } return grid; }
/* * Copyright (c) 2012-2013, Intel 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. * * Author: tianyang.zhu@intel.com * * Adding this file to reduce framework/av hack code lines */ //#define LOG_NDEBUG 0 #include <utils/Log.h> #include <utils/RefBase.h> #include <binder/Parcel.h> #include <binder/IServiceManager.h> #include <binder/IPCThreadState.h> #include <display/MultiDisplayVideoClient.h> namespace android { namespace intel { MultiDisplayVideoClient::MultiDisplayVideoClient() { mSessionId = -1; mState = MDS_VIDEO_UNPREPARED; mVideo = NULL; }; MultiDisplayVideoClient::~MultiDisplayVideoClient() { // ALOGI("Destroy mds video client %d", mSessionId); close(); }; void MultiDisplayVideoClient::close() { mSessionId = -1; mState = MDS_VIDEO_UNPREPARED; mVideo = NULL; } status_t MultiDisplayVideoClient::prepare(int state, bool isProtected) { if (state >= MDS_VIDEO_UNPREPARING && mSessionId < 0) { ALOGW("Invalid unprepared state"); return UNKNOWN_ERROR; } if (state == mState) { // ALOGW("Same state %d", state); return UNKNOWN_ERROR; } if (!isProtected && (state == MDS_VIDEO_PREPARING || state == MDS_VIDEO_UNPREPARING)) { // ignore preparing and unpreparing state if video is not protected ALOGI("Ignore MDS preparing and unpreparing for clear content"); return UNKNOWN_ERROR; } ALOGI("Video state is %d, %d", state, mState); if (mVideo == NULL) { mVideo = new MultiDisplayClient(); } if (mSessionId < 0) { mSessionId = 0;//mVideo->allocateVideoSessionId(); } return NO_ERROR; } status_t MultiDisplayVideoClient::setVideoState(int state, bool isProtected, const sp<MetaData> &meta) { if (prepare(state, isProtected) != NO_ERROR) return UNKNOWN_ERROR; if (state == MDS_VIDEO_PREPARED) { MDSVideoSourceInfo info; memset(&info, 0, sizeof(MDSVideoSourceInfo)); info.isProtected = isProtected; info.isPlaying = true; if (meta != NULL && meta.get() != NULL) { if (!meta->findInt32(kKeyFrameRate, &info.frameRate)) { info.frameRate = 0; } if (!meta->findInt32(kKeyDisplayWidth, &info.displayW)) { info.displayW = 0; } if (!meta->findInt32(kKeyDisplayHeight, &info.displayH)) { info.displayH = 0; } } mVideo->updateVideoSourceInfo(mSessionId, info); ALOGI("%s: Video source Info %d x %d @ %d fps", __func__, info.displayW, info.displayH, info.frameRate); } mVideo->updateVideoState(mSessionId, (MDS_VIDEO_STATE)state); if (state == MDS_VIDEO_UNPREPARED) close(); mState = state; return NO_ERROR; } status_t MultiDisplayVideoClient::setVideoState(int state, bool isProtected, const sp<AMessage> &msg) { if (prepare(state, isProtected) != NO_ERROR) return UNKNOWN_ERROR; if (state == MDS_VIDEO_PREPARED) { if (msg != NULL && msg.get() != NULL) { MDSVideoSourceInfo info; memset(&info, 0, sizeof(MDSVideoSourceInfo)); info.isPlaying = true; info.isProtected = isProtected; bool success = msg->findInt32("frame-rate", &info.frameRate); if (!success) info.frameRate = 0; success = msg->findInt32("width", &info.displayW); if (!success) info.displayW = 0; success = msg->findInt32("height", &info.displayH); if (!success) info.displayH = 0; mVideo->updateVideoSourceInfo(mSessionId, info); ALOGI("%s: Video source Info %d x %d @ %d fps ", __func__, info.displayW, info.displayH, info.frameRate); } } mVideo->updateVideoState(mSessionId, (MDS_VIDEO_STATE)state); if (state == MDS_VIDEO_UNPREPARED) close(); mState = state; return NO_ERROR; } status_t MultiDisplayVideoClient::reset() { if (mVideo != NULL) return mVideo->resetVideoPlayback(); else return UNKNOWN_ERROR; } }; // namespace intel }; // namespace android
#include <iostream> #include <cstdlib> #include <cstdio> using namespace std; int a, b, x, y; int solve(int start, int end, int x, int y) { int d1 = abs(start - x) + abs(end - y); int d2 = abs(start - y) + abs(end - x); int ans = min(abs(start - end), min(d1, d2)); return ans; } int main() { freopen("teleport.in", "r", stdin); freopen("teleport.out", "w", stdout); scanf("%d%d%d%d", &a, &b, &x, &y); printf("%d\n", solve(a, b, x, y)); return 0; }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <array> # include "Fwd.hpp" # include "Color.hpp" # include "HSV.hpp" # include "KinectV1.hpp" namespace s3d { /// <summary> /// Kinect v2 の取得データフラグ /// </summary> struct KinectV2DataType { enum Type { /// <summary> /// カラー (1920×1080) /// </summary> Color = 0x01, /// <summary> /// デプス (512×424) /// </summary> Depth = 0x02, /// <summary> /// ボディインデックス /// </summary> BodyIndex = 0x04, /// <summary> /// ボディ /// </summary> Body = 0x08, /// <summary> /// 赤外線 (512×424) /// </summary> Infrared = 0x10, /// <summary> /// オーディオビーム /// </summary> AudioBeam = 0x20, /// <summary> /// デフォルト [カラー (1920×1080) | デプス (512×424) | ボディインデックス | ボディ] /// </summary> Default = Color | Depth | BodyIndex | Body, }; }; /// <summary> /// 手の状態 /// </summary> enum class HandState { /// <summary> /// 不明 /// </summary> Unknown, /// <summary> /// 追跡されていない /// </summary> NotTracked, /// <summary> /// 開いている /// </summary> Open, /// <summary> /// 閉じている /// </summary> Closed, /// <summary> /// チョキ /// </summary> Lasso, }; /// <summary> /// 関節のインデックス /// </summary> struct V2JointType { enum Type { /// <summary> /// 背骨の下部 /// </summary> SpineBase, /// <summary> /// 背骨の中央 /// </summary> SpineMid, /// <summary> /// 首 /// </summary> Neck, /// <summary> /// 頭 /// </summary> Head, /// <summary> /// 左肩 /// </summary> ShoulderLeft, /// <summary> /// 左ひじ /// </summary> ElbowLeft, /// <summary> /// 左手首 /// </summary> WristLeft, /// <summary> /// 左手 /// </summary> HandLeft, /// <summary> /// 右肩 /// </summary> ShoulderRight, /// <summary> /// 右ひじ /// </summary> ElbowRight, /// <summary> /// 右手首 /// </summary> WristRight, /// <summary> /// 右手 /// </summary> HandRight, /// <summary> /// 左尻 /// </summary> HipLeft, /// <summary> /// 左ひざ /// </summary> KneeLeft, /// <summary> /// 左足首 /// </summary> AnkleLeft, /// <summary> /// 左足 /// </summary> FootLeft, /// <summary> /// 右尻 /// </summary> HipRight, /// <summary> /// 右ひざ /// </summary> KneeRight, /// <summary> /// 右足首 /// </summary> AnkleRight, /// <summary> /// 右足 /// </summary> FootRight, /// <summary> /// 肩の高さの背骨 /// </summary> SpineShoulder, /// <summary> /// 左手の先端 /// </summary> HandTipLeft, /// <summary> /// 左手の親指 /// </summary> ThumbLeft, /// <summary> /// 右手の先端 /// </summary> HandTipRight, /// <summary> /// 右手の親指 /// </summary> ThumbRight, }; }; /// <summary> /// 関節の情報 /// </summary> struct KinectV2Joint { /// <summary> /// カメラ空間での座標 /// </summary> Vec3 cameraSpacePos = Vec3::Zero; /// <summary> /// カラー画像(1920x1080)上の座標 /// </summary> Vec2 colorSpacePos = Vec2::Zero; /// <summary> /// デプス画像(512×424)上の座標 /// </summary> Vec2 depthSpacePos = Vec2::Zero; /// <summary> /// トラッキングの状態 /// </summary> TrackingState trackingState = TrackingState::NotTracked; }; /// <summary> /// Kinect v2 ボディ /// </summary> struct KinectV2Body { enum { /// <summary> /// 関節の個数 /// </summary> Num_Joints = 25 }; /// <summary> /// 関節 /// </summary> KinectV2Joint joints[Num_Joints]; /// <summary> /// 体の傾き /// </summary> Vec2 lean = Vec2::Zero; /// <summary> /// 左手の状態 /// </summary> HandState leftHand = HandState::Unknown; /// <summary> /// 右手の状態 /// </summary> HandState rightHand = HandState::Unknown; /// <summary> /// 左手の追跡が高信頼であるか /// </summary> bool leftHandHighConfidence = false; /// <summary> /// 右手の追跡が高信頼であるか /// </summary> bool rightHandHighConfidence = false; }; /// <summary> /// オーディオビーム /// </summary> struct KinectV2AudioBeam { /// <summary> /// オーディオの方向(ラジアン) /// </summary> double angle = 0.0; /// <summary> /// オーディオの方向の信頼性 [0.0, 1.0] /// </summary> double confidence = 0.0; }; /// <summary> /// Kinect v2 /// </summary> /// <remarks> /// Kinect v2 の機能を提供します。 /// </remarks> namespace KinectV2 { /// <summary> /// 深度を色に変換するデフォルトの関数です。 /// </summary> /// <param name="depth"> /// デプス [mm] /// </param> /// <returns> /// 変換後の色 /// </returns> inline Color DefaultDepthColoring(uint16 depth) { return depth != 0 ? HueToColor(depth / 4.0) : Palette::Black; } /// <summary> /// ボディインデックスを色に変換するデフォルトの関数です。 /// </summary> /// <param name="index"> /// ボディインデックス。何もない場合は 255 /// </param> /// <returns> /// 変換後の色 /// </returns> inline Color DefaultBodyIndexColoring(uint8 index) { return index != 255 ? HueToColor(index * 60) : Palette::Black; } /// <summary> /// 赤外線を色に変換するデフォルトの関数です。 /// </summary> /// <param name="infrared"> /// 赤外線 /// </param> /// <returns> /// 変換後の色 /// </returns> inline Color DefaultInfraredColoring(uint16 infrared) { return Color(infrared / 256); } /// <summary> /// Kinect v2 が使用可能かを取得します。 /// </summary> /// <returns> /// Kinect v2 が使用可能な場合 true, それ以外の場合は false /// </returns> bool IsAvailable(); /// <summary> /// Kinect v2 を起動します。 /// </summary> /// <param name="dataType"> /// Kinect v2 の設定、KinectV2DataType::Type の組み合わせ /// </param> /// <returns> /// 起動に成功した場合 true, それ以外の場合は false /// </returns> bool Start(int32 dataType = KinectV2DataType::Default); //////////////////////////////////////////////////////////////// // // カラー // //////////////////////////////////////////////////////////////// /// <summary> /// カラーフレームの撮影を開始 / 再開します。 /// </summary> /// <returns> /// カラーフレームの撮影開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StartColorFrame(); /// <summary> /// カラーフレームの撮影を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopColorFrame(); /// <summary> /// 新しいカラーフレームがあるかを取得します。 /// </summary> /// <returns> /// 新しいカラーフレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewColorFrame(); /// <summary> /// カラーフレームを取得します。 /// </summary> /// <param name="image"> /// カラーフレームのコピー先 /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetColorFrame(Image& image); /// <summary> /// カラーフレームを取得します。 /// </summary> /// <param name="texture"> /// カラーフレームのコピー先 /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetColorFrame(DynamicTexture& texture); //////////////////////////////////////////////////////////////// // // デプス // //////////////////////////////////////////////////////////////// /// <summary> /// デプスフレームの撮影を開始 / 再開します。 /// </summary> /// <returns> /// デプスフレームの撮影開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StartDepthFrame(); /// <summary> /// デプスフレームの撮影を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopDepthFrame(); /// <summary> /// 新しいデプスフレームがあるかを取得します。 /// </summary> /// <returns> /// 新しいデプスフレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewDepthFrame(); /// <summary> /// デプスデータにアクセスします。 /// </summary> /// <returns> /// デプスデータへの参照 /// </returns> const Grid<uint16>& GetRawDepthData(); /// <summary> /// デプスフレームを取得します。 /// </summary> /// <param name="image"> /// デプスフレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetDepthFrame(Image& image, std::function<Color(uint16)> coloring = DefaultDepthColoring); /// <summary> /// デプスフレームを取得します。 /// </summary> /// <param name="texture"> /// デプスフレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetDepthFrame(DynamicTexture& texture, std::function<Color(uint16)> coloring = DefaultDepthColoring); //////////////////////////////////////////////////////////////// // // ボディインデックス // //////////////////////////////////////////////////////////////// /// <summary> /// ボディインデックスの取得を開始 / 再開します。 /// </summary> /// <returns> /// ボディインデックスの取得開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StartBodyIndexFrame(); /// <summary> /// ボディインデックスの取得を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopBodyIndexFrame(); /// <summary> /// 新しいボディインデックスフレームがあるかを取得します。 /// </summary> /// <returns> /// 新しいボディインデックスフレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewBodyIndexFrame(); /// <summary> /// ボディインデックスデータにアクセスします。 /// </summary> /// <returns> /// ボディインデックスデータへの参照 /// </returns> const Grid<uint8>& GetRawBodyIndexData(); /// <summary> /// ボディインデックスフレームを取得します。 /// </summary> /// <param name="image"> /// ボディインデックスフレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetBodyIndexFrame(Image& image, std::function<Color(uint8)> coloring = DefaultBodyIndexColoring); /// <summary> /// ボディインデックスフレームを取得します。 /// </summary> /// <param name="texture"> /// ボディインデックスフレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetBodyIndexFrame(DynamicTexture& texture, std::function<Color(uint8)> coloring = DefaultBodyIndexColoring); //////////////////////////////////////////////////////////////// // // ボディ // //////////////////////////////////////////////////////////////// /// <summary> /// ボディの取得を開始 / 再開します。 /// </summary> /// <returns> /// ボディの取得開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StarBodyFrame(); /// <summary> /// ボディの取得を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopBodyFrame(); /// <summary> /// 新しいボディフレームがあるかを取得します。 /// </summary> /// <returns> /// 新しいボディフレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewBodyFrame(); /// <summary> /// ボディフレームを取得します。 /// </summary> /// <param name="bodies"> /// ボディフレームのコピー先 /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetBodyFrame(std::array<Optional<KinectV2Body>, 6>& bodies); //////////////////////////////////////////////////////////////// // // 赤外線 // //////////////////////////////////////////////////////////////// /// <summary> /// 赤外線の撮影を開始 / 再開します。 /// </summary> /// <returns> /// 赤外線の撮影開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StartInfraredFrame(); /// <summary> /// 赤外線の撮影を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopInfraredFrame(); /// <summary> /// 新しい赤外線フレームがあるかを取得します。 /// </summary> /// <returns> /// 新しい赤外線フレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewInfraredFrame(); /// <summary> /// 赤外線データにアクセスします。 /// </summary> /// <returns> /// 赤外線データへの参照 /// </returns> const Grid<uint16>& GetRawInfraredData(); /// <summary> /// 赤外線フレームを取得します。 /// </summary> /// <param name="image"> /// 赤外線フレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetInfraredFrame(Image& image, std::function<Color(uint16)> coloring = DefaultInfraredColoring); /// <summary> /// 赤外線フレームを取得します。 /// </summary> /// <param name="texture"> /// 赤外線フレームのコピー先 /// </param> /// <param name="coloring"> /// 色の変換ルール /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetInfraredFrame(DynamicTexture& texture, std::function<Color(uint16)> coloring = DefaultInfraredColoring); //////////////////////////////////////////////////////////////// // // オーディオビーム // //////////////////////////////////////////////////////////////// /// <summary> /// オーディオビームの取得を開始 / 再開します。 /// </summary> /// <returns> /// オーディオビームの取得開始 / 再開に成功した場合 true, それ以外の場合は false /// </returns> bool StarAudioBeamFrame(); /// <summary> /// オーディオビームの取得を停止します。 /// </summary> /// <returns> /// なし /// </returns> void StopAudioBeamFrame(); /// <summary> /// 新しいオーディオビームフレームがあるかを取得します。 /// </summary> /// <returns> /// 新しいオーディオビームフレームがある場合 true, それ以外の場合は false /// </returns> bool HasNewAudioBeamFrame(); /// <summary> /// オーディオビームフレームを取得します。 /// </summary> /// <param name="audioBeam"> /// オーディオビームフレームのコピー先 /// </param> /// <returns> /// 取得に成功した場合 true, それ以外の場合は false /// </returns> bool GetAudioBeamFrame(KinectV2AudioBeam& audioBeam); } }
#include "play_noughts_and_crosses.hpp" #include "joueur.hpp" #include "random.hpp" #include <iostream> #include <p6/p6.h> void play_noughts_and_crosses() { auto ctx = p6::Context{{720, 720, "Morpion Vert//Rouge"}}; float n = 3; Joueur J1; Joueur J2; J1.setSigne('x'); J2.setSigne('o'); Joueur current = J1; bool endGame = false; cellule tab[3][3]; tab[0][0].x = -1; tab[0][0].y = 1; tab[0][1].x = -1 + 2 * 0.33; tab[0][1].y = 1; tab[0][2].x = -1 + 4 * 0.33; tab[0][2].y = 1; tab[1][0].x = -1; tab[1][0].y = 0.33; tab[1][1].x = -1 + 2 * 0.33; tab[1][1].y = 0.33; tab[1][2].x = -1 + 4 * 0.33; tab[1][2].y = 0.33; tab[2][0].x = -1; tab[2][0].y = -0.33; tab[2][1].x = -1 + 2 * 0.33; tab[2][1].y = -0.33; tab[2][2].x = -1 + 4 * 0.33; tab[2][2].y = -0.33; ctx.background({1, 1, 1, 1}); const auto square_radius = 1 / n; std::cout << "Au tour du premier joueur !" << std::endl; while (endGame == false) { ctx.update = [&]() { ctx.mouse_pressed = [&](p6::MouseButton) { std::vector<double> posMouse; posMouse.push_back(ctx.mouse().x); posMouse.push_back(ctx.mouse().y); cellule cell_clicked = current.getPosition(posMouse, tab); switch (cell_clicked.signe) { case ('x'): ctx.fill = {1, 0, 0, 1}; ctx.square(p6::TopLeftCorner{(cell_clicked.x), (cell_clicked.y)}, p6::Radius{0.33f}); break; case ('o'): ctx.fill = {0, 1, 0, 1}; ctx.square(p6::TopLeftCorner{(cell_clicked.x), (cell_clicked.y)}, p6::Radius{0.33f}); break; }; if (current.testWinner(tab)) { endGame = true; std::cout << current.getSigne() << " a gagné ! Clique sur la croix." << std::endl; } else { if (current.getSigne() == 'x') { current = J2; std::cout << "Au tour de l'autre joueur !" << std::endl; } else { current = J1; std::cout << "Au tour de l'autre joueur !" << std::endl; } } }; }; for (float i = -(1.0f); i <= (1.0f); i = i + (2.0f / n)) { for (float j = -(1.0f); j <= (1.0f); j = j + (2.0f / n)) { ctx.use_fill = true; ctx.square(p6::TopLeftCorner{i, j}, p6::Radius{square_radius}); } } ctx.start(); } std::cout << " FIN DU JEU !" << std::endl; }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: requests.proto #include "requests.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_requests_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto; namespace communication { namespace request { class TokenLoginDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<TokenLogin> _instance; } _TokenLogin_default_instance_; class DirectoryVerification_ContentsEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DirectoryVerification_ContentsEntry_DoNotUse> _instance; } _DirectoryVerification_ContentsEntry_DoNotUse_default_instance_; class DirectoryVerificationDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DirectoryVerification> _instance; } _DirectoryVerification_default_instance_; class FileDiffDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FileDiff> _instance; } _FileDiff_default_instance_; } // namespace request } // namespace communication static void InitDefaultsTokenLogin_requests_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::communication::request::_TokenLogin_default_instance_; new (ptr) ::communication::request::TokenLogin(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::communication::request::TokenLogin::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_TokenLogin_requests_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTokenLogin_requests_2eproto}, {}}; static void InitDefaultsDirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::communication::request::_DirectoryVerification_ContentsEntry_DoNotUse_default_instance_; new (ptr) ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse(); } ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_DirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto}, {}}; static void InitDefaultsDirectoryVerification_requests_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::communication::request::_DirectoryVerification_default_instance_; new (ptr) ::communication::request::DirectoryVerification(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::communication::request::DirectoryVerification::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_DirectoryVerification_requests_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDirectoryVerification_requests_2eproto}, { &scc_info_DirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto.base,}}; static void InitDefaultsFileDiff_requests_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::communication::request::_FileDiff_default_instance_; new (ptr) ::communication::request::FileDiff(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::communication::request::FileDiff::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_FileDiff_requests_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFileDiff_requests_2eproto}, {}}; void InitDefaults_requests_2eproto() { ::google::protobuf::internal::InitSCC(&scc_info_TokenLogin_requests_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_DirectoryVerification_ContentsEntry_DoNotUse_requests_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_DirectoryVerification_requests_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_FileDiff_requests_2eproto.base); } ::google::protobuf::Metadata file_level_metadata_requests_2eproto[4]; constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_requests_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_requests_2eproto = nullptr; const ::google::protobuf::uint32 TableStruct_requests_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::communication::request::TokenLogin, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::communication::request::TokenLogin, token_), PROTOBUF_FIELD_OFFSET(::communication::request::TokenLogin, name_), PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification_ContentsEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification_ContentsEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification_ContentsEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification_ContentsEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification, root_name_), PROTOBUF_FIELD_OFFSET(::communication::request::DirectoryVerification, contents_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::communication::request::FileDiff, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::communication::request::FileDiff, relative_path_), PROTOBUF_FIELD_OFFSET(::communication::request::FileDiff, content_), PROTOBUF_FIELD_OFFSET(::communication::request::FileDiff, status_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::communication::request::TokenLogin)}, { 7, 14, sizeof(::communication::request::DirectoryVerification_ContentsEntry_DoNotUse)}, { 16, -1, sizeof(::communication::request::DirectoryVerification)}, { 23, -1, sizeof(::communication::request::FileDiff)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::communication::request::_TokenLogin_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::communication::request::_DirectoryVerification_ContentsEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::communication::request::_DirectoryVerification_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::communication::request::_FileDiff_default_instance_), }; ::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_requests_2eproto = { {}, AddDescriptors_requests_2eproto, "requests.proto", schemas, file_default_instances, TableStruct_requests_2eproto::offsets, file_level_metadata_requests_2eproto, 4, file_level_enum_descriptors_requests_2eproto, file_level_service_descriptors_requests_2eproto, }; const char descriptor_table_protodef_requests_2eproto[] = "\n\016requests.proto\022\025communication.request\"" ")\n\nTokenLogin\022\r\n\005token\030\001 \001(\t\022\014\n\004name\030\002 \001" "(\t\"\251\001\n\025DirectoryVerification\022\021\n\troot_nam" "e\030\001 \001(\t\022L\n\010contents\030\002 \003(\0132:.communicatio" "n.request.DirectoryVerification.Contents" "Entry\032/\n\rContentsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005v" "alue\030\002 \001(\t:\0028\001\"B\n\010FileDiff\022\025\n\rrelative_p" "ath\030\001 \001(\t\022\017\n\007content\030\002 \001(\t\022\016\n\006status\030\003 \001" "(\005b\006proto3" ; ::google::protobuf::internal::DescriptorTable descriptor_table_requests_2eproto = { false, InitDefaults_requests_2eproto, descriptor_table_protodef_requests_2eproto, "requests.proto", &assign_descriptors_table_requests_2eproto, 330, }; void AddDescriptors_requests_2eproto() { static constexpr ::google::protobuf::internal::InitFunc deps[1] = { }; ::google::protobuf::internal::AddDescriptors(&descriptor_table_requests_2eproto, deps, 0); } // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_requests_2eproto = []() { AddDescriptors_requests_2eproto(); return true; }(); namespace communication { namespace request { // =================================================================== void TokenLogin::InitAsDefaultInstance() { } class TokenLogin::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int TokenLogin::kTokenFieldNumber; const int TokenLogin::kNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 TokenLogin::TokenLogin() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:communication.request.TokenLogin) } TokenLogin::TokenLogin(const TokenLogin& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); token_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.token().size() > 0) { token_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.token_); } name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } // @@protoc_insertion_point(copy_constructor:communication.request.TokenLogin) } void TokenLogin::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_TokenLogin_requests_2eproto.base); token_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } TokenLogin::~TokenLogin() { // @@protoc_insertion_point(destructor:communication.request.TokenLogin) SharedDtor(); } void TokenLogin::SharedDtor() { token_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void TokenLogin::SetCachedSize(int size) const { _cached_size_.Set(size); } const TokenLogin& TokenLogin::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_TokenLogin_requests_2eproto.base); return *internal_default_instance(); } void TokenLogin::Clear() { // @@protoc_insertion_point(message_clear_start:communication.request.TokenLogin) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; token_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* TokenLogin::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<TokenLogin*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string token = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("communication.request.TokenLogin.token"); object = msg->mutable_token(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string name = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("communication.request.TokenLogin.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool TokenLogin::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:communication.request.TokenLogin) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string token = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_token())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->token().data(), static_cast<int>(this->token().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.TokenLogin.token")); } else { goto handle_unusual; } break; } // string name = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.TokenLogin.name")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:communication.request.TokenLogin) return true; failure: // @@protoc_insertion_point(parse_failure:communication.request.TokenLogin) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void TokenLogin::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:communication.request.TokenLogin) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string token = 1; if (this->token().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->token().data(), static_cast<int>(this->token().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.TokenLogin.token"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->token(), output); } // string name = 2; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.TokenLogin.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->name(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:communication.request.TokenLogin) } ::google::protobuf::uint8* TokenLogin::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:communication.request.TokenLogin) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string token = 1; if (this->token().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->token().data(), static_cast<int>(this->token().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.TokenLogin.token"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->token(), target); } // string name = 2; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.TokenLogin.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->name(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:communication.request.TokenLogin) return target; } size_t TokenLogin::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:communication.request.TokenLogin) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string token = 1; if (this->token().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->token()); } // string name = 2; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TokenLogin::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:communication.request.TokenLogin) GOOGLE_DCHECK_NE(&from, this); const TokenLogin* source = ::google::protobuf::DynamicCastToGenerated<TokenLogin>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:communication.request.TokenLogin) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:communication.request.TokenLogin) MergeFrom(*source); } } void TokenLogin::MergeFrom(const TokenLogin& from) { // @@protoc_insertion_point(class_specific_merge_from_start:communication.request.TokenLogin) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.token().size() > 0) { token_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.token_); } if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } } void TokenLogin::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:communication.request.TokenLogin) if (&from == this) return; Clear(); MergeFrom(from); } void TokenLogin::CopyFrom(const TokenLogin& from) { // @@protoc_insertion_point(class_specific_copy_from_start:communication.request.TokenLogin) if (&from == this) return; Clear(); MergeFrom(from); } bool TokenLogin::IsInitialized() const { return true; } void TokenLogin::Swap(TokenLogin* other) { if (other == this) return; InternalSwap(other); } void TokenLogin::InternalSwap(TokenLogin* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); token_.Swap(&other->token_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata TokenLogin::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_requests_2eproto); return ::file_level_metadata_requests_2eproto[kIndexInFileMessages]; } // =================================================================== DirectoryVerification_ContentsEntry_DoNotUse::DirectoryVerification_ContentsEntry_DoNotUse() {} DirectoryVerification_ContentsEntry_DoNotUse::DirectoryVerification_ContentsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void DirectoryVerification_ContentsEntry_DoNotUse::MergeFrom(const DirectoryVerification_ContentsEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata DirectoryVerification_ContentsEntry_DoNotUse::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_requests_2eproto); return ::file_level_metadata_requests_2eproto[1]; } void DirectoryVerification_ContentsEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DirectoryVerification_ContentsEntry_DoNotUse::_ParseMap(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { using MF = ::google::protobuf::internal::MapField< DirectoryVerification_ContentsEntry_DoNotUse, EntryKeyType, EntryValueType, kEntryKeyFieldType, kEntryValueFieldType, kEntryDefaultEnumValue>; auto mf = static_cast<MF*>(object); Parser<MF, ::google::protobuf::Map<EntryKeyType, EntryValueType>> parser(mf); #define DO_(x) if (!(x)) return false DO_(parser.ParseMap(begin, end)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.DirectoryVerification.ContentsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.DirectoryVerification.ContentsEntry.value")); #undef DO_ return true; } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER // =================================================================== void DirectoryVerification::InitAsDefaultInstance() { } class DirectoryVerification::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DirectoryVerification::kRootNameFieldNumber; const int DirectoryVerification::kContentsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DirectoryVerification::DirectoryVerification() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:communication.request.DirectoryVerification) } DirectoryVerification::DirectoryVerification(const DirectoryVerification& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); contents_.MergeFrom(from.contents_); root_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.root_name().size() > 0) { root_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_name_); } // @@protoc_insertion_point(copy_constructor:communication.request.DirectoryVerification) } void DirectoryVerification::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_DirectoryVerification_requests_2eproto.base); root_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } DirectoryVerification::~DirectoryVerification() { // @@protoc_insertion_point(destructor:communication.request.DirectoryVerification) SharedDtor(); } void DirectoryVerification::SharedDtor() { root_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void DirectoryVerification::SetCachedSize(int size) const { _cached_size_.Set(size); } const DirectoryVerification& DirectoryVerification::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_DirectoryVerification_requests_2eproto.base); return *internal_default_instance(); } void DirectoryVerification::Clear() { // @@protoc_insertion_point(message_clear_start:communication.request.DirectoryVerification) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; contents_.Clear(); root_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* DirectoryVerification::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<DirectoryVerification*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string root_name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("communication.request.DirectoryVerification.root_name"); object = msg->mutable_root_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // map<string, string> contents = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::SlowMapEntryParser; auto parse_map = ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse::_ParseMap; ctx->extra_parse_data().payload.clear(); ctx->extra_parse_data().parse_map = parse_map; object = &msg->contents_; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, object, ctx)); ptr = newend; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DirectoryVerification::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:communication.request.DirectoryVerification) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string root_name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_root_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->root_name().data(), static_cast<int>(this->root_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.DirectoryVerification.root_name")); } else { goto handle_unusual; } break; } // map<string, string> contents = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DirectoryVerification_ContentsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< DirectoryVerification_ContentsEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&contents_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.DirectoryVerification.ContentsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.DirectoryVerification.ContentsEntry.value")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:communication.request.DirectoryVerification) return true; failure: // @@protoc_insertion_point(parse_failure:communication.request.DirectoryVerification) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DirectoryVerification::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:communication.request.DirectoryVerification) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string root_name = 1; if (this->root_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->root_name().data(), static_cast<int>(this->root_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.root_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->root_name(), output); } // map<string, string> contents = 2; if (!this->contents().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.ContentsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.ContentsEntry.value"); } }; if (output->IsSerializationDeterministic() && this->contents().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->contents().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->contents().begin(); it != this->contents().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<DirectoryVerification_ContentsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(contents_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(2, *entry, output); Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)])); } } else { ::std::unique_ptr<DirectoryVerification_ContentsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->contents().begin(); it != this->contents().end(); ++it) { entry.reset(contents_.NewEntryWrapper(it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(2, *entry, output); Utf8Check::Check(&(*it)); } } } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:communication.request.DirectoryVerification) } ::google::protobuf::uint8* DirectoryVerification::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:communication.request.DirectoryVerification) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string root_name = 1; if (this->root_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->root_name().data(), static_cast<int>(this->root_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.root_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->root_name(), target); } // map<string, string> contents = 2; if (!this->contents().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.ContentsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.DirectoryVerification.ContentsEntry.value"); } }; if (false && this->contents().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->contents().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->contents().begin(); it != this->contents().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<DirectoryVerification_ContentsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(contents_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(2, *entry, target); Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)])); } } else { ::std::unique_ptr<DirectoryVerification_ContentsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->contents().begin(); it != this->contents().end(); ++it) { entry.reset(contents_.NewEntryWrapper(it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(2, *entry, target); Utf8Check::Check(&(*it)); } } } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:communication.request.DirectoryVerification) return target; } size_t DirectoryVerification::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:communication.request.DirectoryVerification) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // map<string, string> contents = 2; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->contents_size()); { ::std::unique_ptr<DirectoryVerification_ContentsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->contents().begin(); it != this->contents().end(); ++it) { entry.reset(contents_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } // string root_name = 1; if (this->root_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->root_name()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DirectoryVerification::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:communication.request.DirectoryVerification) GOOGLE_DCHECK_NE(&from, this); const DirectoryVerification* source = ::google::protobuf::DynamicCastToGenerated<DirectoryVerification>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:communication.request.DirectoryVerification) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:communication.request.DirectoryVerification) MergeFrom(*source); } } void DirectoryVerification::MergeFrom(const DirectoryVerification& from) { // @@protoc_insertion_point(class_specific_merge_from_start:communication.request.DirectoryVerification) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; contents_.MergeFrom(from.contents_); if (from.root_name().size() > 0) { root_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_name_); } } void DirectoryVerification::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:communication.request.DirectoryVerification) if (&from == this) return; Clear(); MergeFrom(from); } void DirectoryVerification::CopyFrom(const DirectoryVerification& from) { // @@protoc_insertion_point(class_specific_copy_from_start:communication.request.DirectoryVerification) if (&from == this) return; Clear(); MergeFrom(from); } bool DirectoryVerification::IsInitialized() const { return true; } void DirectoryVerification::Swap(DirectoryVerification* other) { if (other == this) return; InternalSwap(other); } void DirectoryVerification::InternalSwap(DirectoryVerification* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); contents_.Swap(&other->contents_); root_name_.Swap(&other->root_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata DirectoryVerification::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_requests_2eproto); return ::file_level_metadata_requests_2eproto[kIndexInFileMessages]; } // =================================================================== void FileDiff::InitAsDefaultInstance() { } class FileDiff::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FileDiff::kRelativePathFieldNumber; const int FileDiff::kContentFieldNumber; const int FileDiff::kStatusFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FileDiff::FileDiff() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:communication.request.FileDiff) } FileDiff::FileDiff(const FileDiff& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); relative_path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.relative_path().size() > 0) { relative_path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.relative_path_); } content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.content().size() > 0) { content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); } status_ = from.status_; // @@protoc_insertion_point(copy_constructor:communication.request.FileDiff) } void FileDiff::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_FileDiff_requests_2eproto.base); relative_path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); status_ = 0; } FileDiff::~FileDiff() { // @@protoc_insertion_point(destructor:communication.request.FileDiff) SharedDtor(); } void FileDiff::SharedDtor() { relative_path_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void FileDiff::SetCachedSize(int size) const { _cached_size_.Set(size); } const FileDiff& FileDiff::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_FileDiff_requests_2eproto.base); return *internal_default_instance(); } void FileDiff::Clear() { // @@protoc_insertion_point(message_clear_start:communication.request.FileDiff) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; relative_path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); status_ = 0; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* FileDiff::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<FileDiff*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string relative_path = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("communication.request.FileDiff.relative_path"); object = msg->mutable_relative_path(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string content = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("communication.request.FileDiff.content"); object = msg->mutable_content(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // int32 status = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; msg->set_status(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileDiff::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:communication.request.FileDiff) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string relative_path = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_relative_path())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->relative_path().data(), static_cast<int>(this->relative_path().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.FileDiff.relative_path")); } else { goto handle_unusual; } break; } // string content = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_content())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content().data(), static_cast<int>(this->content().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "communication.request.FileDiff.content")); } else { goto handle_unusual; } break; } // int32 status = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &status_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:communication.request.FileDiff) return true; failure: // @@protoc_insertion_point(parse_failure:communication.request.FileDiff) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FileDiff::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:communication.request.FileDiff) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string relative_path = 1; if (this->relative_path().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->relative_path().data(), static_cast<int>(this->relative_path().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.FileDiff.relative_path"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->relative_path(), output); } // string content = 2; if (this->content().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content().data(), static_cast<int>(this->content().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.FileDiff.content"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->content(), output); } // int32 status = 3; if (this->status() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->status(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:communication.request.FileDiff) } ::google::protobuf::uint8* FileDiff::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:communication.request.FileDiff) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string relative_path = 1; if (this->relative_path().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->relative_path().data(), static_cast<int>(this->relative_path().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.FileDiff.relative_path"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->relative_path(), target); } // string content = 2; if (this->content().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content().data(), static_cast<int>(this->content().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "communication.request.FileDiff.content"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->content(), target); } // int32 status = 3; if (this->status() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->status(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:communication.request.FileDiff) return target; } size_t FileDiff::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:communication.request.FileDiff) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string relative_path = 1; if (this->relative_path().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->relative_path()); } // string content = 2; if (this->content().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->content()); } // int32 status = 3; if (this->status() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->status()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void FileDiff::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:communication.request.FileDiff) GOOGLE_DCHECK_NE(&from, this); const FileDiff* source = ::google::protobuf::DynamicCastToGenerated<FileDiff>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:communication.request.FileDiff) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:communication.request.FileDiff) MergeFrom(*source); } } void FileDiff::MergeFrom(const FileDiff& from) { // @@protoc_insertion_point(class_specific_merge_from_start:communication.request.FileDiff) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.relative_path().size() > 0) { relative_path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.relative_path_); } if (from.content().size() > 0) { content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); } if (from.status() != 0) { set_status(from.status()); } } void FileDiff::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:communication.request.FileDiff) if (&from == this) return; Clear(); MergeFrom(from); } void FileDiff::CopyFrom(const FileDiff& from) { // @@protoc_insertion_point(class_specific_copy_from_start:communication.request.FileDiff) if (&from == this) return; Clear(); MergeFrom(from); } bool FileDiff::IsInitialized() const { return true; } void FileDiff::Swap(FileDiff* other) { if (other == this) return; InternalSwap(other); } void FileDiff::InternalSwap(FileDiff* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); relative_path_.Swap(&other->relative_path_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(status_, other->status_); } ::google::protobuf::Metadata FileDiff::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_requests_2eproto); return ::file_level_metadata_requests_2eproto[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace request } // namespace communication namespace google { namespace protobuf { template<> PROTOBUF_NOINLINE ::communication::request::TokenLogin* Arena::CreateMaybeMessage< ::communication::request::TokenLogin >(Arena* arena) { return Arena::CreateInternal< ::communication::request::TokenLogin >(arena); } template<> PROTOBUF_NOINLINE ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse* Arena::CreateMaybeMessage< ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::communication::request::DirectoryVerification_ContentsEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::communication::request::DirectoryVerification* Arena::CreateMaybeMessage< ::communication::request::DirectoryVerification >(Arena* arena) { return Arena::CreateInternal< ::communication::request::DirectoryVerification >(arena); } template<> PROTOBUF_NOINLINE ::communication::request::FileDiff* Arena::CreateMaybeMessage< ::communication::request::FileDiff >(Arena* arena) { return Arena::CreateInternal< ::communication::request::FileDiff >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
/* * Copyright 2001-2018 Adrian Thurston <thurston@colm.net> * * 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 "inputdata.h" #include "nragel.h" extern struct colm_sections rlparseJava; extern struct colm_sections rlhcJava; /* * Java */ const char *defaultOutFnJava( const char *inputFileName ) { return fileNameFromStem( inputFileName, ".java" ); } HostType hostTypesJava[] = { { "byte", 0, "byte", true, true, false, SCHAR_MIN, SCHAR_MAX, 0, 0, 1 }, { "short", 0, "short", true, true, false, SHRT_MIN, SHRT_MAX, 0, 0, 2 }, { "char", 0, "char", false, true, false, 0, 0, 0, USHRT_MAX, 2 }, { "int", 0, "int", true, true, false, INT_MIN, INT_MAX, 0, 0, 4 }, }; const HostLang hostLangJava = { hostTypesJava, 4, 2, false, true, /* loopLabels */ Translated, BreakFeature, &makeCodeGen, &defaultOutFnJava, &genLineDirectiveTrans }; int main( int argc, const char **argv ) { InputData id( &hostLangJava, &rlparseJava, &rlhcJava ); return id.rlhcMain( argc, argv ); }
#include "mbed.h" #include "stepper.hpp" ///*** PROGRAMME DE TEST ***/// //** Using MBED OS 5 **// /* TARGET : F767ZI */ DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); Ticker blink; InterruptIn bp(USER_BUTTON); Stepper stepper1(PA_3,PC_0); void blink_led(void) { led2=!led2; stepper1.kill(); } int main() { bp.rise(blink_led); stepper1.move(400); stepper1.move(800); bool moved(false); int new_acc(0); int new_step(0); int new_dir(0); int new_vit(0); while(1) { led3=!led3; if(!stepper1.is_running()&&!moved){stepper1.move(-400);moved=true;} if(!stepper1.is_running()) { printf("%c\033[2Jnouvelle commande stepper 1 : \n acc : ",7); scanf("%d",&new_acc); stepper1.set_accel(new_acc); printf("\nvitesse : "); scanf("%d",&new_vit); stepper1.set_rpm(new_vit); printf("\nmouvement : "); scanf("%d",&new_step); printf("\ndirection : "); scanf("%d",&new_dir); if(new_dir)stepper1.move(new_step); else stepper1.move(-new_step); printf("lancement ...\n"); } wait_ms(200); } }
// This file is auto-generated. Do not edit! #include "precomp.hpp" #include "cvconfig.h" #include "opencl_kernels_video.hpp" #ifdef HAVE_OPENCL namespace cv { namespace ocl { namespace video { static const char* const moduleName = "video"; struct cv::ocl::internal::ProgramEntry bgfg_knn_oclsrc={moduleName, "bgfg_knn", "#if CN==1\n" "#define T_MEAN float\n" "#define F_ZERO (0.0f)\n" "#define frameToMean(a, b) (b) = *(a);\n" "#define meanToFrame(a, b) *b = convert_uchar_sat(a);\n" "#else\n" "#define T_MEAN float4\n" "#define F_ZERO (0.0f, 0.0f, 0.0f, 0.0f)\n" "#define meanToFrame(a, b)\\\n" "b[0] = convert_uchar_sat(a.x); \\\n" "b[1] = convert_uchar_sat(a.y); \\\n" "b[2] = convert_uchar_sat(a.z);\n" "#define frameToMean(a, b)\\\n" "b.x = a[0]; \\\n" "b.y = a[1]; \\\n" "b.z = a[2]; \\\n" "b.w = 0.0f;\n" "#endif\n" "__kernel void knn_kernel(__global const uchar* frame, int frame_step, int frame_offset, int frame_row, int frame_col,\n" "__global const uchar* nNextLongUpdate,\n" "__global const uchar* nNextMidUpdate,\n" "__global const uchar* nNextShortUpdate,\n" "__global uchar* aModelIndexLong,\n" "__global uchar* aModelIndexMid,\n" "__global uchar* aModelIndexShort,\n" "__global uchar* flag,\n" "__global uchar* sample,\n" "__global uchar* fgmask, int fgmask_step, int fgmask_offset,\n" "int nLongCounter, int nMidCounter, int nShortCounter,\n" "float c_Tb, int c_nkNN, float c_tau\n" "#ifdef SHADOW_DETECT\n" ", uchar c_shadowVal\n" "#endif\n" ")\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if( x < frame_col && y < frame_row)\n" "{\n" "__global const uchar* _frame = (frame + mad24(y, frame_step, mad24(x, CN, frame_offset)));\n" "T_MEAN pix;\n" "frameToMean(_frame, pix);\n" "uchar foreground = 255;\n" "int Pbf = 0;\n" "int Pb = 0;\n" "uchar include = 0;\n" "int pt_idx = mad24(y, frame_col, x);\n" "int idx_step = frame_row * frame_col;\n" "__global T_MEAN* _sample = (__global T_MEAN*)(sample);\n" "for (uchar n = 0; n < (NSAMPLES) * 3 ; ++n)\n" "{\n" "int n_idx = mad24(n, idx_step, pt_idx);\n" "T_MEAN c_mean = _sample[n_idx];\n" "uchar c_flag = flag[n_idx];\n" "T_MEAN diff = c_mean - pix;\n" "float dist2 = dot(diff, diff);\n" "if (dist2 < c_Tb)\n" "{\n" "Pbf++;\n" "if (c_flag)\n" "{\n" "Pb++;\n" "if (Pb >= c_nkNN)\n" "{\n" "include = 1;\n" "foreground = 0;\n" "break;\n" "}\n" "}\n" "}\n" "}\n" "if (Pbf >= c_nkNN)\n" "{\n" "include = 1;\n" "}\n" "#ifdef SHADOW_DETECT\n" "if (foreground)\n" "{\n" "int Ps = 0;\n" "for (uchar n = 0; n < (NSAMPLES) * 3 ; ++n)\n" "{\n" "int n_idx = mad24(n, idx_step, pt_idx);\n" "uchar c_flag = flag[n_idx];\n" "if (c_flag)\n" "{\n" "T_MEAN c_mean = _sample[n_idx];\n" "float numerator = dot(pix, c_mean);\n" "float denominator = dot(c_mean, c_mean);\n" "if (denominator == 0)\n" "break;\n" "if (numerator <= denominator && numerator >= c_tau * denominator)\n" "{\n" "float a = numerator / denominator;\n" "T_MEAN dD = mad(a, c_mean, -pix);\n" "if (dot(dD, dD) < c_Tb * a * a)\n" "{\n" "Ps++;\n" "if (Ps >= c_nkNN)\n" "{\n" "foreground = c_shadowVal;\n" "break;\n" "}\n" "}\n" "}\n" "}\n" "}\n" "}\n" "#endif\n" "__global uchar* _fgmask = fgmask + mad24(y, fgmask_step, x + fgmask_offset);\n" "*_fgmask = (uchar)foreground;\n" "__global const uchar* _nNextLongUpdate = nNextLongUpdate + pt_idx;\n" "__global const uchar* _nNextMidUpdate = nNextMidUpdate + pt_idx;\n" "__global const uchar* _nNextShortUpdate = nNextShortUpdate + pt_idx;\n" "__global uchar* _aModelIndexLong = aModelIndexLong + pt_idx;\n" "__global uchar* _aModelIndexMid = aModelIndexMid + pt_idx;\n" "__global uchar* _aModelIndexShort = aModelIndexShort + pt_idx;\n" "uchar nextLongUpdate = _nNextLongUpdate[0];\n" "uchar nextMidUpdate = _nNextMidUpdate[0];\n" "uchar nextShortUpdate = _nNextShortUpdate[0];\n" "uchar modelIndexLong = _aModelIndexLong[0];\n" "uchar modelIndexMid = _aModelIndexMid[0];\n" "uchar modelIndexShort = _aModelIndexShort[0];\n" "int offsetLong = mad24(mad24(2, (NSAMPLES), modelIndexLong), idx_step, pt_idx);\n" "int offsetMid = mad24((NSAMPLES)+modelIndexMid, idx_step, pt_idx);\n" "int offsetShort = mad24(modelIndexShort, idx_step, pt_idx);\n" "if (nextLongUpdate == nLongCounter)\n" "{\n" "_sample[offsetLong] = _sample[offsetMid];\n" "flag[offsetLong] = flag[offsetMid];\n" "_aModelIndexLong[0] = (modelIndexLong >= ((NSAMPLES)-1)) ? 0 : (modelIndexLong + 1);\n" "}\n" "if (nextMidUpdate == nMidCounter)\n" "{\n" "_sample[offsetMid] = _sample[offsetShort];\n" "flag[offsetMid] = flag[offsetShort];\n" "_aModelIndexMid[0] = (modelIndexMid >= ((NSAMPLES)-1)) ? 0 : (modelIndexMid + 1);\n" "}\n" "if (nextShortUpdate == nShortCounter)\n" "{\n" "_sample[offsetShort] = pix;\n" "flag[offsetShort] = include;\n" "_aModelIndexShort[0] = (modelIndexShort >= ((NSAMPLES)-1)) ? 0 : (modelIndexShort + 1);\n" "}\n" "}\n" "}\n" "__kernel void getBackgroundImage2_kernel(__global const uchar* flag,\n" "__global const uchar* sample,\n" "__global uchar* dst, int dst_step, int dst_offset, int dst_row, int dst_col)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < dst_col && y < dst_row)\n" "{\n" "int pt_idx = mad24(y, dst_col, x);\n" "T_MEAN meanVal = (T_MEAN)F_ZERO;\n" "__global T_MEAN* _sample = (__global T_MEAN*)(sample);\n" "int idx_step = dst_row * dst_col;\n" "for (uchar n = 0; n < (NSAMPLES) * 3 ; ++n)\n" "{\n" "int n_idx = mad24(n, idx_step, pt_idx);\n" "uchar c_flag = flag[n_idx];\n" "if(c_flag)\n" "{\n" "meanVal = _sample[n_idx];\n" "break;\n" "}\n" "}\n" "__global uchar* _dst = dst + mad24(y, dst_step, mad24(x, CN, dst_offset));\n" "meanToFrame(meanVal, _dst);\n" "}\n" "}\n" , "a192721ae727b25afde8d854a0679ee4", NULL}; struct cv::ocl::internal::ProgramEntry bgfg_mog2_oclsrc={moduleName, "bgfg_mog2", "#if CN==1\n" "#define T_MEAN float\n" "#define F_ZERO (0.0f)\n" "#define cnMode 1\n" "#define frameToMean(a, b) (b) = *(a);\n" "#if FL==0\n" "#define meanToFrame(a, b) *b = convert_uchar_sat(a);\n" "#else\n" "#define meanToFrame(a, b) *b = (float)a;\n" "#endif\n" "#else\n" "#define T_MEAN float4\n" "#define F_ZERO (0.0f, 0.0f, 0.0f, 0.0f)\n" "#define cnMode 4\n" "#if FL == 0\n" "#define meanToFrame(a, b)\\\n" "b[0] = convert_uchar_sat(a.x); \\\n" "b[1] = convert_uchar_sat(a.y); \\\n" "b[2] = convert_uchar_sat(a.z);\n" "#else\n" "#define meanToFrame(a, b)\\\n" "b[0] = a.x; \\\n" "b[1] = a.y; \\\n" "b[2] = a.z;\n" "#endif\n" "#define frameToMean(a, b)\\\n" "b.x = a[0]; \\\n" "b.y = a[1]; \\\n" "b.z = a[2]; \\\n" "b.w = 0.0f;\n" "#endif\n" "__kernel void mog2_kernel(__global const uchar* frame, int frame_step, int frame_offset, int frame_row, int frame_col,\n" "__global uchar* modesUsed,\n" "__global uchar* weight,\n" "__global uchar* mean,\n" "__global uchar* variance,\n" "__global uchar* fgmask, int fgmask_step, int fgmask_offset,\n" "float alphaT, float alpha1, float prune,\n" "float c_Tb, float c_TB, float c_Tg, float c_varMin,\n" "float c_varMax, float c_varInit, float c_tau\n" "#ifdef SHADOW_DETECT\n" ", uchar c_shadowVal\n" "#endif\n" ")\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if( x < frame_col && y < frame_row)\n" "{\n" "#if FL==0\n" "__global const uchar* _frame = (frame + mad24(y, frame_step, mad24(x, CN, frame_offset)));\n" "#else\n" "__global const float* _frame = ((__global const float*)( frame + mad24(y, frame_step, frame_offset)) + mad24(x, CN, 0));\n" "#endif\n" "T_MEAN pix;\n" "frameToMean(_frame, pix);\n" "uchar foreground = 255;\n" "bool fitsPDF = false;\n" "int pt_idx = mad24(y, frame_col, x);\n" "int idx_step = frame_row * frame_col;\n" "__global uchar* _modesUsed = modesUsed + pt_idx;\n" "uchar nmodes = _modesUsed[0];\n" "float totalWeight = 0.0f;\n" "__global float* _weight = (__global float*)(weight);\n" "__global float* _variance = (__global float*)(variance);\n" "__global T_MEAN* _mean = (__global T_MEAN*)(mean);\n" "uchar mode = 0;\n" "for (; mode < nmodes; ++mode)\n" "{\n" "int mode_idx = mad24(mode, idx_step, pt_idx);\n" "float c_weight = mad(alpha1, _weight[mode_idx], prune);\n" "float c_var = _variance[mode_idx];\n" "T_MEAN c_mean = _mean[mode_idx];\n" "T_MEAN diff = c_mean - pix;\n" "float dist2 = dot(diff, diff);\n" "if (totalWeight < c_TB && dist2 < c_Tb * c_var)\n" "foreground = 0;\n" "if (dist2 < c_Tg * c_var)\n" "{\n" "fitsPDF = true;\n" "c_weight += alphaT;\n" "float k = alphaT / c_weight;\n" "T_MEAN mean_new = mad((T_MEAN)-k, diff, c_mean);\n" "float variance_new = clamp(mad(k, (dist2 - c_var), c_var), c_varMin, c_varMax);\n" "for (int i = mode; i > 0; --i)\n" "{\n" "int prev_idx = mode_idx - idx_step;\n" "if (c_weight < _weight[prev_idx])\n" "break;\n" "_weight[mode_idx] = _weight[prev_idx];\n" "_variance[mode_idx] = _variance[prev_idx];\n" "_mean[mode_idx] = _mean[prev_idx];\n" "mode_idx = prev_idx;\n" "}\n" "_mean[mode_idx] = mean_new;\n" "_variance[mode_idx] = variance_new;\n" "_weight[mode_idx] = c_weight;\n" "totalWeight += c_weight;\n" "mode ++;\n" "break;\n" "}\n" "if (c_weight < -prune)\n" "c_weight = 0.0f;\n" "_weight[mode_idx] = c_weight;\n" "totalWeight += c_weight;\n" "}\n" "for (; mode < nmodes; ++mode)\n" "{\n" "int mode_idx = mad24(mode, idx_step, pt_idx);\n" "float c_weight = mad(alpha1, _weight[mode_idx], prune);\n" "if (c_weight < -prune)\n" "{\n" "c_weight = 0.0f;\n" "nmodes = mode;\n" "break;\n" "}\n" "_weight[mode_idx] = c_weight;\n" "totalWeight += c_weight;\n" "}\n" "if (0.f < totalWeight)\n" "{\n" "totalWeight = 1.f / totalWeight;\n" "for (int mode = 0; mode < nmodes; ++mode)\n" "_weight[mad24(mode, idx_step, pt_idx)] *= totalWeight;\n" "}\n" "if (!fitsPDF)\n" "{\n" "uchar mode = nmodes == (NMIXTURES) ? (NMIXTURES) - 1 : nmodes++;\n" "int mode_idx = mad24(mode, idx_step, pt_idx);\n" "if (nmodes == 1)\n" "_weight[mode_idx] = 1.f;\n" "else\n" "{\n" "_weight[mode_idx] = alphaT;\n" "for (int i = pt_idx; i < mode_idx; i += idx_step)\n" "_weight[i] *= alpha1;\n" "}\n" "for (int i = nmodes - 1; i > 0; --i)\n" "{\n" "int prev_idx = mode_idx - idx_step;\n" "if (alphaT < _weight[prev_idx])\n" "break;\n" "_weight[mode_idx] = _weight[prev_idx];\n" "_variance[mode_idx] = _variance[prev_idx];\n" "_mean[mode_idx] = _mean[prev_idx];\n" "mode_idx = prev_idx;\n" "}\n" "_mean[mode_idx] = pix;\n" "_variance[mode_idx] = c_varInit;\n" "}\n" "_modesUsed[0] = nmodes;\n" "#ifdef SHADOW_DETECT\n" "if (foreground)\n" "{\n" "float tWeight = 0.0f;\n" "for (uchar mode = 0; mode < nmodes; ++mode)\n" "{\n" "int mode_idx = mad24(mode, idx_step, pt_idx);\n" "T_MEAN c_mean = _mean[mode_idx];\n" "float numerator = dot(pix, c_mean);\n" "float denominator = dot(c_mean, c_mean);\n" "if (denominator == 0)\n" "break;\n" "if (numerator <= denominator && numerator >= c_tau * denominator)\n" "{\n" "float a = numerator / denominator;\n" "T_MEAN dD = mad(a, c_mean, -pix);\n" "if (dot(dD, dD) < c_Tb * _variance[mode_idx] * a * a)\n" "{\n" "foreground = c_shadowVal;\n" "break;\n" "}\n" "}\n" "tWeight += _weight[mode_idx];\n" "if (tWeight > c_TB)\n" "break;\n" "}\n" "}\n" "#endif\n" "__global uchar* _fgmask = fgmask + mad24(y, fgmask_step, x + fgmask_offset);\n" "*_fgmask = (uchar)foreground;\n" "}\n" "}\n" "__kernel void getBackgroundImage2_kernel(__global const uchar* modesUsed,\n" "__global const uchar* weight,\n" "__global const uchar* mean,\n" "__global uchar* dst, int dst_step, int dst_offset, int dst_row, int dst_col,\n" "float c_TB)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < dst_col && y < dst_row)\n" "{\n" "int pt_idx = mad24(y, dst_col, x);\n" "__global const uchar* _modesUsed = modesUsed + pt_idx;\n" "uchar nmodes = _modesUsed[0];\n" "T_MEAN meanVal = (T_MEAN)F_ZERO;\n" "float totalWeight = 0.0f;\n" "__global const float* _weight = (__global const float*)weight;\n" "__global const T_MEAN* _mean = (__global const T_MEAN*)(mean);\n" "int idx_step = dst_row * dst_col;\n" "for (uchar mode = 0; mode < nmodes; ++mode)\n" "{\n" "int mode_idx = mad24(mode, idx_step, pt_idx);\n" "float c_weight = _weight[mode_idx];\n" "T_MEAN c_mean = _mean[mode_idx];\n" "meanVal = mad(c_weight, c_mean, meanVal);\n" "totalWeight += c_weight;\n" "if (totalWeight > c_TB)\n" "break;\n" "}\n" "if (0.f < totalWeight)\n" "meanVal = meanVal / totalWeight;\n" "else\n" "meanVal = (T_MEAN)(0.f);\n" "#if FL==0\n" "__global uchar* _dst = dst + mad24(y, dst_step, mad24(x, CN, dst_offset));\n" "meanToFrame(meanVal, _dst);\n" "#else\n" "__global float* _dst = ((__global float*)( dst + mad24(y, dst_step, dst_offset)) + mad24(x, CN, 0));\n" "meanToFrame(meanVal, _dst);\n" "#endif\n" "}\n" "}\n" , "39b7e7b52e8eb53029cf2337ae3d904f", NULL}; struct cv::ocl::internal::ProgramEntry optical_flow_farneback_oclsrc={moduleName, "optical_flow_farneback", "#define tx (int)get_local_id(0)\n" "#define ty get_local_id(1)\n" "#define bx get_group_id(0)\n" "#define bdx (int)get_local_size(0)\n" "#define BORDER_SIZE 5\n" "#define MAX_KSIZE_HALF 100\n" "#ifndef polyN\n" "#define polyN 5\n" "#endif\n" "#if USE_DOUBLE\n" "#ifdef cl_amd_fp64\n" "#pragma OPENCL EXTENSION cl_amd_fp64:enable\n" "#elif defined (cl_khr_fp64)\n" "#pragma OPENCL EXTENSION cl_khr_fp64:enable\n" "#endif\n" "#define TYPE double\n" "#define VECTYPE double4\n" "#else\n" "#define TYPE float\n" "#define VECTYPE float4\n" "#endif\n" "__kernel void polynomialExpansion(__global __const float * src, int srcStep,\n" "__global float * dst, int dstStep,\n" "const int rows, const int cols,\n" "__global __const float * c_g,\n" "__global __const float * c_xg,\n" "__global __const float * c_xxg,\n" "__local float * smem,\n" "const VECTYPE ig)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = bx * (bdx - 2*polyN) + tx - polyN;\n" "int xWarped;\n" "__local float *row = smem + tx;\n" "if (y < rows && y >= 0)\n" "{\n" "xWarped = min(max(x, 0), cols - 1);\n" "row[0] = src[mad24(y, srcStep, xWarped)] * c_g[0];\n" "row[bdx] = 0.f;\n" "row[2*bdx] = 0.f;\n" "#pragma unroll\n" "for (int k = 1; k <= polyN; ++k)\n" "{\n" "float t0 = src[mad24(max(y - k, 0), srcStep, xWarped)];\n" "float t1 = src[mad24(min(y + k, rows - 1), srcStep, xWarped)];\n" "row[0] += c_g[k] * (t0 + t1);\n" "row[bdx] += c_xg[k] * (t1 - t0);\n" "row[2*bdx] += c_xxg[k] * (t0 + t1);\n" "}\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (y < rows && y >= 0 && tx >= polyN && tx + polyN < bdx && x < cols)\n" "{\n" "TYPE b1 = c_g[0] * row[0];\n" "TYPE b3 = c_g[0] * row[bdx];\n" "TYPE b5 = c_g[0] * row[2*bdx];\n" "TYPE b2 = 0, b4 = 0, b6 = 0;\n" "#pragma unroll\n" "for (int k = 1; k <= polyN; ++k)\n" "{\n" "b1 += (row[k] + row[-k]) * c_g[k];\n" "b4 += (row[k] + row[-k]) * c_xxg[k];\n" "b2 += (row[k] - row[-k]) * c_xg[k];\n" "b3 += (row[k + bdx] + row[-k + bdx]) * c_g[k];\n" "b6 += (row[k + bdx] - row[-k + bdx]) * c_xg[k];\n" "b5 += (row[k + 2*bdx] + row[-k + 2*bdx]) * c_g[k];\n" "}\n" "dst[mad24(y, dstStep, xWarped)] = (float)(b3*ig.s0);\n" "dst[mad24(rows + y, dstStep, xWarped)] = (float)(b2*ig.s0);\n" "dst[mad24(2*rows + y, dstStep, xWarped)] = (float)(b1*ig.s1 + b5*ig.s2);\n" "dst[mad24(3*rows + y, dstStep, xWarped)] = (float)(b1*ig.s1 + b4*ig.s2);\n" "dst[mad24(4*rows + y, dstStep, xWarped)] = (float)(b6*ig.s3);\n" "}\n" "}\n" "inline int idx_row_low(const int y, const int last_row)\n" "{\n" "return abs(y) % (last_row + 1);\n" "}\n" "inline int idx_row_high(const int y, const int last_row)\n" "{\n" "return abs(last_row - abs(last_row - y)) % (last_row + 1);\n" "}\n" "inline int idx_col_low(const int x, const int last_col)\n" "{\n" "return abs(x) % (last_col + 1);\n" "}\n" "inline int idx_col_high(const int x, const int last_col)\n" "{\n" "return abs(last_col - abs(last_col - x)) % (last_col + 1);\n" "}\n" "inline int idx_col(const int x, const int last_col)\n" "{\n" "return idx_col_low(idx_col_high(x, last_col), last_col);\n" "}\n" "__kernel void gaussianBlur(__global const float * src, int srcStep,\n" "__global float * dst, int dstStep, const int rows, const int cols,\n" "__global const float * c_gKer, const int ksizeHalf,\n" "__local float * smem)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = get_global_id(0);\n" "__local float *row = smem + ty * (bdx + 2*ksizeHalf);\n" "if (y < rows)\n" "{\n" "for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)\n" "{\n" "int xExt = (int)(bx * bdx) + i - ksizeHalf;\n" "xExt = idx_col(xExt, cols - 1);\n" "row[i] = src[mad24(y, srcStep, xExt)] * c_gKer[0];\n" "for (int j = 1; j <= ksizeHalf; ++j)\n" "row[i] += (src[mad24(idx_row_low(y - j, rows - 1), srcStep, xExt)]\n" "+ src[mad24(idx_row_high(y + j, rows - 1), srcStep, xExt)]) * c_gKer[j];\n" "}\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (y < rows && y >= 0 && x < cols && x >= 0)\n" "{\n" "row += tx + ksizeHalf;\n" "float res = row[0] * c_gKer[0];\n" "for (int i = 1; i <= ksizeHalf; ++i)\n" "res += (row[-i] + row[i]) * c_gKer[i];\n" "dst[mad24(y, dstStep, x)] = res;\n" "}\n" "}\n" "__kernel void gaussianBlur5(__global const float * src, int srcStep,\n" "__global float * dst, int dstStep,\n" "const int rows, const int cols,\n" "__global const float * c_gKer, const int ksizeHalf,\n" "__local float * smem)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = get_global_id(0);\n" "const int smw = bdx + 2*ksizeHalf;\n" "__local volatile float *row = smem + 5 * ty * smw;\n" "if (y < rows)\n" "{\n" "for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)\n" "{\n" "int xExt = (int)(bx * bdx) + i - ksizeHalf;\n" "xExt = idx_col(xExt, cols - 1);\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "row[k*smw + i] = src[mad24(k*rows + y, srcStep, xExt)] * c_gKer[0];\n" "for (int j = 1; j <= ksizeHalf; ++j)\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "row[k*smw + i] +=\n" "(src[mad24(k*rows + idx_row_low(y - j, rows - 1), srcStep, xExt)] +\n" "src[mad24(k*rows + idx_row_high(y + j, rows - 1), srcStep, xExt)]) * c_gKer[j];\n" "}\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (y < rows && y >= 0 && x < cols && x >= 0)\n" "{\n" "row += tx + ksizeHalf;\n" "float res[5];\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "res[k] = row[k*smw] * c_gKer[0];\n" "for (int i = 1; i <= ksizeHalf; ++i)\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "res[k] += (row[k*smw - i] + row[k*smw + i]) * c_gKer[i];\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "dst[mad24(k*rows + y, dstStep, x)] = res[k];\n" "}\n" "}\n" "__constant float c_border[BORDER_SIZE + 1] = { 0.14f, 0.14f, 0.4472f, 0.4472f, 0.4472f, 1.f };\n" "__kernel void updateMatrices(__global const float * flowx, int xStep,\n" "__global const float * flowy, int yStep,\n" "const int rows, const int cols,\n" "__global const float * R0, int R0Step,\n" "__global const float * R1, int R1Step,\n" "__global float * M, int mStep)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = get_global_id(0);\n" "if (y < rows && y >= 0 && x < cols && x >= 0)\n" "{\n" "float dx = flowx[mad24(y, xStep, x)];\n" "float dy = flowy[mad24(y, yStep, x)];\n" "float fx = x + dx;\n" "float fy = y + dy;\n" "int x1 = convert_int(floor(fx));\n" "int y1 = convert_int(floor(fy));\n" "fx -= x1;\n" "fy -= y1;\n" "float r2, r3, r4, r5, r6;\n" "if (x1 >= 0 && y1 >= 0 && x1 < cols - 1 && y1 < rows - 1)\n" "{\n" "float a00 = (1.f - fx) * (1.f - fy);\n" "float a01 = fx * (1.f - fy);\n" "float a10 = (1.f - fx) * fy;\n" "float a11 = fx * fy;\n" "r2 = a00 * R1[mad24(y1, R1Step, x1)] +\n" "a01 * R1[mad24(y1, R1Step, x1 + 1)] +\n" "a10 * R1[mad24(y1 + 1, R1Step, x1)] +\n" "a11 * R1[mad24(y1 + 1, R1Step, x1 + 1)];\n" "r3 = a00 * R1[mad24(rows + y1, R1Step, x1)] +\n" "a01 * R1[mad24(rows + y1, R1Step, x1 + 1)] +\n" "a10 * R1[mad24(rows + y1 + 1, R1Step, x1)] +\n" "a11 * R1[mad24(rows + y1 + 1, R1Step, x1 + 1)];\n" "r4 = a00 * R1[mad24(2*rows + y1, R1Step, x1)] +\n" "a01 * R1[mad24(2*rows + y1, R1Step, x1 + 1)] +\n" "a10 * R1[mad24(2*rows + y1 + 1, R1Step, x1)] +\n" "a11 * R1[mad24(2*rows + y1 + 1, R1Step, x1 + 1)];\n" "r5 = a00 * R1[mad24(3*rows + y1, R1Step, x1)] +\n" "a01 * R1[mad24(3*rows + y1, R1Step, x1 + 1)] +\n" "a10 * R1[mad24(3*rows + y1 + 1, R1Step, x1)] +\n" "a11 * R1[mad24(3*rows + y1 + 1, R1Step, x1 + 1)];\n" "r6 = a00 * R1[mad24(4*rows + y1, R1Step, x1)] +\n" "a01 * R1[mad24(4*rows + y1, R1Step, x1 + 1)] +\n" "a10 * R1[mad24(4*rows + y1 + 1, R1Step, x1)] +\n" "a11 * R1[mad24(4*rows + y1 + 1, R1Step, x1 + 1)];\n" "r4 = (R0[mad24(2*rows + y, R0Step, x)] + r4) * 0.5f;\n" "r5 = (R0[mad24(3*rows + y, R0Step, x)] + r5) * 0.5f;\n" "r6 = (R0[mad24(4*rows + y, R0Step, x)] + r6) * 0.25f;\n" "}\n" "else\n" "{\n" "r2 = r3 = 0.f;\n" "r4 = R0[mad24(2*rows + y, R0Step, x)];\n" "r5 = R0[mad24(3*rows + y, R0Step, x)];\n" "r6 = R0[mad24(4*rows + y, R0Step, x)] * 0.5f;\n" "}\n" "r2 = (R0[mad24(y, R0Step, x)] - r2) * 0.5f;\n" "r3 = (R0[mad24(rows + y, R0Step, x)] - r3) * 0.5f;\n" "r2 += r4*dy + r6*dx;\n" "r3 += r6*dy + r5*dx;\n" "float scale =\n" "c_border[min(x, BORDER_SIZE)] *\n" "c_border[min(y, BORDER_SIZE)] *\n" "c_border[min(cols - x - 1, BORDER_SIZE)] *\n" "c_border[min(rows - y - 1, BORDER_SIZE)];\n" "r2 *= scale;\n" "r3 *= scale;\n" "r4 *= scale;\n" "r5 *= scale;\n" "r6 *= scale;\n" "M[mad24(y, mStep, x)] = r4*r4 + r6*r6;\n" "M[mad24(rows + y, mStep, x)] = (r4 + r5)*r6;\n" "M[mad24(2*rows + y, mStep, x)] = r5*r5 + r6*r6;\n" "M[mad24(3*rows + y, mStep, x)] = r4*r2 + r6*r3;\n" "M[mad24(4*rows + y, mStep, x)] = r6*r2 + r5*r3;\n" "}\n" "}\n" "__kernel void boxFilter5(__global const float * src, int srcStep,\n" "__global float * dst, int dstStep,\n" "const int rows, const int cols,\n" "const int ksizeHalf,\n" "__local float * smem)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = get_global_id(0);\n" "const float boxAreaInv = 1.f / ((1 + 2*ksizeHalf) * (1 + 2*ksizeHalf));\n" "const int smw = bdx + 2*ksizeHalf;\n" "__local float *row = smem + 5 * ty * smw;\n" "if (y < rows)\n" "{\n" "for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)\n" "{\n" "int xExt = (int)(bx * bdx) + i - ksizeHalf;\n" "xExt = min(max(xExt, 0), cols - 1);\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "row[k*smw + i] = src[mad24(k*rows + y, srcStep, xExt)];\n" "for (int j = 1; j <= ksizeHalf; ++j)\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "row[k*smw + i] +=\n" "src[mad24(k*rows + max(y - j, 0), srcStep, xExt)] +\n" "src[mad24(k*rows + min(y + j, rows - 1), srcStep, xExt)];\n" "}\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (y < rows && y >= 0 && x < cols && x >= 0)\n" "{\n" "row += tx + ksizeHalf;\n" "float res[5];\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "res[k] = row[k*smw];\n" "for (int i = 1; i <= ksizeHalf; ++i)\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "res[k] += row[k*smw - i] + row[k*smw + i];\n" "#pragma unroll\n" "for (int k = 0; k < 5; ++k)\n" "dst[mad24(k*rows + y, dstStep, x)] = res[k] * boxAreaInv;\n" "}\n" "}\n" "__kernel void updateFlow(__global const float * M, int mStep,\n" "__global float * flowx, int xStep,\n" "__global float * flowy, int yStep,\n" "const int rows, const int cols)\n" "{\n" "const int y = get_global_id(1);\n" "const int x = get_global_id(0);\n" "if (y < rows && y >= 0 && x < cols && x >= 0)\n" "{\n" "float g11 = M[mad24(y, mStep, x)];\n" "float g12 = M[mad24(rows + y, mStep, x)];\n" "float g22 = M[mad24(2*rows + y, mStep, x)];\n" "float h1 = M[mad24(3*rows + y, mStep, x)];\n" "float h2 = M[mad24(4*rows + y, mStep, x)];\n" "float detInv = 1.f / (g11*g22 - g12*g12 + 1e-3f);\n" "flowx[mad24(y, xStep, x)] = (g11*h2 - g12*h1) * detInv;\n" "flowy[mad24(y, yStep, x)] = (g22*h1 - g12*h2) * detInv;\n" "}\n" "}\n" , "529300e6242f574f83d11a089cc120c0", NULL}; struct cv::ocl::internal::ProgramEntry optical_flow_tvl1_oclsrc={moduleName, "optical_flow_tvl1", "__kernel void centeredGradientKernel(__global const float* src_ptr, int src_col, int src_row, int src_step,\n" "__global float* dx, __global float* dy, int d_step)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if((x < src_col)&&(y < src_row))\n" "{\n" "int src_x1 = (x + 1) < (src_col -1)? (x + 1) : (src_col - 1);\n" "int src_x2 = (x - 1) > 0 ? (x -1) : 0;\n" "dx[y * d_step+ x] = 0.5f * (src_ptr[y * src_step + src_x1] - src_ptr[y * src_step+ src_x2]);\n" "int src_y1 = (y+1) < (src_row - 1) ? (y + 1) : (src_row - 1);\n" "int src_y2 = (y - 1) > 0 ? (y - 1) : 0;\n" "dy[y * d_step+ x] = 0.5f * (src_ptr[src_y1 * src_step + x] - src_ptr[src_y2 * src_step+ x]);\n" "}\n" "}\n" "inline float bicubicCoeff(float x_)\n" "{\n" "float x = fabs(x_);\n" "if (x <= 1.0f)\n" "return x * x * (1.5f * x - 2.5f) + 1.0f;\n" "else if (x < 2.0f)\n" "return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f;\n" "else\n" "return 0.0f;\n" "}\n" "__kernel void warpBackwardKernel(__global const float* I0, int I0_step, int I0_col, int I0_row,\n" "image2d_t tex_I1, image2d_t tex_I1x, image2d_t tex_I1y,\n" "__global const float* u1, int u1_step,\n" "__global const float* u2,\n" "__global float* I1w,\n" "__global float* I1wx, \n" "__global float* I1wy, \n" "__global float* grad, \n" "__global float* rho,\n" "int I1w_step,\n" "int u2_step,\n" "int u1_offset_x,\n" "int u1_offset_y,\n" "int u2_offset_x,\n" "int u2_offset_y)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < I0_col&&y < I0_row)\n" "{\n" "float u1Val = u1[(y + u1_offset_y) * u1_step + x + u1_offset_x];\n" "float u2Val = u2[(y + u2_offset_y) * u2_step + x + u2_offset_x];\n" "float wx = x + u1Val;\n" "float wy = y + u2Val;\n" "int xmin = ceil(wx - 2.0f);\n" "int xmax = floor(wx + 2.0f);\n" "int ymin = ceil(wy - 2.0f);\n" "int ymax = floor(wy + 2.0f);\n" "float sum = 0.0f;\n" "float sumx = 0.0f;\n" "float sumy = 0.0f;\n" "float wsum = 0.0f;\n" "sampler_t sampleri = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;\n" "for (int cy = ymin; cy <= ymax; ++cy)\n" "{\n" "for (int cx = xmin; cx <= xmax; ++cx)\n" "{\n" "float w = bicubicCoeff(wx - cx) * bicubicCoeff(wy - cy);\n" "int2 cood = (int2)(cx, cy);\n" "sum += w * read_imagef(tex_I1, sampleri, cood).x;\n" "sumx += w * read_imagef(tex_I1x, sampleri, cood).x;\n" "sumy += w * read_imagef(tex_I1y, sampleri, cood).x;\n" "wsum += w;\n" "}\n" "}\n" "float coeff = 1.0f / wsum;\n" "float I1wVal = sum * coeff;\n" "float I1wxVal = sumx * coeff;\n" "float I1wyVal = sumy * coeff;\n" "I1w[y * I1w_step + x] = I1wVal;\n" "I1wx[y * I1w_step + x] = I1wxVal;\n" "I1wy[y * I1w_step + x] = I1wyVal;\n" "float Ix2 = I1wxVal * I1wxVal;\n" "float Iy2 = I1wyVal * I1wyVal;\n" "grad[y * I1w_step + x] = Ix2 + Iy2;\n" "float I0Val = I0[y * I0_step + x];\n" "rho[y * I1w_step + x] = I1wVal - I1wxVal * u1Val - I1wyVal * u2Val - I0Val;\n" "}\n" "}\n" "inline float readImage(__global const float *image, int x, int y, int rows, int cols, int elemCntPerRow)\n" "{\n" "int i0 = clamp(x, 0, cols - 1);\n" "int j0 = clamp(y, 0, rows - 1);\n" "return image[j0 * elemCntPerRow + i0];\n" "}\n" "__kernel void warpBackwardKernelNoImage2d(__global const float* I0, int I0_step, int I0_col, int I0_row,\n" "__global const float* tex_I1, __global const float* tex_I1x, __global const float* tex_I1y,\n" "__global const float* u1, int u1_step,\n" "__global const float* u2,\n" "__global float* I1w,\n" "__global float* I1wx, \n" "__global float* I1wy, \n" "__global float* grad, \n" "__global float* rho,\n" "int I1w_step,\n" "int u2_step,\n" "int I1_step,\n" "int I1x_step)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < I0_col&&y < I0_row)\n" "{\n" "float u1Val = u1[y * u1_step + x];\n" "float u2Val = u2[y * u2_step + x];\n" "float wx = x + u1Val;\n" "float wy = y + u2Val;\n" "int xmin = ceil(wx - 2.0f);\n" "int xmax = floor(wx + 2.0f);\n" "int ymin = ceil(wy - 2.0f);\n" "int ymax = floor(wy + 2.0f);\n" "float sum = 0.0f;\n" "float sumx = 0.0f;\n" "float sumy = 0.0f;\n" "float wsum = 0.0f;\n" "for (int cy = ymin; cy <= ymax; ++cy)\n" "{\n" "for (int cx = xmin; cx <= xmax; ++cx)\n" "{\n" "float w = bicubicCoeff(wx - cx) * bicubicCoeff(wy - cy);\n" "int2 cood = (int2)(cx, cy);\n" "sum += w * readImage(tex_I1, cood.x, cood.y, I0_col, I0_row, I1_step);\n" "sumx += w * readImage(tex_I1x, cood.x, cood.y, I0_col, I0_row, I1x_step);\n" "sumy += w * readImage(tex_I1y, cood.x, cood.y, I0_col, I0_row, I1x_step);\n" "wsum += w;\n" "}\n" "}\n" "float coeff = 1.0f / wsum;\n" "float I1wVal = sum * coeff;\n" "float I1wxVal = sumx * coeff;\n" "float I1wyVal = sumy * coeff;\n" "I1w[y * I1w_step + x] = I1wVal;\n" "I1wx[y * I1w_step + x] = I1wxVal;\n" "I1wy[y * I1w_step + x] = I1wyVal;\n" "float Ix2 = I1wxVal * I1wxVal;\n" "float Iy2 = I1wyVal * I1wyVal;\n" "grad[y * I1w_step + x] = Ix2 + Iy2;\n" "float I0Val = I0[y * I0_step + x];\n" "rho[y * I1w_step + x] = I1wVal - I1wxVal * u1Val - I1wyVal * u2Val - I0Val;\n" "}\n" "}\n" "__kernel void estimateDualVariablesKernel(__global const float* u1, int u1_col, int u1_row, int u1_step,\n" "__global const float* u2,\n" "__global float* p11, int p11_step,\n" "__global float* p12,\n" "__global float* p21,\n" "__global float* p22,\n" "float taut,\n" "int u2_step,\n" "int u1_offset_x,\n" "int u1_offset_y,\n" "int u2_offset_x,\n" "int u2_offset_y)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < u1_col && y < u1_row)\n" "{\n" "int src_x1 = (x + 1) < (u1_col - 1) ? (x + 1) : (u1_col - 1);\n" "float u1x = u1[(y + u1_offset_y) * u1_step + src_x1 + u1_offset_x] - u1[(y + u1_offset_y) * u1_step + x + u1_offset_x];\n" "int src_y1 = (y + 1) < (u1_row - 1) ? (y + 1) : (u1_row - 1);\n" "float u1y = u1[(src_y1 + u1_offset_y) * u1_step + x + u1_offset_x] - u1[(y + u1_offset_y) * u1_step + x + u1_offset_x];\n" "int src_x2 = (x + 1) < (u1_col - 1) ? (x + 1) : (u1_col - 1);\n" "float u2x = u2[(y + u2_offset_y) * u2_step + src_x2 + u2_offset_x] - u2[(y + u2_offset_y) * u2_step + x + u2_offset_x];\n" "int src_y2 = (y + 1) < (u1_row - 1) ? (y + 1) : (u1_row - 1);\n" "float u2y = u2[(src_y2 + u2_offset_y) * u2_step + x + u2_offset_x] - u2[(y + u2_offset_y) * u2_step + x + u2_offset_x];\n" "float g1 = hypot(u1x, u1y);\n" "float g2 = hypot(u2x, u2y);\n" "float ng1 = 1.0f + taut * g1;\n" "float ng2 = 1.0f + taut * g2;\n" "p11[y * p11_step + x] = (p11[y * p11_step + x] + taut * u1x) / ng1;\n" "p12[y * p11_step + x] = (p12[y * p11_step + x] + taut * u1y) / ng1;\n" "p21[y * p11_step + x] = (p21[y * p11_step + x] + taut * u2x) / ng2;\n" "p22[y * p11_step + x] = (p22[y * p11_step + x] + taut * u2y) / ng2;\n" "}\n" "}\n" "inline float divergence(__global const float* v1, __global const float* v2, int y, int x, int v1_step, int v2_step)\n" "{\n" "if (x > 0 && y > 0)\n" "{\n" "float v1x = v1[y * v1_step + x] - v1[y * v1_step + x - 1];\n" "float v2y = v2[y * v2_step + x] - v2[(y - 1) * v2_step + x];\n" "return v1x + v2y;\n" "}\n" "else\n" "{\n" "if (y > 0)\n" "return v1[y * v1_step + 0] + v2[y * v2_step + 0] - v2[(y - 1) * v2_step + 0];\n" "else\n" "{\n" "if (x > 0)\n" "return v1[0 * v1_step + x] - v1[0 * v1_step + x - 1] + v2[0 * v2_step + x];\n" "else\n" "return v1[0 * v1_step + 0] + v2[0 * v2_step + 0];\n" "}\n" "}\n" "}\n" "__kernel void estimateUKernel(__global const float* I1wx, int I1wx_col, int I1wx_row, int I1wx_step,\n" "__global const float* I1wy, \n" "__global const float* grad, \n" "__global const float* rho_c, \n" "__global const float* p11, \n" "__global const float* p12, \n" "__global const float* p21, \n" "__global const float* p22, \n" "__global float* u1, int u1_step,\n" "__global float* u2,\n" "__global float* error, float l_t, float theta, int u2_step,\n" "int u1_offset_x,\n" "int u1_offset_y,\n" "int u2_offset_x,\n" "int u2_offset_y,\n" "char calc_error)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < I1wx_col && y < I1wx_row)\n" "{\n" "float I1wxVal = I1wx[y * I1wx_step + x];\n" "float I1wyVal = I1wy[y * I1wx_step + x];\n" "float gradVal = grad[y * I1wx_step + x];\n" "float u1OldVal = u1[(y + u1_offset_y) * u1_step + x + u1_offset_x];\n" "float u2OldVal = u2[(y + u2_offset_y) * u2_step + x + u2_offset_x];\n" "float rho = rho_c[y * I1wx_step + x] + (I1wxVal * u1OldVal + I1wyVal * u2OldVal);\n" "float d1 = 0.0f;\n" "float d2 = 0.0f;\n" "if (rho < -l_t * gradVal)\n" "{\n" "d1 = l_t * I1wxVal;\n" "d2 = l_t * I1wyVal;\n" "}\n" "else if (rho > l_t * gradVal)\n" "{\n" "d1 = -l_t * I1wxVal;\n" "d2 = -l_t * I1wyVal;\n" "}\n" "else if (gradVal > 1.192092896e-07f)\n" "{\n" "float fi = -rho / gradVal;\n" "d1 = fi * I1wxVal;\n" "d2 = fi * I1wyVal;\n" "}\n" "float v1 = u1OldVal + d1;\n" "float v2 = u2OldVal + d2;\n" "float div_p1 = divergence(p11, p12, y, x, I1wx_step, I1wx_step);\n" "float div_p2 = divergence(p21, p22, y, x, I1wx_step, I1wx_step);\n" "float u1NewVal = v1 + theta * div_p1;\n" "float u2NewVal = v2 + theta * div_p2;\n" "u1[(y + u1_offset_y) * u1_step + x + u1_offset_x] = u1NewVal;\n" "u2[(y + u2_offset_y) * u2_step + x + u2_offset_x] = u2NewVal;\n" "if(calc_error)\n" "{\n" "float n1 = (u1OldVal - u1NewVal) * (u1OldVal - u1NewVal);\n" "float n2 = (u2OldVal - u2NewVal) * (u2OldVal - u2NewVal);\n" "error[y * I1wx_step + x] = n1 + n2;\n" "}\n" "}\n" "}\n" , "9474ca90cbcc7660f6c47b8a45d6730d", NULL}; struct cv::ocl::internal::ProgramEntry pyrlk_oclsrc={moduleName, "pyrlk", "#define GRIDSIZE 3\n" "#define LSx 8\n" "#define LSy 8\n" "#define LM_W (LSx*GRIDSIZE+2)\n" "#define LM_H (LSy*GRIDSIZE+2)\n" "#define BUFFER (LSx*LSy)\n" "#define BUFFER2 BUFFER>>1\n" "#ifndef WAVE_SIZE\n" "#define WAVE_SIZE 1\n" "#endif\n" "#ifdef CPU\n" "inline void reduce3(float val1, float val2, float val3, __local float* smem1, __local float* smem2, __local float* smem3, int tid)\n" "{\n" "smem1[tid] = val1;\n" "smem2[tid] = val2;\n" "smem3[tid] = val3;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "for(int i = BUFFER2; i > 0; i >>= 1)\n" "{\n" "if(tid < i)\n" "{\n" "smem1[tid] += smem1[tid + i];\n" "smem2[tid] += smem2[tid + i];\n" "smem3[tid] += smem3[tid + i];\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "}\n" "inline void reduce2(float val1, float val2, volatile __local float* smem1, volatile __local float* smem2, int tid)\n" "{\n" "smem1[tid] = val1;\n" "smem2[tid] = val2;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "for(int i = BUFFER2; i > 0; i >>= 1)\n" "{\n" "if(tid < i)\n" "{\n" "smem1[tid] += smem1[tid + i];\n" "smem2[tid] += smem2[tid + i];\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "}\n" "inline void reduce1(float val1, volatile __local float* smem1, int tid)\n" "{\n" "smem1[tid] = val1;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "for(int i = BUFFER2; i > 0; i >>= 1)\n" "{\n" "if(tid < i)\n" "{\n" "smem1[tid] += smem1[tid + i];\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "}\n" "#else\n" "inline void reduce3(float val1, float val2, float val3,\n" "__local volatile float* smem1, __local volatile float* smem2, __local volatile float* smem3, int tid)\n" "{\n" "smem1[tid] = val1;\n" "smem2[tid] = val2;\n" "smem3[tid] = val3;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 32)\n" "{\n" "smem1[tid] += smem1[tid + 32];\n" "smem2[tid] += smem2[tid + 32];\n" "smem3[tid] += smem3[tid + 32];\n" "#if WAVE_SIZE < 32\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 16)\n" "{\n" "#endif\n" "smem1[tid] += smem1[tid + 16];\n" "smem2[tid] += smem2[tid + 16];\n" "smem3[tid] += smem3[tid + 16];\n" "#if WAVE_SIZE <16\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid<1)\n" "{\n" "#endif\n" "local float8* m1 = (local float8*)smem1;\n" "local float8* m2 = (local float8*)smem2;\n" "local float8* m3 = (local float8*)smem3;\n" "float8 t1 = m1[0]+m1[1];\n" "float8 t2 = m2[0]+m2[1];\n" "float8 t3 = m3[0]+m3[1];\n" "float4 t14 = t1.lo + t1.hi;\n" "float4 t24 = t2.lo + t2.hi;\n" "float4 t34 = t3.lo + t3.hi;\n" "smem1[0] = t14.x+t14.y+t14.z+t14.w;\n" "smem2[0] = t24.x+t24.y+t24.z+t24.w;\n" "smem3[0] = t34.x+t34.y+t34.z+t34.w;\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "inline void reduce2(float val1, float val2, __local volatile float* smem1, __local volatile float* smem2, int tid)\n" "{\n" "smem1[tid] = val1;\n" "smem2[tid] = val2;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 32)\n" "{\n" "smem1[tid] += smem1[tid + 32];\n" "smem2[tid] += smem2[tid + 32];\n" "#if WAVE_SIZE < 32\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 16)\n" "{\n" "#endif\n" "smem1[tid] += smem1[tid + 16];\n" "smem2[tid] += smem2[tid + 16];\n" "#if WAVE_SIZE <16\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid<1)\n" "{\n" "#endif\n" "local float8* m1 = (local float8*)smem1;\n" "local float8* m2 = (local float8*)smem2;\n" "float8 t1 = m1[0]+m1[1];\n" "float8 t2 = m2[0]+m2[1];\n" "float4 t14 = t1.lo + t1.hi;\n" "float4 t24 = t2.lo + t2.hi;\n" "smem1[0] = t14.x+t14.y+t14.z+t14.w;\n" "smem2[0] = t24.x+t24.y+t24.z+t24.w;\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "inline void reduce1(float val1, __local volatile float* smem1, int tid)\n" "{\n" "smem1[tid] = val1;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 32)\n" "{\n" "smem1[tid] += smem1[tid + 32];\n" "#if WAVE_SIZE < 32\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid < 16)\n" "{\n" "#endif\n" "smem1[tid] += smem1[tid + 16];\n" "#if WAVE_SIZE <16\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (tid<1)\n" "{\n" "#endif\n" "local float8* m1 = (local float8*)smem1;\n" "float8 t1 = m1[0]+m1[1];\n" "float4 t14 = t1.lo + t1.hi;\n" "smem1[0] = t14.x+t14.y+t14.z+t14.w;\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "#endif\n" "#define SCALE (1.0f / (1 << 20))\n" "#define THRESHOLD 0.01f\n" "__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_LINEAR;\n" "#define VAL(_y,_x,_yy,_xx) (IPatchLocal[mad24(((_y) + (_yy)), LM_W, ((_x) + (_xx)))])\n" "inline void SetPatch(local float* IPatchLocal, int TileY, int TileX,\n" "float* Pch, float* Dx, float* Dy,\n" "float* A11, float* A12, float* A22, float w)\n" "{\n" "int xid=get_local_id(0);\n" "int yid=get_local_id(1);\n" "int xBase = mad24(TileX, LSx, (xid + 1));\n" "int yBase = mad24(TileY, LSy, (yid + 1));\n" "*Pch = VAL(yBase,xBase,0,0);\n" "*Dx = mad((VAL(yBase,xBase,-1,1) + VAL(yBase,xBase,+1,1) - VAL(yBase,xBase,-1,-1) - VAL(yBase,xBase,+1,-1)), 3.0f, (VAL(yBase,xBase,0,1) - VAL(yBase,xBase,0,-1)) * 10.0f) * w;\n" "*Dy = mad((VAL(yBase,xBase,1,-1) + VAL(yBase,xBase,1,+1) - VAL(yBase,xBase,-1,-1) - VAL(yBase,xBase,-1,+1)), 3.0f, (VAL(yBase,xBase,1,0) - VAL(yBase,xBase,-1,0)) * 10.0f) * w;\n" "*A11 = mad(*Dx, *Dx, *A11);\n" "*A12 = mad(*Dx, *Dy, *A12);\n" "*A22 = mad(*Dy, *Dy, *A22);\n" "}\n" "#undef VAL\n" "inline void GetPatch(image2d_t J, float x, float y,\n" "float* Pch, float* Dx, float* Dy,\n" "float* b1, float* b2)\n" "{\n" "float diff = read_imagef(J, sampler, (float2)(x,y)).x-*Pch;\n" "*b1 = mad(diff, *Dx, *b1);\n" "*b2 = mad(diff, *Dy, *b2);\n" "}\n" "inline void GetError(image2d_t J, const float x, const float y, const float* Pch, float* errval, float w)\n" "{\n" "float diff = ((((read_imagef(J, sampler, (float2)(x,y)).x * 16384) + 256) / 512) - (((*Pch * 16384) + 256) /512)) * w;\n" "*errval += fabs(diff);\n" "}\n" "#define READI(_y,_x) IPatchLocal[mad24(mad24((_y), LSy, yid), LM_W, mad24((_x), LSx, xid))] = read_imagef(I, sampler, (float2)(mad((float)(_x), (float)LSx, Point.x + xid - 0.5f), mad((float)(_y), (float)LSy, Point.y + yid - 0.5f))).x;\n" "void ReadPatchIToLocalMem(image2d_t I, float2 Point, local float* IPatchLocal)\n" "{\n" "int xid=get_local_id(0);\n" "int yid=get_local_id(1);\n" "READI(0,0);READI(0,1);READI(0,2);\n" "READI(1,0);READI(1,1);READI(1,2);\n" "READI(2,0);READI(2,1);READI(2,2);\n" "if(xid<2)\n" "{\n" "READI(0,3);\n" "READI(1,3);\n" "READI(2,3);\n" "}\n" "if(yid<2)\n" "{\n" "READI(3,0);READI(3,1);READI(3,2);\n" "}\n" "if(yid<2 && xid<2)\n" "{\n" "READI(3,3);\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n" "#undef READI\n" "__attribute__((reqd_work_group_size(LSx, LSy, 1)))\n" "__kernel void lkSparse(image2d_t I, image2d_t J,\n" "__global const float2* prevPts, __global float2* nextPts, __global uchar* status, __global float* err,\n" "const int level, const int rows, const int cols, int PATCH_X, int PATCH_Y, int c_winSize_x, int c_winSize_y, int c_iters, char calcErr)\n" "{\n" "__local float smem1[BUFFER];\n" "__local float smem2[BUFFER];\n" "__local float smem3[BUFFER];\n" "int xid=get_local_id(0);\n" "int yid=get_local_id(1);\n" "int gid=get_group_id(0);\n" "int xsize=get_local_size(0);\n" "int ysize=get_local_size(1);\n" "int k;\n" "#ifdef CPU\n" "float wx0 = 1.0f;\n" "float wy0 = 1.0f;\n" "int xBase = mad24(xsize, 2, xid);\n" "int yBase = mad24(ysize, 2, yid);\n" "float wx1 = (xBase < c_winSize_x) ? 1 : 0;\n" "float wy1 = (yBase < c_winSize_y) ? 1 : 0;\n" "#else\n" "#if WSX == 1\n" "float wx0 = 1.0f;\n" "int xBase = mad24(xsize, 2, xid);\n" "float wx1 = (xBase < c_winSize_x) ? 1 : 0;\n" "#else\n" "int xBase = mad24(xsize, 1, xid);\n" "float wx0 = (xBase < c_winSize_x) ? 1 : 0;\n" "float wx1 = 0.0f;\n" "#endif\n" "#if WSY == 1\n" "float wy0 = 1.0f;\n" "int yBase = mad24(ysize, 2, yid);\n" "float wy1 = (yBase < c_winSize_y) ? 1 : 0;\n" "#else\n" "int yBase = mad24(ysize, 1, yid);\n" "float wy0 = (yBase < c_winSize_y) ? 1 : 0;\n" "float wy1 = 0.0f;\n" "#endif\n" "#endif\n" "float2 c_halfWin = (float2)((c_winSize_x - 1)>>1, (c_winSize_y - 1)>>1);\n" "const int tid = mad24(yid, xsize, xid);\n" "float2 prevPt = prevPts[gid] / (float2)(1 << level);\n" "if (prevPt.x < 0 || prevPt.x >= cols || prevPt.y < 0 || prevPt.y >= rows)\n" "{\n" "if (tid == 0 && level == 0)\n" "{\n" "status[gid] = 0;\n" "}\n" "return;\n" "}\n" "prevPt -= c_halfWin;\n" "float A11 = 0;\n" "float A12 = 0;\n" "float A22 = 0;\n" "float I_patch[GRIDSIZE][GRIDSIZE];\n" "float dIdx_patch[GRIDSIZE][GRIDSIZE];\n" "float dIdy_patch[GRIDSIZE][GRIDSIZE];\n" "local float IPatchLocal[LM_W*LM_H];\n" "ReadPatchIToLocalMem(I,prevPt,IPatchLocal);\n" "{\n" "SetPatch(IPatchLocal, 0, 0,\n" "&I_patch[0][0], &dIdx_patch[0][0], &dIdy_patch[0][0],\n" "&A11, &A12, &A22,1);\n" "SetPatch(IPatchLocal, 0, 1,\n" "&I_patch[0][1], &dIdx_patch[0][1], &dIdy_patch[0][1],\n" "&A11, &A12, &A22,wx0);\n" "SetPatch(IPatchLocal, 0, 2,\n" "&I_patch[0][2], &dIdx_patch[0][2], &dIdy_patch[0][2],\n" "&A11, &A12, &A22,wx1);\n" "}\n" "{\n" "SetPatch(IPatchLocal, 1, 0,\n" "&I_patch[1][0], &dIdx_patch[1][0], &dIdy_patch[1][0],\n" "&A11, &A12, &A22,wy0);\n" "SetPatch(IPatchLocal, 1,1,\n" "&I_patch[1][1], &dIdx_patch[1][1], &dIdy_patch[1][1],\n" "&A11, &A12, &A22,wx0*wy0);\n" "SetPatch(IPatchLocal, 1,2,\n" "&I_patch[1][2], &dIdx_patch[1][2], &dIdy_patch[1][2],\n" "&A11, &A12, &A22,wx1*wy0);\n" "}\n" "{\n" "SetPatch(IPatchLocal, 2,0,\n" "&I_patch[2][0], &dIdx_patch[2][0], &dIdy_patch[2][0],\n" "&A11, &A12, &A22,wy1);\n" "SetPatch(IPatchLocal, 2,1,\n" "&I_patch[2][1], &dIdx_patch[2][1], &dIdy_patch[2][1],\n" "&A11, &A12, &A22,wx0*wy1);\n" "SetPatch(IPatchLocal, 2,2,\n" "&I_patch[2][2], &dIdx_patch[2][2], &dIdy_patch[2][2],\n" "&A11, &A12, &A22,wx1*wy1);\n" "}\n" "reduce3(A11, A12, A22, smem1, smem2, smem3, tid);\n" "A11 = smem1[0];\n" "A12 = smem2[0];\n" "A22 = smem3[0];\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "float D = mad(A11, A22, - A12 * A12);\n" "if (D < 1.192092896e-07f)\n" "{\n" "if (tid == 0 && level == 0)\n" "status[gid] = 0;\n" "return;\n" "}\n" "A11 /= D;\n" "A12 /= D;\n" "A22 /= D;\n" "prevPt = mad(nextPts[gid], 2.0f, - c_halfWin);\n" "float2 offset0 = (float2)(xid + 0.5f, yid + 0.5f);\n" "float2 offset1 = (float2)(xsize, ysize);\n" "float2 loc0 = prevPt + offset0;\n" "float2 loc1 = loc0 + offset1;\n" "float2 loc2 = loc1 + offset1;\n" "for (k = 0; k < c_iters; ++k)\n" "{\n" "if (prevPt.x < -c_halfWin.x || prevPt.x >= cols || prevPt.y < -c_halfWin.y || prevPt.y >= rows)\n" "{\n" "if (tid == 0 && level == 0)\n" "status[gid] = 0;\n" "break;\n" "}\n" "float b1 = 0;\n" "float b2 = 0;\n" "{\n" "GetPatch(J, loc0.x, loc0.y,\n" "&I_patch[0][0], &dIdx_patch[0][0], &dIdy_patch[0][0],\n" "&b1, &b2);\n" "GetPatch(J, loc1.x, loc0.y,\n" "&I_patch[0][1], &dIdx_patch[0][1], &dIdy_patch[0][1],\n" "&b1, &b2);\n" "GetPatch(J, loc2.x, loc0.y,\n" "&I_patch[0][2], &dIdx_patch[0][2], &dIdy_patch[0][2],\n" "&b1, &b2);\n" "}\n" "{\n" "GetPatch(J, loc0.x, loc1.y,\n" "&I_patch[1][0], &dIdx_patch[1][0], &dIdy_patch[1][0],\n" "&b1, &b2);\n" "GetPatch(J, loc1.x, loc1.y,\n" "&I_patch[1][1], &dIdx_patch[1][1], &dIdy_patch[1][1],\n" "&b1, &b2);\n" "GetPatch(J, loc2.x, loc1.y,\n" "&I_patch[1][2], &dIdx_patch[1][2], &dIdy_patch[1][2],\n" "&b1, &b2);\n" "}\n" "{\n" "GetPatch(J, loc0.x, loc2.y,\n" "&I_patch[2][0], &dIdx_patch[2][0], &dIdy_patch[2][0],\n" "&b1, &b2);\n" "GetPatch(J, loc1.x, loc2.y,\n" "&I_patch[2][1], &dIdx_patch[2][1], &dIdy_patch[2][1],\n" "&b1, &b2);\n" "GetPatch(J, loc2.x, loc2.y,\n" "&I_patch[2][2], &dIdx_patch[2][2], &dIdy_patch[2][2],\n" "&b1, &b2);\n" "}\n" "reduce2(b1, b2, smem1, smem2, tid);\n" "b1 = smem1[0];\n" "b2 = smem2[0];\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "float2 delta;\n" "delta.x = mad(A12, b2, - A22 * b1) * 32.0f;\n" "delta.y = mad(A12, b1, - A11 * b2) * 32.0f;\n" "prevPt += delta;\n" "loc0 += delta;\n" "loc1 += delta;\n" "loc2 += delta;\n" "if (fabs(delta.x) < THRESHOLD && fabs(delta.y) < THRESHOLD)\n" "break;\n" "}\n" "D = 0.0f;\n" "if (calcErr)\n" "{\n" "{\n" "GetError(J, loc0.x, loc0.y, &I_patch[0][0], &D, 1);\n" "GetError(J, loc1.x, loc0.y, &I_patch[0][1], &D, wx0);\n" "}\n" "{\n" "GetError(J, loc0.x, loc1.y, &I_patch[1][0], &D, wy0);\n" "GetError(J, loc1.x, loc1.y, &I_patch[1][1], &D, wx0*wy0);\n" "}\n" "if(xBase < c_winSize_x)\n" "{\n" "GetError(J, loc2.x, loc0.y, &I_patch[0][2], &D, wx1);\n" "GetError(J, loc2.x, loc1.y, &I_patch[1][2], &D, wx1*wy0);\n" "}\n" "if(yBase < c_winSize_y)\n" "{\n" "GetError(J, loc0.x, loc2.y, &I_patch[2][0], &D, wy1);\n" "GetError(J, loc1.x, loc2.y, &I_patch[2][1], &D, wx0*wy1);\n" "if(xBase < c_winSize_x)\n" "GetError(J, loc2.x, loc2.y, &I_patch[2][2], &D, wx1*wy1);\n" "}\n" "reduce1(D, smem1, tid);\n" "}\n" "if (tid == 0)\n" "{\n" "prevPt += c_halfWin;\n" "nextPts[gid] = prevPt;\n" "if (calcErr)\n" "err[gid] = smem1[0] / (float)(32 * c_winSize_x * c_winSize_y);\n" "}\n" "}\n" , "bb795566482a0fd9c80aabca645bf9ee", NULL}; }}} #endif
// Copyright 2013 The Flutter 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 <memory> #include <string> #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/event_channel.h" #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/event_stream_handler_functions.h" #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_method_codec.h" #include "gtest/gtest.h" namespace flutter { namespace { class TestBinaryMessenger : public BinaryMessenger { public: void Send(const std::string& channel, const uint8_t* message, const size_t message_size, BinaryReply reply) const override {} void SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) override { last_message_handler_channel_ = channel; last_message_handler_ = handler; } std::string last_message_handler_channel() { return last_message_handler_channel_; } BinaryMessageHandler last_message_handler() { return last_message_handler_; } private: std::string last_message_handler_channel_; BinaryMessageHandler last_message_handler_; }; } // namespace // Tests that SetStreamHandler sets a handler that correctly interacts with // the binary messenger. TEST(EventChannelTest, Registration) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EventChannel channel(&messenger, channel_name, &codec); bool on_listen_called = false; auto handler = std::make_unique<StreamHandlerFunctions<>>( [&on_listen_called](const EncodableValue* arguments, std::unique_ptr<EventSink<>>&& events) -> std::unique_ptr<StreamHandlerError<>> { on_listen_called = true; return nullptr; }, [](const EncodableValue* arguments) -> std::unique_ptr<StreamHandlerError<>> { return nullptr; }); channel.SetStreamHandler(std::move(handler)); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); // Send dummy listen message. MethodCall<> call("listen", nullptr); auto message = codec.EncodeMethodCall(call); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); // Check results. EXPECT_EQ(on_listen_called, true); } // Tests that SetStreamHandler with a null handler unregisters the handler. TEST(EventChannelTest, Unregistration) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EventChannel channel(&messenger, channel_name, &codec); auto handler = std::make_unique<StreamHandlerFunctions<>>( [](const EncodableValue* arguments, std::unique_ptr<EventSink<>>&& events) -> std::unique_ptr<StreamHandlerError<>> { return nullptr; }, [](const EncodableValue* arguments) -> std::unique_ptr<StreamHandlerError<>> { return nullptr; }); channel.SetStreamHandler(std::move(handler)); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); channel.SetStreamHandler(nullptr); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_EQ(messenger.last_message_handler(), nullptr); } // Test that OnCancel callback sequence. TEST(EventChannelTest, Cancel) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EventChannel channel(&messenger, channel_name, &codec); bool on_listen_called = false; bool on_cancel_called = false; auto handler = std::make_unique<StreamHandlerFunctions<>>( [&on_listen_called](const EncodableValue* arguments, std::unique_ptr<EventSink<>>&& events) -> std::unique_ptr<StreamHandlerError<>> { on_listen_called = true; return nullptr; }, [&on_cancel_called](const EncodableValue* arguments) -> std::unique_ptr<StreamHandlerError<>> { on_cancel_called = true; return nullptr; }); channel.SetStreamHandler(std::move(handler)); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); // Send dummy listen message. MethodCall<> call_listen("listen", nullptr); auto message = codec.EncodeMethodCall(call_listen); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); EXPECT_EQ(on_listen_called, true); // Send dummy cancel message. MethodCall<> call_cancel("cancel", nullptr); message = codec.EncodeMethodCall(call_cancel); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); // Check results. EXPECT_EQ(on_cancel_called, true); } // Pseudo test when user re-registers or call OnListen to the same channel. // Confirm that OnCancel is called and OnListen is called again // when user re-registers the same channel that has already started // communication. TEST(EventChannelTest, ReRegistration) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EventChannel channel(&messenger, channel_name, &codec); bool on_listen_called = false; bool on_cancel_called = false; auto handler = std::make_unique<StreamHandlerFunctions<>>( [&on_listen_called](const EncodableValue* arguments, std::unique_ptr<EventSink<>>&& events) -> std::unique_ptr<StreamHandlerError<>> { on_listen_called = true; return nullptr; }, [&on_cancel_called](const EncodableValue* arguments) -> std::unique_ptr<StreamHandlerError<>> { on_cancel_called = true; return nullptr; }); channel.SetStreamHandler(std::move(handler)); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); // Send dummy listen message. MethodCall<> call("listen", nullptr); auto message = codec.EncodeMethodCall(call); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); EXPECT_EQ(on_listen_called, true); // Send second dummy message to test StreamHandler's OnCancel // method is called before OnListen method is called. on_listen_called = false; message = codec.EncodeMethodCall(call); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); // Check results. EXPECT_EQ(on_cancel_called, true); EXPECT_EQ(on_listen_called, true); } } // namespace flutter
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <cuda/std/tuple> // template <class... Types> class tuple; // template <class U1, class U2> // tuple& operator=(pair<U1, U2>&& u); // UNSUPPORTED: c++98, c++03 // Internal compiler error in 14.24 // XFAIL: msvc-19.20, msvc-19.21, msvc-19.22, msvc-19.23, msvc-19.24, msvc-19.25 #include <cuda/std/tuple> #include <cuda/std/utility> #include <cuda/std/cassert> #include "test_macros.h" #include "MoveOnly.h" struct B { int id_; __device__ __host__ explicit B(int i = 0) : id_(i) {} __device__ __host__ virtual ~B() {} }; struct D : B { __device__ __host__ explicit D(int i) : B(i) {} }; int main(int, char**) { { typedef cuda::std::pair<long, MoveOnly> T0; typedef cuda::std::tuple<long long, MoveOnly> T1; T0 t0(2, MoveOnly(3)); T1 t1; t1 = cuda::std::move(t0); assert(cuda::std::get<0>(t1) == 2); assert(cuda::std::get<1>(t1).get() == 3); } return 0; }
// Copyright (c) 2018 The Mantle Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <blockfilter.h> static void ConstructGCSFilter(benchmark::Bench& bench) { GCSFilter::ElementSet elements; for (int i = 0; i < 10000; ++i) { GCSFilter::Element element(32); element[0] = static_cast<unsigned char>(i); element[1] = static_cast<unsigned char>(i >> 8); elements.insert(std::move(element)); } uint64_t siphash_k0 = 0; bench.batch(elements.size()).unit("elem").run([&] { GCSFilter filter({siphash_k0, 0, 20, 1 << 20}, elements); siphash_k0++; }); } static void MatchGCSFilter(benchmark::Bench& bench) { GCSFilter::ElementSet elements; for (int i = 0; i < 10000; ++i) { GCSFilter::Element element(32); element[0] = static_cast<unsigned char>(i); element[1] = static_cast<unsigned char>(i >> 8); elements.insert(std::move(element)); } GCSFilter filter({0, 0, 20, 1 << 20}, elements); bench.unit("elem").run([&] { filter.Match(GCSFilter::Element()); }); } BENCHMARK(ConstructGCSFilter); BENCHMARK(MatchGCSFilter);
/*************************************************************************/ /* gi_probe.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "gi_probe.h" #include "core/os/os.h" #include "mesh_instance.h" #include "voxel_light_baker.h" void GIProbeData::set_bounds(const AABB &p_bounds) { VS::get_singleton()->gi_probe_set_bounds(probe, p_bounds); } AABB GIProbeData::get_bounds() const { return VS::get_singleton()->gi_probe_get_bounds(probe); } void GIProbeData::set_cell_size(float p_size) { VS::get_singleton()->gi_probe_set_cell_size(probe, p_size); } float GIProbeData::get_cell_size() const { return VS::get_singleton()->gi_probe_get_cell_size(probe); } void GIProbeData::set_to_cell_xform(const Transform &p_xform) { VS::get_singleton()->gi_probe_set_to_cell_xform(probe, p_xform); } Transform GIProbeData::get_to_cell_xform() const { return VS::get_singleton()->gi_probe_get_to_cell_xform(probe); } void GIProbeData::set_dynamic_data(const PoolVector<int> &p_data) { VS::get_singleton()->gi_probe_set_dynamic_data(probe, p_data); } PoolVector<int> GIProbeData::get_dynamic_data() const { return VS::get_singleton()->gi_probe_get_dynamic_data(probe); } void GIProbeData::set_dynamic_range(int p_range) { VS::get_singleton()->gi_probe_set_dynamic_range(probe, p_range); } void GIProbeData::set_energy(float p_range) { VS::get_singleton()->gi_probe_set_energy(probe, p_range); } float GIProbeData::get_energy() const { return VS::get_singleton()->gi_probe_get_energy(probe); } void GIProbeData::set_bias(float p_range) { VS::get_singleton()->gi_probe_set_bias(probe, p_range); } float GIProbeData::get_bias() const { return VS::get_singleton()->gi_probe_get_bias(probe); } void GIProbeData::set_normal_bias(float p_range) { VS::get_singleton()->gi_probe_set_normal_bias(probe, p_range); } float GIProbeData::get_normal_bias() const { return VS::get_singleton()->gi_probe_get_normal_bias(probe); } void GIProbeData::set_propagation(float p_range) { VS::get_singleton()->gi_probe_set_propagation(probe, p_range); } float GIProbeData::get_propagation() const { return VS::get_singleton()->gi_probe_get_propagation(probe); } void GIProbeData::set_interior(bool p_enable) { VS::get_singleton()->gi_probe_set_interior(probe, p_enable); } bool GIProbeData::is_interior() const { return VS::get_singleton()->gi_probe_is_interior(probe); } bool GIProbeData::is_compressed() const { return VS::get_singleton()->gi_probe_is_compressed(probe); } void GIProbeData::set_compress(bool p_enable) { VS::get_singleton()->gi_probe_set_compress(probe, p_enable); } int GIProbeData::get_dynamic_range() const { return VS::get_singleton()->gi_probe_get_dynamic_range(probe); } RID GIProbeData::get_rid() const { return probe; } void GIProbeData::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bounds", "bounds"), &GIProbeData::set_bounds); ClassDB::bind_method(D_METHOD("get_bounds"), &GIProbeData::get_bounds); ClassDB::bind_method(D_METHOD("set_cell_size", "cell_size"), &GIProbeData::set_cell_size); ClassDB::bind_method(D_METHOD("get_cell_size"), &GIProbeData::get_cell_size); ClassDB::bind_method(D_METHOD("set_to_cell_xform", "to_cell_xform"), &GIProbeData::set_to_cell_xform); ClassDB::bind_method(D_METHOD("get_to_cell_xform"), &GIProbeData::get_to_cell_xform); ClassDB::bind_method(D_METHOD("set_dynamic_data", "dynamic_data"), &GIProbeData::set_dynamic_data); ClassDB::bind_method(D_METHOD("get_dynamic_data"), &GIProbeData::get_dynamic_data); ClassDB::bind_method(D_METHOD("set_dynamic_range", "dynamic_range"), &GIProbeData::set_dynamic_range); ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbeData::get_dynamic_range); ClassDB::bind_method(D_METHOD("set_energy", "energy"), &GIProbeData::set_energy); ClassDB::bind_method(D_METHOD("get_energy"), &GIProbeData::get_energy); ClassDB::bind_method(D_METHOD("set_bias", "bias"), &GIProbeData::set_bias); ClassDB::bind_method(D_METHOD("get_bias"), &GIProbeData::get_bias); ClassDB::bind_method(D_METHOD("set_normal_bias", "bias"), &GIProbeData::set_normal_bias); ClassDB::bind_method(D_METHOD("get_normal_bias"), &GIProbeData::get_normal_bias); ClassDB::bind_method(D_METHOD("set_propagation", "propagation"), &GIProbeData::set_propagation); ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbeData::get_propagation); ClassDB::bind_method(D_METHOD("set_interior", "interior"), &GIProbeData::set_interior); ClassDB::bind_method(D_METHOD("is_interior"), &GIProbeData::is_interior); ClassDB::bind_method(D_METHOD("set_compress", "compress"), &GIProbeData::set_compress); ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbeData::is_compressed); ADD_PROPERTY(PropertyInfo(Variant::AABB, "bounds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bounds", "get_bounds"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "cell_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_cell_size", "get_cell_size"); ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "to_cell_xform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_to_cell_xform", "get_to_cell_xform"); ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "dynamic_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_data", "get_dynamic_data"); ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_range", "get_dynamic_range"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_energy", "get_energy"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bias", "get_bias"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "normal_bias", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_normal_bias", "get_normal_bias"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_propagation", "get_propagation"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_interior", "is_interior"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_compress", "is_compressed"); } GIProbeData::GIProbeData() { probe = RID_PRIME(VS::get_singleton()->gi_probe_create()); } GIProbeData::~GIProbeData() { VS::get_singleton()->free(probe); } ////////////////////// ////////////////////// void GIProbe::set_probe_data(const Ref<GIProbeData> &p_data) { if (p_data.is_valid()) { VS::get_singleton()->instance_set_base(get_instance(), p_data->get_rid()); } else { VS::get_singleton()->instance_set_base(get_instance(), RID()); } probe_data = p_data; } Ref<GIProbeData> GIProbe::get_probe_data() const { return probe_data; } void GIProbe::set_subdiv(Subdiv p_subdiv) { ERR_FAIL_INDEX(p_subdiv, SUBDIV_MAX); subdiv = p_subdiv; update_gizmo(); } GIProbe::Subdiv GIProbe::get_subdiv() const { return subdiv; } void GIProbe::set_extents(const Vector3 &p_extents) { extents = p_extents; update_gizmo(); _change_notify("extents"); } Vector3 GIProbe::get_extents() const { return extents; } void GIProbe::set_dynamic_range(int p_dynamic_range) { dynamic_range = p_dynamic_range; } int GIProbe::get_dynamic_range() const { return dynamic_range; } void GIProbe::set_energy(float p_energy) { energy = p_energy; if (probe_data.is_valid()) { probe_data->set_energy(energy); } } float GIProbe::get_energy() const { return energy; } void GIProbe::set_bias(float p_bias) { bias = p_bias; if (probe_data.is_valid()) { probe_data->set_bias(bias); } } float GIProbe::get_bias() const { return bias; } void GIProbe::set_normal_bias(float p_normal_bias) { normal_bias = p_normal_bias; if (probe_data.is_valid()) { probe_data->set_normal_bias(normal_bias); } } float GIProbe::get_normal_bias() const { return normal_bias; } void GIProbe::set_propagation(float p_propagation) { propagation = p_propagation; if (probe_data.is_valid()) { probe_data->set_propagation(propagation); } } float GIProbe::get_propagation() const { return propagation; } void GIProbe::set_interior(bool p_enable) { interior = p_enable; if (probe_data.is_valid()) { probe_data->set_interior(p_enable); } } bool GIProbe::is_interior() const { return interior; } void GIProbe::set_compress(bool p_enable) { compress = p_enable; if (probe_data.is_valid()) { probe_data->set_compress(p_enable); } update_configuration_warning(); } bool GIProbe::is_compressed() const { return compress; } void GIProbe::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) { MeshInstance *mi = Object::cast_to<MeshInstance>(p_at_node); if (mi && mi->get_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT) && mi->is_visible_in_tree()) { Ref<Mesh> mesh = mi->get_mesh(); if (mesh.is_valid()) { AABB aabb = mesh->get_aabb(); Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform(); if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) { PlotMesh pm; pm.local_xform = xf; pm.mesh = mesh; for (int i = 0; i < mesh->get_surface_count(); i++) { pm.instance_materials.push_back(mi->get_surface_material(i)); } pm.override_material = mi->get_material_override(); plot_meshes.push_back(pm); } } } Spatial *s = Object::cast_to<Spatial>(p_at_node); if (s) { if (s->is_visible_in_tree()) { Array meshes = p_at_node->call("get_meshes"); for (int i = 0; i < meshes.size(); i += 2) { Transform mxf = meshes[i]; Ref<Mesh> mesh = meshes[i + 1]; if (!mesh.is_valid()) { continue; } AABB aabb = mesh->get_aabb(); Transform xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf); if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) { PlotMesh pm; pm.local_xform = xf; pm.mesh = mesh; plot_meshes.push_back(pm); } } } } for (int i = 0; i < p_at_node->get_child_count(); i++) { Node *child = p_at_node->get_child(i); _find_meshes(child, plot_meshes); } } GIProbe::BakeBeginFunc GIProbe::bake_begin_function = nullptr; GIProbe::BakeStepFunc GIProbe::bake_step_function = nullptr; GIProbe::BakeEndFunc GIProbe::bake_end_function = nullptr; void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) { static const int subdiv_value[SUBDIV_MAX] = { 7, 8, 9, 10 }; p_from_node = p_from_node ? p_from_node : get_parent(); ERR_FAIL_NULL(p_from_node); VoxelLightBaker baker; baker.begin_bake(subdiv_value[subdiv], AABB(-extents, extents * 2.0)); List<PlotMesh> mesh_list; _find_meshes(p_from_node, mesh_list); if (bake_begin_function) { bake_begin_function(mesh_list.size() + 1); } int pmc = 0; for (List<PlotMesh>::Element *E = mesh_list.front(); E; E = E->next()) { if (bake_step_function) { bake_step_function(pmc, RTR("Plotting Meshes") + " " + itos(pmc) + "/" + itos(mesh_list.size())); } pmc++; baker.plot_mesh(E->get().local_xform, E->get().mesh, E->get().instance_materials, E->get().override_material); } if (bake_step_function) { bake_step_function(pmc++, RTR("Finishing Plot")); } baker.end_bake(); //create the data for visual server PoolVector<int> data = baker.create_gi_probe_data(); if (p_create_visual_debug) { MultiMeshInstance *mmi = memnew(MultiMeshInstance); mmi->set_multimesh(baker.create_debug_multimesh()); add_child(mmi); #ifdef TOOLS_ENABLED if (is_inside_tree() && get_tree()->get_edited_scene_root() == this) { mmi->set_owner(this); } else { mmi->set_owner(get_owner()); } #else mmi->set_owner(get_owner()); #endif } else { Ref<GIProbeData> probe_data = get_probe_data(); if (probe_data.is_null()) { probe_data.instance(); } probe_data->set_bounds(AABB(-extents, extents * 2.0)); probe_data->set_cell_size(baker.get_cell_size()); probe_data->set_dynamic_data(data); probe_data->set_dynamic_range(dynamic_range); probe_data->set_energy(energy); probe_data->set_bias(bias); probe_data->set_normal_bias(normal_bias); probe_data->set_propagation(propagation); probe_data->set_interior(interior); probe_data->set_compress(compress); probe_data->set_to_cell_xform(baker.get_to_cell_space_xform()); set_probe_data(probe_data); } if (bake_end_function) { bake_end_function(); } } void GIProbe::_debug_bake() { bake(nullptr, true); } AABB GIProbe::get_aabb() const { return AABB(-extents, extents * 2); } PoolVector<Face3> GIProbe::get_faces(uint32_t p_usage_flags) const { return PoolVector<Face3>(); } String GIProbe::get_configuration_warning() const { String warning = VisualInstance::get_configuration_warning(); if (OS::get_singleton()->get_current_video_driver() == OS::VIDEO_DRIVER_GLES2) { if (warning != String()) { warning += "\n\n"; } warning += TTR("GIProbes are not supported by the GLES2 video driver.\nUse a BakedLightmap instead."); } if (is_compressed()) { if (warning != String()) { warning += "\n\n"; } warning += TTR("The GIProbe Compress property has been deprecated due to known bugs and no longer has any effect.\nTo remove this warning, disable the GIProbe's Compress property."); } return warning; } void GIProbe::_bind_methods() { ClassDB::bind_method(D_METHOD("set_probe_data", "data"), &GIProbe::set_probe_data); ClassDB::bind_method(D_METHOD("get_probe_data"), &GIProbe::get_probe_data); ClassDB::bind_method(D_METHOD("set_subdiv", "subdiv"), &GIProbe::set_subdiv); ClassDB::bind_method(D_METHOD("get_subdiv"), &GIProbe::get_subdiv); ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GIProbe::set_extents); ClassDB::bind_method(D_METHOD("get_extents"), &GIProbe::get_extents); ClassDB::bind_method(D_METHOD("set_dynamic_range", "max"), &GIProbe::set_dynamic_range); ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbe::get_dynamic_range); ClassDB::bind_method(D_METHOD("set_energy", "max"), &GIProbe::set_energy); ClassDB::bind_method(D_METHOD("get_energy"), &GIProbe::get_energy); ClassDB::bind_method(D_METHOD("set_bias", "max"), &GIProbe::set_bias); ClassDB::bind_method(D_METHOD("get_bias"), &GIProbe::get_bias); ClassDB::bind_method(D_METHOD("set_normal_bias", "max"), &GIProbe::set_normal_bias); ClassDB::bind_method(D_METHOD("get_normal_bias"), &GIProbe::get_normal_bias); ClassDB::bind_method(D_METHOD("set_propagation", "max"), &GIProbe::set_propagation); ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbe::get_propagation); ClassDB::bind_method(D_METHOD("set_interior", "enable"), &GIProbe::set_interior); ClassDB::bind_method(D_METHOD("is_interior"), &GIProbe::is_interior); ClassDB::bind_method(D_METHOD("set_compress", "enable"), &GIProbe::set_compress); ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbe::is_compressed); ClassDB::bind_method(D_METHOD("bake", "from_node", "create_visual_debug"), &GIProbe::bake, DEFVAL(Variant()), DEFVAL(false)); ClassDB::bind_method(D_METHOD("debug_bake"), &GIProbe::_debug_bake); ClassDB::set_method_flags(get_class_static(), _scs_create("debug_bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); ADD_PROPERTY(PropertyInfo(Variant::INT, "subdiv", PROPERTY_HINT_ENUM, "64,128,256,512"), "set_subdiv", "get_subdiv"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents"); ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_RANGE, "1,16,1"), "set_dynamic_range", "get_dynamic_range"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_RANGE, "0,16,0.01,or_greater"), "set_energy", "get_energy"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_propagation", "get_propagation"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0,4,0.001"), "set_bias", "get_bias"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "normal_bias", PROPERTY_HINT_RANGE, "0,4,0.001"), "set_normal_bias", "get_normal_bias"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress"), "set_compress", "is_compressed"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "GIProbeData", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE), "set_probe_data", "get_probe_data"); BIND_ENUM_CONSTANT(SUBDIV_64); BIND_ENUM_CONSTANT(SUBDIV_128); BIND_ENUM_CONSTANT(SUBDIV_256); BIND_ENUM_CONSTANT(SUBDIV_512); BIND_ENUM_CONSTANT(SUBDIV_MAX); } GIProbe::GIProbe() { subdiv = SUBDIV_128; dynamic_range = 4; energy = 1.0; bias = 1.5; normal_bias = 0.0; propagation = 0.7; extents = Vector3(10, 10, 10); interior = false; compress = false; gi_probe = RID_PRIME(VS::get_singleton()->gi_probe_create()); set_disable_scale(true); } GIProbe::~GIProbe() { VS::get_singleton()->free(gi_probe); }
#include "stdio.h" #include "vector" #include "unordered_map" #include "set" using namespace std; class WordFilter { public: unordered_map<string, set<int>> pre_map; unordered_map<string, set<int>> suf_map; vector<string> words; WordFilter(vector<string> &words) { this->words = words; int size = words.size(); for (size_t i = 0; i < size; i++) { auto w = words[i]; int wsize = w.size(); for (int j = 0; j < wsize; j++) { pre_map[w.substr(0, j + 1)].insert(i); } for (int j = wsize-1; j >= 0;j--) { suf_map[w.substr(j, wsize-j)].insert(i); } } } int f(string prefix, string suffix) { auto& v1 = pre_map[prefix]; auto& v2 = suf_map[suffix]; int max = -1; if(prefix.empty() && !suffix.empty()) { if(v2.size()>0){ max = *(--v2.end()); } } else if(!prefix.empty() && suffix.empty()) { if(v1.size()>0){ max = *(--v1.end()); } } else if(!prefix.empty() && !suffix.empty()) { for (auto &k : v1) { auto t = v2.find(k); if (t != v2.end()) { if (max < *t) { max = *t; } } } } return max; } }; int main(int argc, char const *argv[]) { WordFilter s(vector<string>({"pop"})); printf("%d\n", s.f("", "op")); printf("%d\n", s.f("", "p")); printf("%d\n", s.f("", "")); return 0; }
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <legacy/graph_tools.hpp> #include "gna_graph_tools.hpp" #include "gna_plugin_log.hpp" #include "layers/gna_layer_info.hpp" namespace GNAPluginNS { /** * @brief returns a pointer to 2D reshaped data to satisfy maximum size of zero dimension * @param input a pointer to data to be reshaped * @param maxZeroDimSize the maximum size of zero dimension */ inline InferenceEngine::DataPtr Get2DReshapedData(InferenceEngine::DataPtr input, size_t minZeroDimSize, size_t maxZeroDimSize) { IE_ASSERT(minZeroDimSize > 0); auto dims = input->getDims(); uint32_t numRowsIn = InferenceEngine::details::product(begin(dims), end(dims)); uint32_t numColumnsIn = 1; // Rows number should be 8-elements aligned if (numRowsIn % 8 == 0) { if (dims.size() >= 2 || dims[0] >= maxZeroDimSize) { size_t indexDivide = maxZeroDimSize; while (indexDivide > minZeroDimSize) { if ((numRowsIn / 8) % indexDivide == 0) break; --indexDivide; } numRowsIn /= indexDivide; numColumnsIn = indexDivide; } } size_t newDimsSize = (dims.size() > 1) ? dims.size() : 2; InferenceEngine::Layout new_layout = (dims.size() > 1) ? input->getLayout() : InferenceEngine::Layout::NC; InferenceEngine::SizeVector newDims(newDimsSize, 1); newDims[0] = numColumnsIn; newDims[1] = numRowsIn; return std::make_shared<InferenceEngine::Data>(input->getName(), InferenceEngine::TensorDesc(input->getPrecision(), newDims, new_layout)); } /** * @brief returns true if input data should be 2D reshaped for the layer * @param layer */ inline bool HasTo2DReshapeData(InferenceEngine::CNNLayerPtr layer) { if (GNAPluginNS::LayerInfo(layer).isPower() || GNAPluginNS::LayerInfo(layer).isCopy()) return true; if (!GNAPluginNS::LayerInfo(layer).isSyntheticScaleShift()) return false; // Don't reshape the first dnn layer since it breaks groups recognition auto prevLayer = InferenceEngine::CNNNetPrevLayerSkipCertain(layer, 0, [](InferenceEngine::CNNLayerPtr ptr) { return LayerInfo(ptr).isNonValuesChangable(); }); IE_ASSERT(prevLayer != nullptr); if (LayerInfo(prevLayer).isInput()) return false; // Don't reshape diagonallayers with bias connection return !GNAPluginNS::LayerInfo(getCreatorLayer(layer->insData.front().lock()).lock()).has32BOutput(); } } // namespace GNAPluginNS
// Copyright (c) 2011-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. #define BOOST_TEST_MODULE SapoCoin Test Suite #include <banman.h> #include <net.h> #include <memory> #include <boost/test/unit_test.hpp> std::unique_ptr<CConnman> g_connman; std::unique_ptr<BanMan> g_banman; [[noreturn]] void Shutdown(void* parg) { std::exit(EXIT_SUCCESS); } [[noreturn]] void StartShutdown() { std::exit(EXIT_SUCCESS); } bool ShutdownRequested() { return false; }
// WNetTesterDlg.cpp : implementation file // #include "stdafx.h" #include "WNetTester.h" #include "WNetTesterDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CWNetTesterDlg dialog CWNetTesterDlg::CWNetTesterDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_WNETTESTER_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CWNetTesterDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_BROWSER, m_ctrlBrowserButton); DDX_Control(pDX, IDC_VALUE, m_ctrlValueEdit); DDX_Control(pDX, IDC_INFOLIST, m_ctrlInfoList); } BEGIN_MESSAGE_MAP(CWNetTesterDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BROWSER, &CWNetTesterDlg::OnBnClickedBrowser) END_MESSAGE_MAP() // CWNetTesterDlg message handlers BOOL CWNetTesterDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CWNetTesterDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CWNetTesterDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CWNetTesterDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CWNetTesterDlg::OnBnClickedBrowser() { // TODO: Add your control notification handler code here wnet.OpenBrowser(this); }
/* [auto_generated] boost/numeric/odeint/iterator/adaptive_time_iterator.hpp [begin_description] Iterator for iterating throught the solution of an ODE with adaptive step size. The dereferenced types containes also the time. [end_description] Copyright 2012-2013 Karsten Ahnert Copyright 2012-2013 Mario Mulansky 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) */ #ifndef BOOST_NUMERIC_ODEINT_ITERATOR_ADAPTIVE_TIME_ITERATOR_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_ITERATOR_ADAPTIVE_TIME_ITERATOR_HPP_INCLUDED #include <boost/numeric/odeint/stepper/stepper_categories.hpp> #include <boost/numeric/odeint/util/stepper_traits.hpp> #include <boost/numeric/odeint/iterator/impl/adaptive_iterator_impl.hpp> namespace boost { namespace numeric { namespace odeint { /* use the adaptive_iterator_impl with the right tags */ template< class Stepper , class System , class State #ifndef DOXYGEN_SKIP , class StepperTag = typename base_tag< typename traits::stepper_category< Stepper >::type >::type #endif > class adaptive_time_iterator : public adaptive_iterator_impl< adaptive_time_iterator< Stepper , System , State , StepperTag > , Stepper , System , State , detail::ode_state_time_iterator_tag , StepperTag > { typedef typename traits::time_type< Stepper >::type time_type; typedef adaptive_time_iterator< Stepper , System , State , StepperTag > iterator_type; public: adaptive_time_iterator( Stepper stepper , System sys , State &s , time_type t_start , time_type t_end , time_type dt ) : adaptive_iterator_impl< iterator_type , Stepper , System , State , detail::ode_state_time_iterator_tag , StepperTag >( stepper , sys , s , t_start , t_end , dt ) {} adaptive_time_iterator( Stepper stepper , System sys , State &s ) : adaptive_iterator_impl< iterator_type , Stepper , System , State , detail::ode_state_time_iterator_tag , StepperTag >( stepper , sys , s ) {} }; template< class Stepper , class System , class State > adaptive_time_iterator< Stepper , System , State > make_adaptive_time_iterator_begin( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t_start , typename traits::time_type< Stepper >::type t_end , typename traits::time_type< Stepper >::type dt ) { return adaptive_time_iterator< Stepper , System , State >( stepper , system , x , t_start , t_end , dt ); } template< class Stepper , class System , class State > adaptive_time_iterator< Stepper , System , State > make_adaptive_time_iterator_end( Stepper stepper , System system , State &x ) { return adaptive_time_iterator< Stepper , System , State >( stepper , system , x ); } template< class Stepper , class System , class State > std::pair< adaptive_time_iterator< Stepper , System , State > , adaptive_time_iterator< Stepper , System , State > > make_adaptive_time_range( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t_start , typename traits::time_type< Stepper >::type t_end , typename traits::time_type< Stepper >::type dt ) { return std::make_pair( adaptive_time_iterator< Stepper , System , State >( stepper , system , x , t_start , t_end , dt ) , adaptive_time_iterator< Stepper , System , State >( stepper , system , x ) ); } /** * \class adaptive_time_iterator * * \brief ODE Iterator with adaptive step size. The value type of this iterator is a std::pair containing state and time. * * Implements an iterator representing the solution of an ODE from t_start * to t_end evaluated at steps with an adaptive step size dt. * After each iteration the iterator dereferences to a pair containing state * and time at the next time point t+dt where dt is controlled by the stepper. * This iterator can be used with ControlledSteppers and * DenseOutputSteppers and it always makes use of the all the given steppers * capabilities. A for_each over such an iterator range behaves similar to * the integrate_adaptive routine. * * adaptive_iterator is a model of single-pass iterator. * * The value type of this iterator is a std::pair of state and time of the stepper. * * \tparam Stepper The stepper type which should be used during the iteration. * \tparam System The type of the system function (ODE) which should be solved. * \tparam State The state type of the ODE. */ /** * \fn make_adaptive_time_iterator_begin( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t_start , typename traits::time_type< Stepper >::type t_end , typename traits::time_type< Stepper >::type dt ) * * \brief Factory function for adaptive_time_iterator. Constructs a begin iterator. * * \param stepper The stepper to use during the iteration. * \param system The system function (ODE) to solve. * \param x The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration. * \param t_start The initial time. * \param t_end The end time, at which the iteration should stop. * \param dt The initial time step. * \returns The adaptive time iterator. */ /** * \fn make_adaptive_time_iterator_end( Stepper stepper , System system , State &x ) * \brief Factory function for adaptive_time_iterator. Constructs a end iterator. * * \param stepper The stepper to use during the iteration. * \param system The system function (ODE) to solve. * \param x The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration. * \returns The adaptive time iterator. */ /** * \fn make_adaptive_time_range( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t_start , typename traits::time_type< Stepper >::type t_end , typename traits::time_type< Stepper >::type dt ) * * \brief Factory function to construct a single pass range of adaptive time iterators. A range is here a pair of adaptive_time_iterators. * * \param stepper The stepper to use during the iteration. * \param system The system function (ODE) to solve. * \param x The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration. * \param t_start The initial time. * \param t_end The end time, at which the iteration should stop. * \param dt The initial time step. * \returns The adaptive time range. */ } // namespace odeint } // namespace numeric } // namespace boost #endif // BOOST_NUMERIC_ODEINT_ITERATOR_ADAPTIVE_TIME_ITERATOR_HPP_INCLUDED
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: jschorr@google.com (Joseph Schorr) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/text_format.h> #include <math.h> #include <stdlib.h> #include <limits> #include <memory> #ifndef _SHARED_PTR_H #include <google/protobuf/stubs/shared_ptr.h> #endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_mset.pb.h> #include <google/protobuf/unittest_mset_wire_format.pb.h> #include <google/protobuf/io/tokenizer.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/stubs/mathlimits.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> namespace google { namespace protobuf { // Can't use an anonymous namespace here due to brokenness of Tru64 compiler. namespace text_format_unittest { // A basic string with different escapable characters for testing. const string kEscapeTestString = "\"A string with ' characters \n and \r newlines and \t tabs and \001 " "slashes \\ and multiple spaces"; // A representation of the above string with all the characters escaped. const string kEscapeTestStringEscaped = "\"\\\"A string with \\' characters \\n and \\r newlines " "and \\t tabs and \\001 slashes \\\\ and multiple spaces\""; class TextFormatTest : public testing::Test { public: static void SetUpTestCase() { GOOGLE_CHECK_OK(File::GetContents( TestSourceDir() + "/google/protobuf/" "testdata/text_format_unittest_data_oneof_implemented.txt", &static_proto_debug_string_, true)); } TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {} protected: // Debug string read from text_format_unittest_data.txt. const string proto_debug_string_; unittest::TestAllTypes proto_; private: static string static_proto_debug_string_; }; string TextFormatTest::static_proto_debug_string_; class TextFormatExtensionsTest : public testing::Test { public: static void SetUpTestCase() { GOOGLE_CHECK_OK(File::GetContents(TestSourceDir() + "/google/protobuf/testdata/" "text_format_unittest_extensions_data.txt", &static_proto_debug_string_, true)); } TextFormatExtensionsTest() : proto_debug_string_(static_proto_debug_string_) {} protected: // Debug string read from text_format_unittest_data.txt. const string proto_debug_string_; unittest::TestAllExtensions proto_; private: static string static_proto_debug_string_; }; string TextFormatExtensionsTest::static_proto_debug_string_; TEST_F(TextFormatTest, Basic) { TestUtil::SetAllFields(&proto_); EXPECT_EQ(proto_debug_string_, proto_.DebugString()); } TEST_F(TextFormatExtensionsTest, Extensions) { TestUtil::SetAllExtensions(&proto_); EXPECT_EQ(proto_debug_string_, proto_.DebugString()); } TEST_F(TextFormatTest, ShortDebugString) { proto_.set_optional_int32(1); proto_.set_optional_string("hello"); proto_.mutable_optional_nested_message()->set_bb(2); proto_.mutable_optional_foreign_message(); EXPECT_EQ("optional_int32: 1 optional_string: \"hello\" " "optional_nested_message { bb: 2 } " "optional_foreign_message { }", proto_.ShortDebugString()); } TEST_F(TextFormatTest, ShortPrimitiveRepeateds) { proto_.set_optional_int32(123); proto_.add_repeated_int32(456); proto_.add_repeated_int32(789); proto_.add_repeated_string("foo"); proto_.add_repeated_string("bar"); proto_.add_repeated_nested_message()->set_bb(2); proto_.add_repeated_nested_message()->set_bb(3); proto_.add_repeated_nested_enum(unittest::TestAllTypes::FOO); proto_.add_repeated_nested_enum(unittest::TestAllTypes::BAR); TextFormat::Printer printer; printer.SetUseShortRepeatedPrimitives(true); string text; printer.PrintToString(proto_, &text); EXPECT_EQ("optional_int32: 123\n" "repeated_int32: [456, 789]\n" "repeated_string: \"foo\"\n" "repeated_string: \"bar\"\n" "repeated_nested_message {\n bb: 2\n}\n" "repeated_nested_message {\n bb: 3\n}\n" "repeated_nested_enum: [FOO, BAR]\n", text); // Try in single-line mode. printer.SetSingleLineMode(true); printer.PrintToString(proto_, &text); EXPECT_EQ("optional_int32: 123 " "repeated_int32: [456, 789] " "repeated_string: \"foo\" " "repeated_string: \"bar\" " "repeated_nested_message { bb: 2 } " "repeated_nested_message { bb: 3 } " "repeated_nested_enum: [FOO, BAR] ", text); } TEST_F(TextFormatTest, StringEscape) { // Set the string value to test. proto_.set_optional_string(kEscapeTestString); // Get the DebugString from the proto. string debug_string = proto_.DebugString(); string utf8_debug_string = proto_.Utf8DebugString(); // Hardcode a correct value to test against. string correct_string = "optional_string: " + kEscapeTestStringEscaped + "\n"; // Compare. EXPECT_EQ(correct_string, debug_string); // UTF-8 string is the same as non-UTF-8 because // the protocol buffer contains no UTF-8 text. EXPECT_EQ(correct_string, utf8_debug_string); string expected_short_debug_string = "optional_string: " + kEscapeTestStringEscaped; EXPECT_EQ(expected_short_debug_string, proto_.ShortDebugString()); } TEST_F(TextFormatTest, Utf8DebugString) { // Set the string value to test. proto_.set_optional_string("\350\260\267\346\255\214"); proto_.set_optional_bytes("\350\260\267\346\255\214"); // Get the DebugString from the proto. string debug_string = proto_.DebugString(); string utf8_debug_string = proto_.Utf8DebugString(); // Hardcode a correct value to test against. string correct_utf8_string = "optional_string: " "\"\350\260\267\346\255\214\"" "\n" "optional_bytes: " "\"\\350\\260\\267\\346\\255\\214\"" "\n"; string correct_string = "optional_string: " "\"\\350\\260\\267\\346\\255\\214\"" "\n" "optional_bytes: " "\"\\350\\260\\267\\346\\255\\214\"" "\n"; // Compare. EXPECT_EQ(correct_utf8_string, utf8_debug_string); EXPECT_EQ(correct_string, debug_string); } TEST_F(TextFormatTest, PrintUnknownFields) { // Test printing of unknown fields in a message. unittest::TestEmptyMessage message; UnknownFieldSet* unknown_fields = message.mutable_unknown_fields(); unknown_fields->AddVarint(5, 1); unknown_fields->AddFixed32(5, 2); unknown_fields->AddFixed64(5, 3); unknown_fields->AddLengthDelimited(5, "4"); unknown_fields->AddGroup(5)->AddVarint(10, 5); unknown_fields->AddVarint(8, 1); unknown_fields->AddVarint(8, 2); unknown_fields->AddVarint(8, 3); EXPECT_EQ( "5: 1\n" "5: 0x00000002\n" "5: 0x0000000000000003\n" "5: \"4\"\n" "5 {\n" " 10: 5\n" "}\n" "8: 1\n" "8: 2\n" "8: 3\n", message.DebugString()); } TEST_F(TextFormatTest, PrintUnknownFieldsHidden) { // Test printing of unknown fields in a message when suppressed. unittest::OneString message; message.set_data("data"); UnknownFieldSet* unknown_fields = message.mutable_unknown_fields(); unknown_fields->AddVarint(5, 1); unknown_fields->AddFixed32(5, 2); unknown_fields->AddFixed64(5, 3); unknown_fields->AddLengthDelimited(5, "4"); unknown_fields->AddGroup(5)->AddVarint(10, 5); unknown_fields->AddVarint(8, 1); unknown_fields->AddVarint(8, 2); unknown_fields->AddVarint(8, 3); TextFormat::Printer printer; printer.SetHideUnknownFields(true); string output; printer.PrintToString(message, &output); EXPECT_EQ("data: \"data\"\n", output); } TEST_F(TextFormatTest, PrintUnknownMessage) { // Test heuristic printing of messages in an UnknownFieldSet. protobuf_unittest::TestAllTypes message; // Cases which should not be interpreted as sub-messages. // 'a' is a valid FIXED64 tag, so for the string to be parseable as a message // it should be followed by 8 bytes. Since this string only has two // subsequent bytes, it should be treated as a string. message.add_repeated_string("abc"); // 'd' happens to be a valid ENDGROUP tag. So, // UnknownFieldSet::MergeFromCodedStream() will successfully parse "def", but // the ConsumedEntireMessage() check should fail. message.add_repeated_string("def"); // A zero-length string should never be interpreted as a message even though // it is technically valid as one. message.add_repeated_string(""); // Case which should be interpreted as a sub-message. // An actual nested message with content should always be interpreted as a // nested message. message.add_repeated_nested_message()->set_bb(123); string data; message.SerializeToString(&data); string text; UnknownFieldSet unknown_fields; EXPECT_TRUE(unknown_fields.ParseFromString(data)); EXPECT_TRUE(TextFormat::PrintUnknownFieldsToString(unknown_fields, &text)); EXPECT_EQ( "44: \"abc\"\n" "44: \"def\"\n" "44: \"\"\n" "48 {\n" " 1: 123\n" "}\n", text); } TEST_F(TextFormatTest, PrintMessageWithIndent) { // Test adding an initial indent to printing. protobuf_unittest::TestAllTypes message; message.add_repeated_string("abc"); message.add_repeated_string("def"); message.add_repeated_nested_message()->set_bb(123); string text; TextFormat::Printer printer; printer.SetInitialIndentLevel(1); EXPECT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( " repeated_string: \"abc\"\n" " repeated_string: \"def\"\n" " repeated_nested_message {\n" " bb: 123\n" " }\n", text); } TEST_F(TextFormatTest, PrintMessageSingleLine) { // Test printing a message on a single line. protobuf_unittest::TestAllTypes message; message.add_repeated_string("abc"); message.add_repeated_string("def"); message.add_repeated_nested_message()->set_bb(123); string text; TextFormat::Printer printer; printer.SetInitialIndentLevel(1); printer.SetSingleLineMode(true); EXPECT_TRUE(printer.PrintToString(message, &text)); EXPECT_EQ( " repeated_string: \"abc\" repeated_string: \"def\" " "repeated_nested_message { bb: 123 } ", text); } TEST_F(TextFormatTest, PrintBufferTooSmall) { // Test printing a message to a buffer that is too small. protobuf_unittest::TestAllTypes message; message.add_repeated_string("abc"); message.add_repeated_string("def"); char buffer[1] = ""; io::ArrayOutputStream output_stream(buffer, 1); EXPECT_FALSE(TextFormat::Print(message, &output_stream)); EXPECT_EQ(buffer[0], 'r'); EXPECT_EQ(output_stream.ByteCount(), 1); } // A printer that appends 'u' to all unsigned int32. class CustomUInt32FieldValuePrinter : public TextFormat::FieldValuePrinter { public: virtual string PrintUInt32(uint32 val) const { return StrCat(FieldValuePrinter::PrintUInt32(val), "u"); } }; TEST_F(TextFormatTest, DefaultCustomFieldPrinter) { protobuf_unittest::TestAllTypes message; message.set_optional_uint32(42); message.add_repeated_uint32(1); message.add_repeated_uint32(2); message.add_repeated_uint32(3); TextFormat::Printer printer; printer.SetDefaultFieldValuePrinter(new CustomUInt32FieldValuePrinter()); // Let's see if that works well together with the repeated primitives: printer.SetUseShortRepeatedPrimitives(true); string text; printer.PrintToString(message, &text); EXPECT_EQ("optional_uint32: 42u\nrepeated_uint32: [1u, 2u, 3u]\n", text); } class CustomInt32FieldValuePrinter : public TextFormat::FieldValuePrinter { public: virtual string PrintInt32(int32 val) const { return StrCat("value-is(", FieldValuePrinter::PrintInt32(val), ")"); } }; TEST_F(TextFormatTest, FieldSpecificCustomPrinter) { protobuf_unittest::TestAllTypes message; message.set_optional_int32(42); // This will be handled by our Printer. message.add_repeated_int32(42); // This will be printed as number. TextFormat::Printer printer; EXPECT_TRUE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), new CustomInt32FieldValuePrinter())); string text; printer.PrintToString(message, &text); EXPECT_EQ("optional_int32: value-is(42)\nrepeated_int32: 42\n", text); } TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { protobuf_unittest::TestAllTypes message; TextFormat::Printer printer; // NULL printer. EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), NULL)); // Because registration fails, the ownership of this printer is never taken. TextFormat::FieldValuePrinter my_field_printer; // NULL field EXPECT_FALSE(printer.RegisterFieldValuePrinter(NULL, &my_field_printer)); } class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter { public: virtual string PrintInt32(int32 v) const { return StrCat(FieldValuePrinter::PrintInt32(v), " # x", strings::Hex(v)); } virtual string PrintMessageStart(const Message& message, int field_index, int field_count, bool single_line_mode) const { if (single_line_mode) { return " { "; } return StrCat( " { # ", message.GetDescriptor()->name(), ": ", field_index, "\n"); } }; TEST_F(TextFormatTest, CustomPrinterForComments) { protobuf_unittest::TestAllTypes message; message.mutable_optional_nested_message(); message.mutable_optional_import_message()->set_d(42); message.add_repeated_nested_message(); message.add_repeated_nested_message(); message.add_repeated_import_message()->set_d(43); message.add_repeated_import_message()->set_d(44); TextFormat::Printer printer; CustomMessageFieldValuePrinter my_field_printer; printer.SetDefaultFieldValuePrinter(new CustomMessageFieldValuePrinter()); string text; printer.PrintToString(message, &text); EXPECT_EQ( "optional_nested_message { # NestedMessage: -1\n" "}\n" "optional_import_message { # ImportMessage: -1\n" " d: 42 # x2a\n" "}\n" "repeated_nested_message { # NestedMessage: 0\n" "}\n" "repeated_nested_message { # NestedMessage: 1\n" "}\n" "repeated_import_message { # ImportMessage: 0\n" " d: 43 # x2b\n" "}\n" "repeated_import_message { # ImportMessage: 1\n" " d: 44 # x2c\n" "}\n", text); } class CustomMultilineCommentPrinter : public TextFormat::FieldValuePrinter { public: virtual string PrintMessageStart(const Message& message, int field_index, int field_count, bool single_line_comment) const { return StrCat(" { # 1\n", " # 2\n"); } }; TEST_F(TextFormatTest, CustomPrinterForMultilineComments) { protobuf_unittest::TestAllTypes message; message.mutable_optional_nested_message(); message.mutable_optional_import_message()->set_d(42); TextFormat::Printer printer; CustomMessageFieldValuePrinter my_field_printer; printer.SetDefaultFieldValuePrinter(new CustomMultilineCommentPrinter()); string text; printer.PrintToString(message, &text); EXPECT_EQ( "optional_nested_message { # 1\n" " # 2\n" "}\n" "optional_import_message { # 1\n" " # 2\n" " d: 42\n" "}\n", text); } TEST_F(TextFormatTest, ParseBasic) { io::ArrayInputStream input_stream(proto_debug_string_.data(), proto_debug_string_.size()); TextFormat::Parse(&input_stream, &proto_); TestUtil::ExpectAllFieldsSet(proto_); } TEST_F(TextFormatExtensionsTest, ParseExtensions) { io::ArrayInputStream input_stream(proto_debug_string_.data(), proto_debug_string_.size()); TextFormat::Parse(&input_stream, &proto_); TestUtil::ExpectAllExtensionsSet(proto_); } TEST_F(TextFormatTest, ParseEnumFieldFromNumber) { // Create a parse string with a numerical value for an enum field. string parse_string = strings::Substitute("optional_nested_enum: $0", unittest::TestAllTypes::BAZ); EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto_)); EXPECT_TRUE(proto_.has_optional_nested_enum()); EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.optional_nested_enum()); } TEST_F(TextFormatTest, ParseEnumFieldFromNegativeNumber) { ASSERT_LT(unittest::SPARSE_E, 0); string parse_string = strings::Substitute("sparse_enum: $0", unittest::SPARSE_E); unittest::SparseEnumMessage proto; EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto)); EXPECT_TRUE(proto.has_sparse_enum()); EXPECT_EQ(unittest::SPARSE_E, proto.sparse_enum()); } TEST_F(TextFormatTest, ParseStringEscape) { // Create a parse string with escpaed characters in it. string parse_string = "optional_string: " + kEscapeTestStringEscaped + "\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(kEscapeTestString, proto_.optional_string()); } TEST_F(TextFormatTest, ParseConcatenatedString) { // Create a parse string with multiple parts on one line. string parse_string = "optional_string: \"foo\" \"bar\"\n"; io::ArrayInputStream input_stream1(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream1, &proto_); // Compare. EXPECT_EQ("foobar", proto_.optional_string()); // Create a parse string with multiple parts on separate lines. parse_string = "optional_string: \"foo\"\n" "\"bar\"\n"; io::ArrayInputStream input_stream2(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream2, &proto_); // Compare. EXPECT_EQ("foobar", proto_.optional_string()); } TEST_F(TextFormatTest, ParseFloatWithSuffix) { // Test that we can parse a floating-point value with 'f' appended to the // end. This is needed for backwards-compatibility with proto1. // Have it parse a float with the 'f' suffix. string parse_string = "optional_float: 1.0f\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(1.0, proto_.optional_float()); } TEST_F(TextFormatTest, ParseShortRepeatedForm) { string parse_string = // Mixed short-form and long-form are simply concatenated. "repeated_int32: 1\n" "repeated_int32: [456, 789]\n" "repeated_nested_enum: [ FOO ,BAR, # comment\n" " 3]\n" // Note that while the printer won't print repeated strings in short-form, // the parser will accept them. "repeated_string: [ \"foo\", 'bar' ]\n" // Repeated message "repeated_nested_message: [ { bb: 1 }, { bb : 2 }]\n" // Repeated group "RepeatedGroup [{ a: 3 },{ a: 4 }]\n"; ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_)); ASSERT_EQ(3, proto_.repeated_int32_size()); EXPECT_EQ(1, proto_.repeated_int32(0)); EXPECT_EQ(456, proto_.repeated_int32(1)); EXPECT_EQ(789, proto_.repeated_int32(2)); ASSERT_EQ(3, proto_.repeated_nested_enum_size()); EXPECT_EQ(unittest::TestAllTypes::FOO, proto_.repeated_nested_enum(0)); EXPECT_EQ(unittest::TestAllTypes::BAR, proto_.repeated_nested_enum(1)); EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.repeated_nested_enum(2)); ASSERT_EQ(2, proto_.repeated_string_size()); EXPECT_EQ("foo", proto_.repeated_string(0)); EXPECT_EQ("bar", proto_.repeated_string(1)); ASSERT_EQ(2, proto_.repeated_nested_message_size()); EXPECT_EQ(1, proto_.repeated_nested_message(0).bb()); EXPECT_EQ(2, proto_.repeated_nested_message(1).bb()); ASSERT_EQ(2, proto_.repeatedgroup_size()); EXPECT_EQ(3, proto_.repeatedgroup(0).a()); EXPECT_EQ(4, proto_.repeatedgroup(1).a()); } TEST_F(TextFormatTest, Comments) { // Test that comments are ignored. string parse_string = "optional_int32: 1 # a comment\n" "optional_int64: 2 # another comment"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(1, proto_.optional_int32()); EXPECT_EQ(2, proto_.optional_int64()); } TEST_F(TextFormatTest, OptionalColon) { // Test that we can place a ':' after the field name of a nested message, // even though we don't have to. string parse_string = "optional_nested_message: { bb: 1}\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_TRUE(proto_.has_optional_nested_message()); EXPECT_EQ(1, proto_.optional_nested_message().bb()); } // Some platforms (e.g. Windows) insist on padding the exponent to three // digits when one or two would be just fine. static string RemoveRedundantZeros(string text) { text = StringReplace(text, "e+0", "e+", true); text = StringReplace(text, "e-0", "e-", true); return text; } TEST_F(TextFormatTest, PrintExotic) { unittest::TestAllTypes message; // Note: In C, a negative integer literal is actually the unary negation // operator being applied to a positive integer literal, and // 9223372036854775808 is outside the range of int64. However, it is not // outside the range of uint64. Confusingly, this means that everything // works if we make the literal unsigned, even though we are negating it. message.add_repeated_int64(-GOOGLE_ULONGLONG(9223372036854775808)); message.add_repeated_uint64(GOOGLE_ULONGLONG(18446744073709551615)); message.add_repeated_double(123.456); message.add_repeated_double(1.23e21); message.add_repeated_double(1.23e-18); message.add_repeated_double(std::numeric_limits<double>::infinity()); message.add_repeated_double(-std::numeric_limits<double>::infinity()); message.add_repeated_double(std::numeric_limits<double>::quiet_NaN()); message.add_repeated_string(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12)); // Fun story: We used to use 1.23e22 instead of 1.23e21 above, but this // seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of // the value differed from strtod()'s parsing. That is to say, the // following assertion fails on MinGW: // assert(1.23e22 == strtod("1.23e22", NULL)); // As a result, SimpleDtoa() would print the value as // "1.2300000000000001e+22" to make sure strtod() produce the exact same // result. Our goal is to test runtime parsing, not compile-time parsing, // so this wasn't our problem. It was found that using 1.23e21 did not // have this problem, so we switched to that instead. EXPECT_EQ( "repeated_int64: -9223372036854775808\n" "repeated_uint64: 18446744073709551615\n" "repeated_double: 123.456\n" "repeated_double: 1.23e+21\n" "repeated_double: 1.23e-18\n" "repeated_double: inf\n" "repeated_double: -inf\n" "repeated_double: nan\n" "repeated_string: \"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n", RemoveRedundantZeros(message.DebugString())); } TEST_F(TextFormatTest, PrintFloatPrecision) { unittest::TestAllTypes message; message.add_repeated_float(1.2); message.add_repeated_float(1.23); message.add_repeated_float(1.234); message.add_repeated_float(1.2345); message.add_repeated_float(1.23456); message.add_repeated_float(1.2e10); message.add_repeated_float(1.23e10); message.add_repeated_float(1.234e10); message.add_repeated_float(1.2345e10); message.add_repeated_float(1.23456e10); message.add_repeated_double(1.2); message.add_repeated_double(1.23); message.add_repeated_double(1.234); message.add_repeated_double(1.2345); message.add_repeated_double(1.23456); message.add_repeated_double(1.234567); message.add_repeated_double(1.2345678); message.add_repeated_double(1.23456789); message.add_repeated_double(1.234567898); message.add_repeated_double(1.2345678987); message.add_repeated_double(1.23456789876); message.add_repeated_double(1.234567898765); message.add_repeated_double(1.2345678987654); message.add_repeated_double(1.23456789876543); message.add_repeated_double(1.2e100); message.add_repeated_double(1.23e100); message.add_repeated_double(1.234e100); message.add_repeated_double(1.2345e100); message.add_repeated_double(1.23456e100); message.add_repeated_double(1.234567e100); message.add_repeated_double(1.2345678e100); message.add_repeated_double(1.23456789e100); message.add_repeated_double(1.234567898e100); message.add_repeated_double(1.2345678987e100); message.add_repeated_double(1.23456789876e100); message.add_repeated_double(1.234567898765e100); message.add_repeated_double(1.2345678987654e100); message.add_repeated_double(1.23456789876543e100); EXPECT_EQ( "repeated_float: 1.2\n" "repeated_float: 1.23\n" "repeated_float: 1.234\n" "repeated_float: 1.2345\n" "repeated_float: 1.23456\n" "repeated_float: 1.2e+10\n" "repeated_float: 1.23e+10\n" "repeated_float: 1.234e+10\n" "repeated_float: 1.2345e+10\n" "repeated_float: 1.23456e+10\n" "repeated_double: 1.2\n" "repeated_double: 1.23\n" "repeated_double: 1.234\n" "repeated_double: 1.2345\n" "repeated_double: 1.23456\n" "repeated_double: 1.234567\n" "repeated_double: 1.2345678\n" "repeated_double: 1.23456789\n" "repeated_double: 1.234567898\n" "repeated_double: 1.2345678987\n" "repeated_double: 1.23456789876\n" "repeated_double: 1.234567898765\n" "repeated_double: 1.2345678987654\n" "repeated_double: 1.23456789876543\n" "repeated_double: 1.2e+100\n" "repeated_double: 1.23e+100\n" "repeated_double: 1.234e+100\n" "repeated_double: 1.2345e+100\n" "repeated_double: 1.23456e+100\n" "repeated_double: 1.234567e+100\n" "repeated_double: 1.2345678e+100\n" "repeated_double: 1.23456789e+100\n" "repeated_double: 1.234567898e+100\n" "repeated_double: 1.2345678987e+100\n" "repeated_double: 1.23456789876e+100\n" "repeated_double: 1.234567898765e+100\n" "repeated_double: 1.2345678987654e+100\n" "repeated_double: 1.23456789876543e+100\n", RemoveRedundantZeros(message.DebugString())); } TEST_F(TextFormatTest, AllowPartial) { unittest::TestRequired message; TextFormat::Parser parser; parser.AllowPartialMessage(true); EXPECT_TRUE(parser.ParseFromString("a: 1", &message)); EXPECT_EQ(1, message.a()); EXPECT_FALSE(message.has_b()); EXPECT_FALSE(message.has_c()); } TEST_F(TextFormatTest, ParseExotic) { unittest::TestAllTypes message; ASSERT_TRUE(TextFormat::ParseFromString( "repeated_int32: -1\n" "repeated_int32: -2147483648\n" "repeated_int64: -1\n" "repeated_int64: -9223372036854775808\n" "repeated_uint32: 4294967295\n" "repeated_uint32: 2147483648\n" "repeated_uint64: 18446744073709551615\n" "repeated_uint64: 9223372036854775808\n" "repeated_double: 123.0\n" "repeated_double: 123.5\n" "repeated_double: 0.125\n" "repeated_double: 1.23E17\n" "repeated_double: 1.235E+22\n" "repeated_double: 1.235e-18\n" "repeated_double: 123.456789\n" "repeated_double: inf\n" "repeated_double: Infinity\n" "repeated_double: -inf\n" "repeated_double: -Infinity\n" "repeated_double: nan\n" "repeated_double: NaN\n" "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n", &message)); ASSERT_EQ(2, message.repeated_int32_size()); EXPECT_EQ(-1, message.repeated_int32(0)); // Note: In C, a negative integer literal is actually the unary negation // operator being applied to a positive integer literal, and 2147483648 is // outside the range of int32. However, it is not outside the range of // uint32. Confusingly, this means that everything works if we make the // literal unsigned, even though we are negating it. EXPECT_EQ(-2147483648u, message.repeated_int32(1)); ASSERT_EQ(2, message.repeated_int64_size()); EXPECT_EQ(-1, message.repeated_int64(0)); // Note: In C, a negative integer literal is actually the unary negation // operator being applied to a positive integer literal, and // 9223372036854775808 is outside the range of int64. However, it is not // outside the range of uint64. Confusingly, this means that everything // works if we make the literal unsigned, even though we are negating it. EXPECT_EQ(-GOOGLE_ULONGLONG(9223372036854775808), message.repeated_int64(1)); ASSERT_EQ(2, message.repeated_uint32_size()); EXPECT_EQ(4294967295u, message.repeated_uint32(0)); EXPECT_EQ(2147483648u, message.repeated_uint32(1)); ASSERT_EQ(2, message.repeated_uint64_size()); EXPECT_EQ(GOOGLE_ULONGLONG(18446744073709551615), message.repeated_uint64(0)); EXPECT_EQ(GOOGLE_ULONGLONG(9223372036854775808), message.repeated_uint64(1)); ASSERT_EQ(13, message.repeated_double_size()); EXPECT_EQ(123.0 , message.repeated_double(0)); EXPECT_EQ(123.5 , message.repeated_double(1)); EXPECT_EQ(0.125 , message.repeated_double(2)); EXPECT_EQ(1.23E17 , message.repeated_double(3)); EXPECT_EQ(1.235E22 , message.repeated_double(4)); EXPECT_EQ(1.235E-18 , message.repeated_double(5)); EXPECT_EQ(123.456789, message.repeated_double(6)); EXPECT_EQ(message.repeated_double(7), numeric_limits<double>::infinity()); EXPECT_EQ(message.repeated_double(8), numeric_limits<double>::infinity()); EXPECT_EQ(message.repeated_double(9), -numeric_limits<double>::infinity()); EXPECT_EQ(message.repeated_double(10), -numeric_limits<double>::infinity()); EXPECT_TRUE(MathLimits<double>::IsNaN(message.repeated_double(11))); EXPECT_TRUE(MathLimits<double>::IsNaN(message.repeated_double(12))); // Note: Since these string literals have \0's in them, we must explicitly // pass their sizes to string's constructor. ASSERT_EQ(1, message.repeated_string_size()); EXPECT_EQ(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12), message.repeated_string(0)); } TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { protobuf_unittest::TestFieldOrderings message; // Fields are listed in index order instead of field number. message.set_my_string("Test String"); // Field number 11 message.set_my_int(12345); // Field number 1 message.set_my_float(0.999); // Field number 101 TextFormat::Printer printer; string text; // By default, print in field number order. printer.PrintToString(message, &text); EXPECT_EQ("my_int: 12345\nmy_string: \"Test String\"\nmy_float: 0.999\n", text); // Print in index order. printer.SetPrintMessageFieldsInIndexOrder(true); printer.PrintToString(message, &text); EXPECT_EQ("my_string: \"Test String\"\nmy_int: 12345\nmy_float: 0.999\n", text); } class TextFormatParserTest : public testing::Test { protected: void ExpectFailure(const string& input, const string& message, int line, int col) { google::protobuf::scoped_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes); ExpectFailure(input, message, line, col, proto.get()); } void ExpectFailure(const string& input, const string& message, int line, int col, Message* proto) { ExpectMessage(input, message, line, col, proto, false); } void ExpectMessage(const string& input, const string& message, int line, int col, Message* proto, bool expected_result) { TextFormat::Parser parser; MockErrorCollector error_collector; parser.RecordErrorsTo(&error_collector); EXPECT_EQ(expected_result, parser.ParseFromString(input, proto)) << input << " -> " << proto->DebugString(); EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) + ": " + message + "\n", error_collector.text_); } void ExpectSuccessAndTree(const string& input, Message* proto, TextFormat::ParseInfoTree* info_tree) { TextFormat::Parser parser; MockErrorCollector error_collector; parser.RecordErrorsTo(&error_collector); parser.WriteLocationsTo(info_tree); EXPECT_TRUE(parser.ParseFromString(input, proto)); } void ExpectLocation(TextFormat::ParseInfoTree* tree, const Descriptor* d, const string& field_name, int index, int line, int column) { TextFormat::ParseLocation location = tree->GetLocation( d->FindFieldByName(field_name), index); EXPECT_EQ(line, location.line); EXPECT_EQ(column, location.column); } // An error collector which simply concatenates all its errors into a big // block of text which can be checked. class MockErrorCollector : public io::ErrorCollector { public: MockErrorCollector() {} ~MockErrorCollector() {} string text_; // implements ErrorCollector ------------------------------------- void AddError(int line, int column, const string& message) { strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line + 1, column + 1, message); } void AddWarning(int line, int column, const string& message) { AddError(line, column, "WARNING:" + message); } }; }; TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); string stringData = "optional_int32: 1\n" "optional_int64: 2\n" " optional_double: 2.4\n" "repeated_int32: 5\n" "repeated_int32: 10\n" "optional_nested_message <\n" " bb: 78\n" ">\n" "repeated_nested_message <\n" " bb: 79\n" ">\n" "repeated_nested_message <\n" " bb: 80\n" ">"; TextFormat::ParseInfoTree tree; ExpectSuccessAndTree(stringData, message.get(), &tree); // Verify that the tree has the correct positions. ExpectLocation(&tree, d, "optional_int32", -1, 0, 0); ExpectLocation(&tree, d, "optional_int64", -1, 1, 0); ExpectLocation(&tree, d, "optional_double", -1, 2, 2); ExpectLocation(&tree, d, "repeated_int32", 0, 3, 0); ExpectLocation(&tree, d, "repeated_int32", 1, 4, 0); ExpectLocation(&tree, d, "optional_nested_message", -1, 5, 0); ExpectLocation(&tree, d, "repeated_nested_message", 0, 8, 0); ExpectLocation(&tree, d, "repeated_nested_message", 1, 11, 0); // Check for fields not set. For an invalid field, the location returned // should be -1, -1. ExpectLocation(&tree, d, "repeated_int64", 0, -1, -1); ExpectLocation(&tree, d, "repeated_int32", 6, -1, -1); ExpectLocation(&tree, d, "some_unknown_field", -1, -1, -1); // Verify inside the nested message. const FieldDescriptor* nested_field = d->FindFieldByName("optional_nested_message"); TextFormat::ParseInfoTree* nested_tree = tree.GetTreeForNested(nested_field, -1); ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 6, 2); // Verify inside another nested message. nested_field = d->FindFieldByName("repeated_nested_message"); nested_tree = tree.GetTreeForNested(nested_field, 0); ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 9, 2); nested_tree = tree.GetTreeForNested(nested_field, 1); ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 12, 2); // Verify a NULL tree for an unknown nested field. TextFormat::ParseInfoTree* unknown_nested_tree = tree.GetTreeForNested(nested_field, 2); EXPECT_EQ(NULL, unknown_nested_tree); } TEST_F(TextFormatParserTest, ParseFieldValueFromString) { google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); #define EXPECT_FIELD(name, value, valuestring) \ EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ valuestring, d->FindFieldByName("optional_" #name), message.get())); \ EXPECT_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); #define EXPECT_BOOL_FIELD(name, value, valuestring) \ EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ valuestring, d->FindFieldByName("optional_" #name), message.get())); \ EXPECT_TRUE(message->optional_##name() == value); \ EXPECT_TRUE(message->has_optional_##name()); #define EXPECT_FLOAT_FIELD(name, value, valuestring) \ EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ valuestring, d->FindFieldByName("optional_" #name), message.get())); \ EXPECT_FLOAT_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); #define EXPECT_DOUBLE_FIELD(name, value, valuestring) \ EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ valuestring, d->FindFieldByName("optional_" #name), message.get())); \ EXPECT_DOUBLE_EQ(value, message->optional_##name()); \ EXPECT_TRUE(message->has_optional_##name()); #define EXPECT_INVALID(name, valuestring) \ EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \ valuestring, d->FindFieldByName("optional_" #name), message.get())); // int32 EXPECT_FIELD(int32, 1, "1"); EXPECT_FIELD(int32, -1, "-1"); EXPECT_FIELD(int32, 0x1234, "0x1234"); EXPECT_INVALID(int32, "a"); EXPECT_INVALID(int32, "999999999999999999999999999999999999"); EXPECT_INVALID(int32, "1,2"); // int64 EXPECT_FIELD(int64, 1, "1"); EXPECT_FIELD(int64, -1, "-1"); EXPECT_FIELD(int64, 0x1234567812345678LL, "0x1234567812345678"); EXPECT_INVALID(int64, "a"); EXPECT_INVALID(int64, "999999999999999999999999999999999999"); EXPECT_INVALID(int64, "1,2"); // uint64 EXPECT_FIELD(uint64, 1, "1"); EXPECT_FIELD(uint64, 0xf234567812345678ULL, "0xf234567812345678"); EXPECT_INVALID(uint64, "-1"); EXPECT_INVALID(uint64, "a"); EXPECT_INVALID(uint64, "999999999999999999999999999999999999"); EXPECT_INVALID(uint64, "1,2"); // fixed32 EXPECT_FIELD(fixed32, 1, "1"); EXPECT_FIELD(fixed32, 0x12345678, "0x12345678"); EXPECT_INVALID(fixed32, "-1"); EXPECT_INVALID(fixed32, "a"); EXPECT_INVALID(fixed32, "999999999999999999999999999999999999"); EXPECT_INVALID(fixed32, "1,2"); // fixed64 EXPECT_FIELD(fixed64, 1, "1"); EXPECT_FIELD(fixed64, 0x1234567812345678ULL, "0x1234567812345678"); EXPECT_INVALID(fixed64, "-1"); EXPECT_INVALID(fixed64, "a"); EXPECT_INVALID(fixed64, "999999999999999999999999999999999999"); EXPECT_INVALID(fixed64, "1,2"); // bool EXPECT_BOOL_FIELD(bool, true, "true"); EXPECT_BOOL_FIELD(bool, false, "false"); EXPECT_BOOL_FIELD(bool, true, "1"); EXPECT_BOOL_FIELD(bool, true, "t"); EXPECT_BOOL_FIELD(bool, false, "0"); EXPECT_BOOL_FIELD(bool, false, "f"); EXPECT_FIELD(bool, true, "True"); EXPECT_FIELD(bool, false, "False"); EXPECT_INVALID(bool, "tRue"); EXPECT_INVALID(bool, "faLse"); EXPECT_INVALID(bool, "2"); EXPECT_INVALID(bool, "-0"); EXPECT_INVALID(bool, "on"); EXPECT_INVALID(bool, "a"); // float EXPECT_FIELD(float, 1, "1"); EXPECT_FLOAT_FIELD(float, 1.5, "1.5"); EXPECT_FLOAT_FIELD(float, 1.5e3, "1.5e3"); EXPECT_FLOAT_FIELD(float, -4.55, "-4.55"); EXPECT_INVALID(float, "a"); EXPECT_INVALID(float, "1,2"); // double EXPECT_FIELD(double, 1, "1"); EXPECT_FIELD(double, -1, "-1"); EXPECT_DOUBLE_FIELD(double, 2.3, "2.3"); EXPECT_DOUBLE_FIELD(double, 3e5, "3e5"); EXPECT_INVALID(double, "a"); EXPECT_INVALID(double, "1,2"); // Rejects hex and oct numbers for a double field. EXPECT_INVALID(double, "0xf"); EXPECT_INVALID(double, "012"); // string EXPECT_FIELD(string, "hello", "\"hello\""); EXPECT_FIELD(string, "-1.87", "'-1.87'"); EXPECT_INVALID(string, "hello"); // without quote for value // enum EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR"); EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ, SimpleItoa(unittest::TestAllTypes::BAZ)); EXPECT_INVALID(nested_enum, "FOOBAR"); // message EXPECT_TRUE(TextFormat::ParseFieldValueFromString( "<bb:12>", d->FindFieldByName("optional_nested_message"), message.get())); EXPECT_EQ(12, message->optional_nested_message().bb()); \ EXPECT_TRUE(message->has_optional_nested_message()); EXPECT_INVALID(nested_message, "any"); #undef EXPECT_FIELD #undef EXPECT_BOOL_FIELD #undef EXPECT_FLOAT_FIELD #undef EXPECT_DOUBLE_FIELD #undef EXPECT_INVALID } TEST_F(TextFormatParserTest, InvalidToken) { ExpectFailure("optional_bool: true\n-5\n", "Expected identifier, got: -", 2, 1); ExpectFailure("optional_bool: true!\n", "Expected identifier, got: !", 1, 20); ExpectFailure("\"some string\"", "Expected identifier, got: \"some string\"", 1, 1); } TEST_F(TextFormatParserTest, InvalidFieldName) { ExpectFailure( "invalid_field: somevalue\n", "Message type \"protobuf_unittest.TestAllTypes\" has no field named " "\"invalid_field\".", 1, 14); } TEST_F(TextFormatParserTest, InvalidCapitalization) { // We require that group names be exactly as they appear in the .proto. ExpectFailure( "optionalgroup {\na: 15\n}\n", "Message type \"protobuf_unittest.TestAllTypes\" has no field named " "\"optionalgroup\".", 1, 15); ExpectFailure( "OPTIONALgroup {\na: 15\n}\n", "Message type \"protobuf_unittest.TestAllTypes\" has no field named " "\"OPTIONALgroup\".", 1, 15); ExpectFailure( "Optional_Double: 10.0\n", "Message type \"protobuf_unittest.TestAllTypes\" has no field named " "\"Optional_Double\".", 1, 16); } TEST_F(TextFormatParserTest, AllowIgnoreCapitalizationError) { TextFormat::Parser parser; protobuf_unittest::TestAllTypes proto; // These fields have a mismatching case. EXPECT_FALSE(parser.ParseFromString("Optional_Double: 10.0", &proto)); EXPECT_FALSE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto)); // ... but are parsed correctly if we match case insensitive. parser.AllowCaseInsensitiveField(true); EXPECT_TRUE(parser.ParseFromString("Optional_Double: 10.0", &proto)); EXPECT_EQ(10.0, proto.optional_double()); EXPECT_TRUE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto)); EXPECT_EQ(15, proto.optionalgroup().a()); } TEST_F(TextFormatParserTest, InvalidFieldValues) { // Invalid values for a double/float field. ExpectFailure("optional_double: \"hello\"\n", "Expected double, got: \"hello\"", 1, 18); ExpectFailure("optional_double: true\n", "Expected double, got: true", 1, 18); ExpectFailure("optional_double: !\n", "Expected double, got: !", 1, 18); ExpectFailure("optional_double {\n \n}\n", "Expected \":\", found \"{\".", 1, 17); // Invalid values for a signed integer field. ExpectFailure("optional_int32: \"hello\"\n", "Expected integer, got: \"hello\"", 1, 17); ExpectFailure("optional_int32: true\n", "Expected integer, got: true", 1, 17); ExpectFailure("optional_int32: 4.5\n", "Expected integer, got: 4.5", 1, 17); ExpectFailure("optional_int32: !\n", "Expected integer, got: !", 1, 17); ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", 1, 16); ExpectFailure("optional_int32: 0x80000000\n", "Integer out of range (0x80000000)", 1, 17); ExpectFailure("optional_int64: 0x8000000000000000\n", "Integer out of range (0x8000000000000000)", 1, 17); ExpectFailure("optional_int32: -0x80000001\n", "Integer out of range (0x80000001)", 1, 18); ExpectFailure("optional_int64: -0x8000000000000001\n", "Integer out of range (0x8000000000000001)", 1, 18); // Invalid values for an unsigned integer field. ExpectFailure("optional_uint64: \"hello\"\n", "Expected integer, got: \"hello\"", 1, 18); ExpectFailure("optional_uint64: true\n", "Expected integer, got: true", 1, 18); ExpectFailure("optional_uint64: 4.5\n", "Expected integer, got: 4.5", 1, 18); ExpectFailure("optional_uint64: -5\n", "Expected integer, got: -", 1, 18); ExpectFailure("optional_uint64: !\n", "Expected integer, got: !", 1, 18); ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", 1, 17); ExpectFailure("optional_uint32: 0x100000000\n", "Integer out of range (0x100000000)", 1, 18); ExpectFailure("optional_uint64: 0x10000000000000000\n", "Integer out of range (0x10000000000000000)", 1, 18); // Invalid values for a boolean field. ExpectFailure("optional_bool: \"hello\"\n", "Expected identifier, got: \"hello\"", 1, 16); ExpectFailure("optional_bool: 5\n", "Integer out of range (5)", 1, 16); ExpectFailure("optional_bool: -7.5\n", "Expected identifier, got: -", 1, 16); ExpectFailure("optional_bool: !\n", "Expected identifier, got: !", 1, 16); ExpectFailure( "optional_bool: meh\n", "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", 2, 1); ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", 1, 15); // Invalid values for a string field. ExpectFailure("optional_string: true\n", "Expected string, got: true", 1, 18); ExpectFailure("optional_string: 5\n", "Expected string, got: 5", 1, 18); ExpectFailure("optional_string: -7.5\n", "Expected string, got: -", 1, 18); ExpectFailure("optional_string: !\n", "Expected string, got: !", 1, 18); ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", 1, 17); // Invalid values for an enumeration field. ExpectFailure("optional_nested_enum: \"hello\"\n", "Expected integer or identifier, got: \"hello\"", 1, 23); // Valid token, but enum value is not defined. ExpectFailure("optional_nested_enum: 5\n", "Unknown enumeration value of \"5\" for field " "\"optional_nested_enum\".", 2, 1); // We consume the negative sign, so the error position starts one character // later. ExpectFailure("optional_nested_enum: -7.5\n", "Expected integer, got: 7.5", 1, 24); ExpectFailure("optional_nested_enum: !\n", "Expected integer or identifier, got: !", 1, 23); ExpectFailure( "optional_nested_enum: grah\n", "Unknown enumeration value of \"grah\" for field " "\"optional_nested_enum\".", 2, 1); ExpectFailure( "optional_nested_enum {\n \n}\n", "Expected \":\", found \"{\".", 1, 22); } TEST_F(TextFormatParserTest, MessageDelimiters) { // Non-matching delimiters. ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", 3, 1); // Invalid delimiters. ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", 1, 15); // Unending message. ExpectFailure("optional_nested_message {\n \nbb: 118\n", "Expected identifier, got: ", 4, 1); } TEST_F(TextFormatParserTest, UnknownExtension) { // Non-matching delimiters. ExpectFailure("[blahblah]: 123", "Extension \"blahblah\" is not defined or is not an " "extension of \"protobuf_unittest.TestAllTypes\".", 1, 11); } TEST_F(TextFormatParserTest, MissingRequired) { unittest::TestRequired message; ExpectFailure("a: 1", "Message missing required fields: b, c", 0, 1, &message); } TEST_F(TextFormatParserTest, ParseDuplicateRequired) { unittest::TestRequired message; ExpectFailure("a: 1 b: 2 c: 3 a: 1", "Non-repeated field \"a\" is specified multiple times.", 1, 17, &message); } TEST_F(TextFormatParserTest, ParseDuplicateOptional) { unittest::ForeignMessage message; ExpectFailure("c: 1 c: 2", "Non-repeated field \"c\" is specified multiple times.", 1, 7, &message); } TEST_F(TextFormatParserTest, MergeDuplicateRequired) { unittest::TestRequired message; TextFormat::Parser parser; EXPECT_TRUE(parser.MergeFromString("a: 1 b: 2 c: 3 a: 4", &message)); EXPECT_EQ(4, message.a()); } TEST_F(TextFormatParserTest, MergeDuplicateOptional) { unittest::ForeignMessage message; TextFormat::Parser parser; EXPECT_TRUE(parser.MergeFromString("c: 1 c: 2", &message)); EXPECT_EQ(2, message.c()); } TEST_F(TextFormatParserTest, ExplicitDelimiters) { unittest::TestRequired message; EXPECT_TRUE(TextFormat::ParseFromString("a:1,b:2;c:3", &message)); EXPECT_EQ(1, message.a()); EXPECT_EQ(2, message.b()); EXPECT_EQ(3, message.c()); } TEST_F(TextFormatParserTest, PrintErrorsToStderr) { vector<string> errors; { ScopedMemoryLog log; unittest::TestAllTypes proto; EXPECT_FALSE(TextFormat::ParseFromString("no_such_field: 1", &proto)); errors = log.GetMessages(ERROR); } ASSERT_EQ(1, errors.size()); EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field " "named \"no_such_field\".", errors[0]); } TEST_F(TextFormatParserTest, FailsOnTokenizationError) { vector<string> errors; { ScopedMemoryLog log; unittest::TestAllTypes proto; EXPECT_FALSE(TextFormat::ParseFromString("\020", &proto)); errors = log.GetMessages(ERROR); } ASSERT_EQ(1, errors.size()); EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " "1:1: Invalid control characters encountered in text.", errors[0]); } TEST_F(TextFormatParserTest, ParseDeprecatedField) { unittest::TestDeprecatedFields message; ExpectMessage("deprecated_int32: 42", "WARNING:text format contains deprecated field " "\"deprecated_int32\"", 1, 21, &message, true); } class TextFormatMessageSetTest : public testing::Test { protected: static const char proto_debug_string_[]; }; const char TextFormatMessageSetTest::proto_debug_string_[] = "message_set {\n" " [protobuf_unittest.TestMessageSetExtension1] {\n" " i: 23\n" " }\n" " [protobuf_unittest.TestMessageSetExtension2] {\n" " str: \"foo\"\n" " }\n" "}\n"; TEST_F(TextFormatMessageSetTest, Serialize) { protobuf_unittest::TestMessageSetContainer proto; protobuf_unittest::TestMessageSetExtension1* item_a = proto.mutable_message_set()->MutableExtension( protobuf_unittest::TestMessageSetExtension1::message_set_extension); item_a->set_i(23); protobuf_unittest::TestMessageSetExtension2* item_b = proto.mutable_message_set()->MutableExtension( protobuf_unittest::TestMessageSetExtension2::message_set_extension); item_b->set_str("foo"); EXPECT_EQ(proto_debug_string_, proto.DebugString()); } TEST_F(TextFormatMessageSetTest, Deserialize) { protobuf_unittest::TestMessageSetContainer proto; ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto)); EXPECT_EQ(23, proto.message_set().GetExtension( protobuf_unittest::TestMessageSetExtension1::message_set_extension).i()); EXPECT_EQ("foo", proto.message_set().GetExtension( protobuf_unittest::TestMessageSetExtension2::message_set_extension).str()); // Ensure that these are the only entries present. vector<const FieldDescriptor*> descriptors; proto.message_set().GetReflection()->ListFields( proto.message_set(), &descriptors); EXPECT_EQ(2, descriptors.size()); } } // namespace text_format_unittest } // namespace protobuf } // namespace google
#include <Functions/IFunction.h> #include <Functions/FunctionFactory.h> #include <DataTypes/DataTypeString.h> #include <DataTypes/DataTypeNullable.h> #include <DataTypes/DataTypeDateTime.h> #include <common/DateLUTImpl.h> #include <Core/Field.h> namespace DB { namespace ErrorCodes { extern const int BAD_ARGUMENTS; } namespace { /** timezoneOf(x) - get the name of the timezone of DateTime data type. * Example: Europe/Moscow. */ class FunctionTimezoneOf : public IFunction { public: static constexpr auto name = "timezoneOf"; String getName() const override { return name; } static FunctionPtr create(ContextPtr) { return std::make_unique<FunctionTimezoneOf>(); } size_t getNumberOfArguments() const override { return 1; } bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; } DataTypePtr getReturnTypeImpl(const DataTypes & types) const override { DataTypePtr type_no_nullable = removeNullable(types[0]); if (isDateTime(type_no_nullable) || isDateTime64(type_no_nullable)) return std::make_shared<DataTypeString>(); else throw Exception(ErrorCodes::BAD_ARGUMENTS, "Bad argument for function {}, should be DateTime or DateTime64", name); } bool useDefaultImplementationForNulls() const override { return false; } bool useDefaultImplementationForLowCardinalityColumns() const override { return false; } ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t /*number_of_arguments*/) const override { return {0}; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override { DataTypePtr type_no_nullable = removeNullable(arguments[0].type); return DataTypeString().createColumnConst(input_rows_count, dynamic_cast<const TimezoneMixin &>(*type_no_nullable).getTimeZone().getTimeZone()); } ColumnPtr getConstantResultForNonConstArguments(const ColumnsWithTypeAndName & arguments, const DataTypePtr &) const override { DataTypePtr type_no_nullable = removeNullable(arguments[0].type); return DataTypeString().createColumnConst(1, dynamic_cast<const TimezoneMixin &>(*type_no_nullable).getTimeZone().getTimeZone()); } }; } void registerFunctionTimezoneOf(FunctionFactory & factory) { factory.registerFunction<FunctionTimezoneOf>(); factory.registerAlias("timeZoneOf", "timezoneOf"); } }
/** * Copyright (c) 2006-2020 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #include "Joint.h" namespace love { namespace physics { love::Type Joint::type("Joint", &Object::type); Joint::~Joint() { } bool Joint::getConstant(const char *in, Type &out) { return types.find(in, out); } bool Joint::getConstant(Type in, const char *&out) { return types.find(in, out); } StringMap<Joint::Type, Joint::JOINT_MAX_ENUM>::Entry Joint::typeEntries[] = { {"distance", Joint::JOINT_DISTANCE}, {"revolute", Joint::JOINT_REVOLUTE}, {"prismatic", Joint::JOINT_PRISMATIC}, {"mouse", Joint::JOINT_MOUSE}, {"pulley", Joint::JOINT_PULLEY}, {"gear", Joint::JOINT_GEAR}, {"friction", Joint::JOINT_FRICTION}, {"weld", Joint::JOINT_WELD}, {"wheel", Joint::JOINT_WHEEL}, {"rope", Joint::JOINT_ROPE}, {"motor", Joint::JOINT_MOTOR}, }; StringMap<Joint::Type, Joint::JOINT_MAX_ENUM> Joint::types(Joint::typeEntries, sizeof(Joint::typeEntries)); } // physics } // love
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/timer.h" #if defined(STM32PLUS_F1_MD) || defined(STM32PLUS_F1_MD_VL) using namespace stm32plus; // static initialisers for the hack that forces the IRQ handlers to be linked template<> TimerInterruptFeatureEnabler<1>::FPTR TimerInterruptFeatureEnabler<1>::_forceLinkage=nullptr; extern "C" { #if defined(USE_TIM1_UP_TIM16_INTERRUPT) /** * TIM1_UP & TIM16 */ void __attribute__ ((interrupt("IRQ"))) TIM1_UP_TIM16_IRQHandler() { if(TIM_GetITStatus(TIM1,TIM_IT_Update)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,1); TIM_ClearITPendingBit(TIM1,TIM_IT_Update); } else if(TIM_GetITStatus(TIM16,TIM_IT_Break)!=RESET) { TimerInterruptFeature<16>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_BREAK,16); TIM_ClearITPendingBit(TIM16,TIM_IT_Break); } __DSB(); // prevent erroneous recall of this handler due to delayed memory write } #endif /** * TIM1_BRK & TIM15 */ #if defined(USE_TIM1_BRK_TIM15_INTERRUPT) void __attribute__ ((interrupt("IRQ"))) TIM1_BRK_TIM15_IRQHandler() { if(TIM_GetITStatus(TIM1,TIM_IT_Break)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_BREAK,1); TIM_ClearITPendingBit(TIM1,TIM_IT_Break); } else if(TIM_GetITStatus(TIM15,TIM_IT_Update)!=RESET) { TimerInterruptFeature<15>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,15); TIM_ClearITPendingBit(TIM15,TIM_IT_Update); } __DSB(); // prevent erroneous recall of this handler due to delayed memory write } #endif /** * TIM1_TRG_COM & TIM17 */ #if defined(USE_TIM1_TRG_COM_TIM17_INTERRUPT) void __attribute__ ((interrupt("IRQ"))) TIM1_TRG_COM_TIM17_IRQHandler() { if(TIM_GetITStatus(TIM1,TIM_IT_Trigger)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_TRIGGER,1); TIM_ClearITPendingBit(TIM1,TIM_IT_Trigger); } else if(TIM_GetITStatus(TIM1,TIM_IT_COM)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COM,1); TIM_ClearITPendingBit(TIM1,TIM_IT_COM); } else if(TIM_GetITStatus(TIM17,TIM_IT_Update)!=RESET) { TimerInterruptFeature<17>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,17); TIM_ClearITPendingBit(TIM17,TIM_IT_Update); } __DSB(); // prevent erroneous recall of this handler due to delayed memory write } #endif /** * TIM1_CC interrupt handler */ #if defined(USE_TIM1_CC_INTERRUPT) void __attribute__ ((interrupt("IRQ"))) TIM1_CC_IRQHandler() { if(TIM_GetITStatus(TIM1,TIM_IT_CC1)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE1,1); TIM_ClearITPendingBit(TIM1,TIM_IT_CC1); } else if(TIM_GetITStatus(TIM1,TIM_IT_CC2)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE2,1); TIM_ClearITPendingBit(TIM1,TIM_IT_CC2); } else if(TIM_GetITStatus(TIM1,TIM_IT_CC3)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE3,1); TIM_ClearITPendingBit(TIM1,TIM_IT_CC3); } else if(TIM_GetITStatus(TIM1,TIM_IT_CC3)!=RESET) { TimerInterruptFeature<1>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE3,1); TIM_ClearITPendingBit(TIM1,TIM_IT_CC3); } __DSB(); // prevent erroneous recall of this handler due to delayed memory write } #endif } // extern "C" #endif
// Copyright (c) 2017-2018, The Moneda Project // // 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 its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "include_base_utils.h" #include "file_io_utils.h" #include "serialization/keyvalue_serialization.h" #include "storages/portable_storage_template_helper.h" #include "storages/portable_storage_base.h" #include "fuzzer.h" class PortableStorageFuzzer: public Fuzzer { public: PortableStorageFuzzer() {} virtual int init(); virtual int run(const std::string &filename); }; int PortableStorageFuzzer::init() { return 0; } int PortableStorageFuzzer::run(const std::string &filename) { std::string s; if (!epee::file_io_utils::load_file_to_string(filename, s)) { std::cout << "Error: failed to load file " << filename << std::endl; return 1; } try { epee::serialization::portable_storage ps; ps.load_from_binary(s); } catch (const std::exception &e) { std::cerr << "Failed to load from binary: " << e.what() << std::endl; return 1; } return 0; } int main(int argc, const char **argv) { PortableStorageFuzzer fuzzer; return run_fuzzer(argc, argv, fuzzer); }
#include "Commands/commands.h" #include "Utils/utils.h" int commands::helpers::is_ntfs(std::shared_ptr<Disk> disk, std::shared_ptr<Volume> vol) { if ((vol->filesystem() != "NTFS") && (vol->filesystem() != "Bitlocker")) { std::cerr << "[!] NTFS volume required" << std::endl; return 0; } return 1; } std::shared_ptr<MFTRecord> commands::helpers::find_record(std::shared_ptr<NTFSExplorer> ex, std::shared_ptr<Options> opts) { std::shared_ptr<MFTRecord> rec = nullptr; auto [filepath, stream_name] = ::utils::files::split_file_and_stream(opts->from); if (opts->from != "") { rec = ex->mft()->record_from_path(filepath); if (rec == nullptr) { invalid_option(opts, "from", opts->from, "Unable to find file record."); } } else { rec = ex->mft()->record_from_number(opts->inode); if (rec == nullptr) { invalid_option(opts, "inode", opts->inode, "Unable to find file record."); } } return rec; }
// Copyright (c) 2014 Anton Bikineev // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) static const boost::array<boost::array<typename table_type<T>::type, 3>, 720 #if LDBL_MAX_10_EXP < 370 - 5 #endif > bessel_j_prime_data = {{ {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.553809732082299888134002685546875e-4), SC_(7.9648978910149220644314151981633892502393579865714) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.69304020144045352935791015625e-4), SC_(6.3653848991988529988220477650241685520191503142332) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.23264062474481761455535888671875e-3), SC_(1.8971705960000986690398059822421160899926699465394) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.4480001516640186309814453125e-3), SC_(0.98529897246253853844800411025777530163752073502973) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.5502865533344447612762451171875e-3), SC_(0.80213378584577808385371731269994831627611100850731) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.19227224402129650115966796875e-2), SC_(0.22881945446922959370415245044176092614274648710909) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.37370622158050537109375e-2), SC_(0.11639238325218579687879378821010964741303634572024) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.47696642577648162841796875e-2), SC_(0.090285635947979939708760228970288288400405507095951) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.1275280676782131195068359375e-1), SC_(0.028310110253065767611367722783039281567929780822508) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.20440109074115753173828125e-1), SC_(0.011437832630785135189848926023917028888883030118541) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.3429813683032989501953125e-1), SC_(-0.0042186780829510697643927657163520133060777440127718) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.96701286733150482177734375e-1), SC_(-0.043654403685014564129834014054367553568659669792961) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.159812271595001220703125e0), SC_(-0.076795076483668747332489412246651051532303741843621) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.297095477581024169921875e0), SC_(-0.14530589560654803595230285920771334403536798001997) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.77344071865081787109375e0), SC_(-0.35781255859257494677870346599515476750516695439221) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.1992881298065185546875e1), SC_(-0.57709619128762175849182337519495024595142653978034) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.3915013790130615234375e1), SC_(0.032874697176171305159599881134984554120579875033562) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.79858455657958984375e1), SC_(-0.23248455952535491176666424888090762133592541368724) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.1571910858154296875e2), SC_(-0.13744744338917036209493697966640300199111782413145) }}, {{ SC_(0.4430477856658399105072021484375e-3), SC_(0.31483119964599609375e2), SC_(0.092384054297253080189500208979099324382934270491253) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.553809732082299888134002685546875e-4), SC_(9.9563140737354415945593422946525211226319134399898) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.69304020144045352935791015625e-4), SC_(7.9570862305908154157502670767893857144258643910134) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.23264062474481761455535888671875e-3), SC_(2.3719155181483651140283794679798873388028215296304) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.4480001516640186309814453125e-3), SC_(1.2319894744844574970516920107312783189510124193957) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.5502865533344447612762451171875e-3), SC_(1.0030112034602294475985095364967567453689835477452) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.19227224402129650115966796875e-2), SC_(0.28638350069997314241293417948854845587335617752927) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.37370622158050537109375e-2), SC_(0.14602972396377771654216460801323111364027557644216) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.47696642577648162841796875e-2), SC_(0.11351290994319074087410492441665358190230772804358) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.1275280676782131195068359375e-1), SC_(0.037008791924439581267986370097571362280888733460166) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.20440109074115753173828125e-1), SC_(0.016870508777086141024636797643775059196570100354985) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.3429813683032989501953125e-1), SC_(-0.0009748286242877649280689834700793092180965082559188) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.96701286733150482177734375e-1), SC_(-0.042489525327810393709078101729898351459510301627119) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.159812271595001220703125e0), SC_(-0.076077771654874512175725382541977707974494001219809) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.297095477581024169921875e0), SC_(-0.1449016974533794537266458225037915821627831419956) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.77344071865081787109375e0), SC_(-0.35763606304629819698651497909483012152923309977282) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.1992881298065185546875e1), SC_(-0.57707668367484666209769235993304653592448524328446) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.3915013790130615234375e1), SC_(0.032803565971798883663621750338601798771900853737723) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.79858455657958984375e1), SC_(-0.23245627383271580403946117793068576486562704835183) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.1571910858154296875e2), SC_(-0.13747319597155377972477306724918905968623791762052) }}, {{ SC_(0.554432161152362823486328125e-3), SC_(0.31483119964599609375e2), SC_(0.092402972740382015495412561744044435050456817053477) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.553809732082299888134002685546875e-4), SC_(32.991155195510662374452228181394207719668827912585) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.69304020144045352935791015625e-4), SC_(26.374288085785808071594815766184735941437037668361) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.23264062474481761455535888671875e-3), SC_(7.8745670452285410777433428652060226596690838235756) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.4480001516640186309814453125e-3), SC_(4.0939888412516262352091077877368046329988231549179) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.5502865533344447612762451171875e-3), SC_(3.3341891189206161618889782248584501135265038836937) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.19227224402129650115966796875e-2), SC_(0.95560384937570815980175679166160209025653903976137) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.37370622158050537109375e-2), SC_(0.49090952938765514533182157874449576923325297005204) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.47696642577648162841796875e-2), SC_(0.38389476017333637199587327253156428168993195132975) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.1275280676782131195068359375e-1), SC_(0.138409389156362855297988849958748604218151741016) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.20440109074115753173828125e-1), SC_(0.080241816559198872765517481865392895830572812371149) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.3429813683032989501953125e-1), SC_(0.036892112652472221644586526213180260842441269686804) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.02887110612739140483997421990789250909295516887439) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.159812271595001220703125e0), SC_(-0.067685739169149094863754883494101630051701749161209) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.297095477581024169921875e0), SC_(-0.14016851381502971127112075638647269597367135444309) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.77344071865081787109375e0), SC_(-0.35556632184765282255617154328610427789832356622214) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.1992881298065185546875e1), SC_(-0.57684653674632859345467293924518112947171640665078) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.3915013790130615234375e1), SC_(0.031969124632149993427358514338814374853801046758595) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.79858455657958984375e1), SC_(-0.23212392987235794473256668897443830855028454545551) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.1571910858154296875e2), SC_(-0.13777498598113913007808999712256844131654804580519) }}, {{ SC_(0.186112499795854091644287109375e-2), SC_(0.31483119964599609375e2), SC_(0.092624697644537533475041370994881579560890987351129) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.553809732082299888134002685546875e-4), SC_(62.454904613305025985092541568718072298279856562443) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.69304020144045352935791015625e-4), SC_(49.947950666961749968398510500237745648681418603404) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.23264062474481761455535888671875e-3), SC_(14.944193661627905898455586863695741230110016599631) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.4480001516640186309814453125e-3), SC_(7.7784129572206297283822428686304106551362644795044) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.5502865533344447612762451171875e-3), SC_(6.3371526780999425820466081747816869557736781837329) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.19227224402129650115966796875e-2), SC_(1.820993665575078594500973453282200116278151251087) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.37370622158050537109375e-2), SC_(0.9377936281725870885241868271005730443425730711559) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.47696642577648162841796875e-2), SC_(0.73450867711905500446374700000456510885348368932524) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.1275280676782131195068359375e-1), SC_(0.27029553238094754272834952547486499293865621939941) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.20440109074115753173828125e-1), SC_(0.16278442505650975565354006872279918590899945301714) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.3429813683032989501953125e-1), SC_(0.086292944004707690950589840564950857129632612299699) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.01104782892769029720544801382986554239946069854045) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.159812271595001220703125e0), SC_(-0.05668535469393136238714153940266293419595207886607) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.297095477581024169921875e0), SC_(-0.13395208202148233977338620116710632764449019915955) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.77344071865081787109375e0), SC_(-0.35283962535090438998824674990498799699024494912424) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.1992881298065185546875e1), SC_(-0.57653944367953511466145604243653167683836799979183) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.3915013790130615234375e1), SC_(0.030868990724401199078667741038245477603972593270015) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.79858455657958984375e1), SC_(-0.23168428917079507517559801618314290273647233672929) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.1571910858154296875e2), SC_(-0.13817198405516350060106646524335248058260389189795) }}, {{ SC_(0.35840012133121490478515625e-2), SC_(0.31483119964599609375e2), SC_(0.092916436595105559391595180151309343563751077592049) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.553809732082299888134002685546875e-4), SC_(76.094037091452672841408919517251753935599130990416) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.69304020144045352935791015625e-4), SC_(60.86694014763617381883362484413204002437988483891) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.23264062474481761455535888671875e-3), SC_(18.229182783832605707598240444273148205330129326374) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.4480001516640186309814453125e-3), SC_(9.4933663212904445110802371668553605819628244021874) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.5502865533344447612762451171875e-3), SC_(7.7356648564267450544222554441272100183990241145299) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.19227224402129650115966796875e-2), SC_(2.2253316945948961542743895239623228539455376609079) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.37370622158050537109375e-2), SC_(1.1469531280898255753143802718054167596670751930758) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.47696642577648162841796875e-2), SC_(0.8987138042469555955140638448947036336020766497208) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.1275280676782131195068359375e-1), SC_(0.33222006268427673176001775575327506626793624720047) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.20440109074115753173828125e-1), SC_(0.20158797802098065441112035562918896779201063031557) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.3429813683032989501953125e-1), SC_(0.10954754542608689498762692934343451061816281331611) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.0026352030152986806285640288099372676975308652569059) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.159812271595001220703125e0), SC_(-0.051486300229518660533195827724135883555923546965981) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.297095477581024169921875e0), SC_(-0.13100921711901138238440294338076135399910977624865) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.77344071865081787109375e0), SC_(-0.35154547252275810168236545554332529311171223761341) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.1992881298065185546875e1), SC_(-0.57639213881628347984110125372663315128642382553447) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.3915013790130615234375e1), SC_(0.030346508334070453430651975727124470878861233027065) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.79858455657958984375e1), SC_(-0.23147490443190245853754535262108083070463877602731) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.1571910858154296875e2), SC_(-0.13836017664760414231270840005996432417492176750639) }}, {{ SC_(0.44022924266755580902099609375e-2), SC_(0.31483119964599609375e2), SC_(0.093054758085530830928594196942552871371673202587369) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.553809732082299888134002685546875e-4), SC_(238.40366837144969439786103525601379114477677307153) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.69304020144045352935791015625e-4), SC_(191.16712873573625819054755770058932780852989850252) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.23264062474481761455535888671875e-3), SC_(58.019648524540935308440305137519165694212527314843) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.4480001516640186309814453125e-3), SC_(30.43392563287949994188281672966817873020334162581) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.5502865533344447612762451171875e-3), SC_(24.85533168119730302852076771558049252631942520417) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.19227224402129650115966796875e-2), SC_(7.2510627068545058442709465549514403544652820845905) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.37370622158050537109375e-2), SC_(3.7677615674740978933153881013861943903635063551538) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.47696642577648162841796875e-2), SC_(2.962324331943341100101643624061007763061585442363) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.1275280676782131195068359375e-1), SC_(1.1197441963909279005647512732082270829583516807172) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.20440109074115753173828125e-1), SC_(0.69788572344937366417209880630068985545559719963545) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.3429813683032989501953125e-1), SC_(0.40883500813978713691656188814831957578718243471079) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.96701286733150482177734375e-1), SC_(0.10700157693081281268315564619716643090427720046237) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.159812271595001220703125e0), SC_(0.016686833954731293114143419204690913686819214571699) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.297095477581024169921875e0), SC_(-0.092124902842593660026469490242650431046031191860855) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.77344071865081787109375e0), SC_(-0.33423965946999394482766889004297913580285873083183) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.1992881298065185546875e1), SC_(-0.57432599769968961776379817247419230653628340804375) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.3915013790130615234375e1), SC_(0.023338620631847629186573253547315649793186094107388) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.79858455657958984375e1), SC_(-0.22862990513409971505075485840350294504759601811506) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.1571910858154296875e2), SC_(-0.1408624244371769854856489920229138227673726479075) }}, {{ SC_(0.153817795217037200927734375e-1), SC_(0.31483119964599609375e2), SC_(0.094895516987968244278180735467242514989968258763469) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.553809732082299888134002685546875e-4), SC_(401.03396568589946004426626518285877552588221703456) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.69304020144045352935791015625e-4), SC_(322.62287318261062067717298841026124993076998674488) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.23264062474481761455535888671875e-3), SC_(99.653154993389532146468468431109235573777170772011) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.4480001516640186309814453125e-3), SC_(52.772263261102197213931020894608318973782604772283) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.5502865533344447612762451171875e-3), SC_(43.227918910310427346951401482833588864302431474419) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.19227224402129650115966796875e-2), SC_(12.842688059620175274882027252980428180593090063375) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.37370622158050537109375e-2), SC_(6.7390274818843771110431882385099223900918335630655) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.47696642577648162841796875e-2), SC_(5.3179544066533640875307065878216351879107714339398) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.1275280676782131195068359375e-1), SC_(2.0435872586177536078792092041967345862250992458715) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.20440109074115753173828125e-1), SC_(1.2876735976248464722948927962724955876009337432191) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.3429813683032989501953125e-1), SC_(0.7695517710363719560199084953580644660557370801408) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.96701286733150482177734375e-1), SC_(0.24290377631717472590521846883415245818694289017361) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.159812271595001220703125e0), SC_(0.10235005529723907433661732235444859781219501249974) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.297095477581024169921875e0), SC_(-0.042435615294286794584933169804436673619316094085801) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.77344071865081787109375e0), SC_(-0.31153951624955756434303873284759634801131236594004) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.1992881298065185546875e1), SC_(-0.57134179001101895426174918063867092457941541295507) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.3915013790130615234375e1), SC_(0.014084292266465387671395167120939259589073512924039) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.79858455657958984375e1), SC_(-0.22476853968317214175668684393591069876083251260042) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.1571910858154296875e2), SC_(-0.14410426741350497805067959400220228144811652583962) }}, {{ SC_(0.298964977264404296875e-1), SC_(0.31483119964599609375e2), SC_(0.097284960842721393212129686759239789256691963503028) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.553809732082299888134002685546875e-4), SC_(471.37166027199904636448992655317335001891374159055) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.69304020144045352935791015625e-4), SC_(379.91116285051480646999270370930575306961149889076) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.23264062474481761455535888671875e-3), SC_(118.5284534444992075821831811768895269929912679192) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.4480001516640186309814453125e-3), SC_(63.108590829623409668728674133337195241661276845369) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.5502865533344447612762451171875e-3), SC_(51.782740477944861994269980994470261382762600222885) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.19227224402129650115966796875e-2), SC_(15.544268928226126013996693399734864212029429548413) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.37370622158050537109375e-2), SC_(8.201851891655569453083763318076996379118826086076) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.47696642577648162841796875e-2), SC_(6.4855739049686344648114313800340052759496043249306) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.1275280676782131195068359375e-1), SC_(2.5138871135928275926305029572436771696322567881157) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.20440109074115753173828125e-1), SC_(1.5916781747744183611274648494292175428501268833477) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.3429813683032989501953125e-1), SC_(0.95799797262309709141604993694108452124333919330399) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.96701286733150482177734375e-1), SC_(0.31579947123617941869611707561671330150093828419791) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.159812271595001220703125e0), SC_(0.14888173291743319960009767579178948429207967528609) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.297095477581024169921875e0), SC_(-0.015024472899673308434232353549495206900642161504769) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.77344071865081787109375e0), SC_(-0.29871719574571292554481591851730285072696777681315) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.1992881298065185546875e1), SC_(-0.5695170506150984259661777633403544300740993771699) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.3915013790130615234375e1), SC_(0.0088241564811086707700323604495282469314479926180765) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.79858455657958984375e1), SC_(-0.22252074121304244082814905021275049155573635418883) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.1571910858154296875e2), SC_(-0.14591516715942387781225219256610088658797868602279) }}, {{ SC_(0.381573140621185302734375e-1), SC_(0.31483119964599609375e2), SC_(0.098622081487985938170665823000958903932402318502123) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.553809732082299888134002685546875e-4), SC_(664.32533220017027254391971447388193587419000066854) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.69304020144045352935791015625e-4), SC_(543.14993593518730741749191498326451276400043639821) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.23264062474481761455535888671875e-3), SC_(183.08336288980652399978057154064375325217723169095) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.4480001516640186309814453125e-3), SC_(101.64612195822514506176998699703728506643345094973) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.5502865533344447612762451171875e-3), SC_(84.506782718783720410448144330858098521084558727765) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.19227224402129650115966796875e-2), SC_(27.478220778710823046480038139592344032974668283707) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.37370622158050537109375e-2), SC_(15.128612926718659706649583727766003486783508333581) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.47696642577648162841796875e-2), SC_(12.151610485805330583680296655400661422227790007773) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.1275280676782131195068359375e-1), SC_(5.0211988998270532788268629016500275009843181242807) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.20440109074115753173828125e-1), SC_(3.2833219226395894112637198307152793560437862511832) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.3429813683032989501953125e-1), SC_(2.0554845436111618577861954626046424038152843282732) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.96701286733150482177734375e-1), SC_(0.77926568698038937491970225128994882478930938769704) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.159812271595001220703125e0), SC_(0.45721448413953804880695655665538011048753399905673) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.297095477581024169921875e0), SC_(0.17595838820313970743143597894791134659072435368234) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.77344071865081787109375e0), SC_(-0.20234566166487137369485686737700596512087693740505) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.1992881298065185546875e1), SC_(-0.55245918030755774838887327767713821647691140899172) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.3915013790130615234375e1), SC_(-0.031569198201922343172110667422174391061517226818925) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.79858455657958984375e1), SC_(-0.2039691459012116792448785415127453560623250119731) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.1571910858154296875e2), SC_(-0.15904726852684046112032774465846226271684901212158) }}, {{ SC_(0.10202245414257049560546875e0), SC_(0.31483119964599609375e2), SC_(0.10837642621725891831814701112308531098361497776006) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.553809732082299888134002685546875e-4), SC_(571.56461253029527068669000527929821362358876374892) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.69304020144045352935791015625e-4), SC_(473.79891993387176204277266117549424341033534115977) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.23264062474481761455535888671875e-3), SC_(172.05485839720109929947386950671741510964174125916) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.4480001516640186309814453125e-3), SC_(99.451419236599843003505543369104449891542801629795) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.5502865533344447612762451171875e-3), SC_(83.734472657295616189146164005523297644578211848323) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.19227224402129650115966796875e-2), SC_(29.404772483993622542588632660044020277977277726233) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.37370622158050537109375e-2), SC_(16.864978089537872687292665548563751461942199756629) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.47696642577648162841796875e-2), SC_(13.751298647148757554892114002160659377601354266307) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.1275280676782131195068359375e-1), SC_(6.0380360220553402596187004316610073017626864386626) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.20440109074115753173828125e-1), SC_(4.0663497714573359019588027393685113619794756585739) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.3429813683032989501953125e-1), SC_(2.6316996446281341936928939605476135172192414133571) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.96701286733150482177734375e-1), SC_(1.0800675534525642651799516999243058856882873167878) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.159812271595001220703125e0), SC_(0.67608209128463307278540094735467713432457749748998) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.297095477581024169921875e0), SC_(0.32608584374570126390899798719606813371587094547022) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.77344071865081787109375e0), SC_(-0.11501166816312720077701173878978907536708382694762) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.1992881298065185546875e1), SC_(-0.5314728961847169395439663807244209484201806638345) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.3915013790130615234375e1), SC_(-0.069744289285064377675956918739400471810698462043296) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.79858455657958984375e1), SC_(-0.18428739558678179918427752660934248572747222415676) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.1571910858154296875e2), SC_(-0.1701631830918606829888917633341779466808057826876) }}, {{ SC_(0.163520872592926025390625e0), SC_(0.31483119964599609375e2), SC_(0.11673308889048171105260368484675293209410925971813) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.553809732082299888134002685546875e-4), SC_(308.58717356564466122617332899775649932714521649465) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.69304020144045352935791015625e-4), SC_(262.24338485799954579780263297984006371132805035765) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.23264062474481761455535888671875e-3), SC_(108.9140590822161623522014027028903621483296652945) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.4480001516640186309814453125e-3), SC_(67.698524590607803770047215956766889859219483667364) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.5502865533344447612762451171875e-3), SC_(58.314147078221691243234467406671269644673760065121) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.19227224402129650115966796875e-2), SC_(23.524741367197420763016782522906886655519879108938) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.37370622158050537109375e-2), SC_(14.524298936061566153087691391710501642546074047005) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.47696642577648162841796875e-2), SC_(12.167592249583090776182625308742942167019780554995) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.1275280676782131195068359375e-1), SC_(5.9591275776624168861248857531487249839683845595979) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.20440109074115753173828125e-1), SC_(4.2299993011890053254279767431385415972934287315434) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.3429813683032989501953125e-1), SC_(2.901983653662807706186712037814246852226231939235) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.96701286733150482177734375e-1), SC_(1.3496909380852439982995232509799172125294458203756) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.159812271595001220703125e0), SC_(0.91242525126551893446034914814532227010185508362973) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.297095477581024169921875e0), SC_(0.52064973039523048311960600009969390809510145563536) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.77344071865081787109375e0), SC_(0.02608182887713046998809955385365744878009456148488) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.1992881298065185546875e1), SC_(-0.48404394822521381052237521035874668152259518700201) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.3915013790130615234375e1), SC_(-0.13570201616386784215064959012924578121705433926688) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.79858455657958984375e1), SC_(-0.14498096948845041264536656900929936579020113377736) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.1571910858154296875e2), SC_(-0.18612546203267788136068772916555345383472834252897) }}, {{ SC_(0.27438509464263916015625e0), SC_(0.31483119964599609375e2), SC_(0.12899781806261234090869739907021396206645515298816) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.553809732082299888134002685546875e-4), SC_(4.5011877008533588406242902236972176812286396782147) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.69304020144045352935791015625e-4), SC_(4.2783592963711542722485419051158488559847591811376) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.23264062474481761455535888671875e-3), SC_(3.2524659231367346417319767900467632749684587310339) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.4480001516640186309814453125e-3), SC_(2.8040379463680128740339422361998161891966695531645) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.5502865533344447612762451171875e-3), SC_(2.6764851124726492809937356104371686943624485612184) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.19227224402129650115966796875e-2), SC_(2.0163238633002003883069078490143730782017724876012) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.37370622158050537109375e-2), SC_(1.7346779498572830113915766279181497675283514219914) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.47696642577648162841796875e-2), SC_(1.6414560048736575318308206797185026809228580164098) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.1275280676782131195068359375e-1), SC_(1.3137218795657822490779781671024980814327832331883) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.20440109074115753173828125e-1), SC_(1.180498075807418501180599163023571364750679628292) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.3429813683032989501953125e-1), SC_(1.0495646967259391880319945252197306235384421843019) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.96701286733150482177734375e-1), SC_(0.82660826007368357107844931444771102363686958247508) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.159812271595001220703125e0), SC_(0.731697482250621946652780569750887216236363899678) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.297095477581024169921875e0), SC_(0.61562951899129792899436180038485577042502506518948) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.77344071865081787109375e0), SC_(0.36903938849520530212100602283754257446521956733474) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.1992881298065185546875e1), SC_(-0.19291140031800296501062914346386249321856024518691) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.3915013790130615234375e1), SC_(-0.35154036868679467260867304469480385731081099786064) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.79858455657958984375e1), SC_(0.059788933964965057005597574789855169709617546272128) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.1571910858154296875e2), SC_(-0.18723724545953900368479270357924724748499087579889) }}, {{ SC_(0.773610293865203857421875e0), SC_(0.31483119964599609375e2), SC_(0.13400966478970684572882507496313188732146052204823) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.553809732082299888134002685546875e-4), SC_(0.029850558043384652101507429968555915143293202103747) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.69304020144045352935791015625e-4), SC_(0.031774415911652133140438383435382850754016739448122) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.23264062474481761455535888671875e-3), SC_(0.044519196152686710899624947084732057474064859756012) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.4480001516640186309814453125e-3), SC_(0.05343253965558058233007650357966646952486068878882) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.5502865533344447612762451171875e-3), SC_(0.056582050509995888920320047141538194664133884681765) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.19227224402129650115966796875e-2), SC_(0.080166705694688052505251448743101310730920964564891) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.37370622158050537109375e-2), SC_(0.096465313480839719026158485392665569685381937552601) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.47696642577648162841796875e-2), SC_(0.10324738754283731303233215056391131014396578323982) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.1275280676782131195068359375e-1), SC_(0.13577304320543918389355602959763206583957881062266) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.20440109074115753173828125e-1), SC_(0.15482474065003848502331515636750756782541403873783) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.3429813683032989501953125e-1), SC_(0.17879300147557342620703893492988364828644117397711) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.96701286733150482177734375e-1), SC_(0.23807839596703794694358205999845219045526959814198) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.159812271595001220703125e0), SC_(0.27258280278021451601361913139001300975146484153291) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.297095477581024169921875e0), SC_(0.3182433247889726108818474117334822562641936486915) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.77344071865081787109375e0), SC_(0.35683698469364376739850271914475103829253363482033) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.1992881298065185546875e1), SC_(0.070741464135753463004945635716734698943142968309161) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.3915013790130615234375e1), SC_(-0.39520273941287401008062462430234282654359660068325) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.79858455657958984375e1), SC_(0.22731076694710148914187566403459737901915531083197) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.1571910858154296875e2), SC_(-0.084753297042445161674776706201678874508373230926603) }}, {{ SC_(0.1278498172760009765625e1), SC_(0.31483119964599609375e2), SC_(0.062225090158300477948826393889918289525552791431653) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.553809732082299888134002685546875e-4), SC_(2.1701155503596191995420732909718061056519326940212e-07) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.69304020144045352935791015625e-4), SC_(2.9551306553591138969355587313633131125997108375235e-07) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.23264062474481761455535888671875e-3), SC_(1.5655037999064767060378816153887775846765797047542e-06) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.4480001516640186309814453125e-3), SC_(3.8589657176343035828125278487873301105081231582557e-06) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.5502865533344447612762451171875e-3), SC_(5.1218954522128421501593736983874506030386512416042e-06) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.19227224402129650115966796875e-2), SC_(2.8672424699646570395201270796019428364107586215741e-05) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.37370622158050537109375e-2), SC_(7.1584131269989352016160990684310779348068505393798e-05) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.47696642577648162841796875e-2), SC_(0.00010016008067897047409150409831104755079644144359547) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.1275280676782131195068359375e-1), SC_(0.00038790640527498589848030243407349786907898487932215) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.20440109074115753173828125e-1), SC_(0.00074264228806456515397818291416507336565139941621982) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.3429813683032989501953125e-1), SC_(0.0015143065765106452690160624557993131465970744618239) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.96701286733150482177734375e-1), SC_(0.0063022557752983131925389842798930716204158533142837) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.159812271595001220703125e0), SC_(0.012557870640894605088772791192937453429777750849756) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.297095477581024169921875e0), SC_(0.029237072013682764068068954048522330751472665213812) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.77344071865081787109375e0), SC_(0.10168572061348920979793506543435383085628690885422) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.1992881298065185546875e1), SC_(0.22002878862596836274705220424499496372405634108772) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.3915013790130615234375e1), SC_(-0.10735465363172394169227652967155355244369432964178) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.79858455657958984375e1), SC_(0.18557681844475882257368896788898742437796376971596) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.1571910858154296875e2), SC_(0.18371304256631794662900176415524300546583527613927) }}, {{ SC_(0.2376763820648193359375e1), SC_(0.31483119964599609375e2), SC_(-0.132794081024849303698958724423239291321967763688) }}, {{ SC_(0.618752574920654296875e1), SC_(0.553809732082299888134002685546875e-4), SC_(6.8618859334909328064313466022394478855895492126519e-27) }}, {{ SC_(0.618752574920654296875e1), SC_(0.69304020144045352935791015625e-4), SC_(2.1963286138774191146212025856359161441752536770309e-26) }}, {{ SC_(0.618752574920654296875e1), SC_(0.23264062474481761455535888671875e-3), SC_(1.1747834954200665458190549366081650771028030041504e-23) }}, {{ SC_(0.618752574920654296875e1), SC_(0.4480001516640186309814453125e-3), SC_(3.5179470865688125605246868941659466149519669762622e-22) }}, {{ SC_(0.618752574920654296875e1), SC_(0.5502865533344447612762451171875e-3), SC_(1.0223298989181615516658896945180863312854077986829e-21) }}, {{ SC_(0.618752574920654296875e1), SC_(0.19227224402129650115966796875e-2), SC_(6.7315860122034580871008571630351185332456357893131e-19) }}, {{ SC_(0.618752574920654296875e1), SC_(0.37370622158050537109375e-2), SC_(2.1149902345470196631249308634396410671647936549547e-17) }}, {{ SC_(0.618752574920654296875e1), SC_(0.47696642577648162841796875e-2), SC_(7.4983438891842891949410561775177614183558926276208e-17) }}, {{ SC_(0.618752574920654296875e1), SC_(0.1275280676782131195068359375e-1), SC_(1.2321058610359859670269189410586432608108543114872e-14) }}, {{ SC_(0.618752574920654296875e1), SC_(0.20440109074115753173828125e-1), SC_(1.4238028742033350327295610376208111939565068601957e-13) }}, {{ SC_(0.618752574920654296875e1), SC_(0.3429813683032989501953125e-1), SC_(2.0870108710052736709734956183853084596264302832559e-12) }}, {{ SC_(0.618752574920654296875e1), SC_(0.96701286733150482177734375e-1), SC_(4.5142628098260017065921905421191994854871890889804e-10) }}, {{ SC_(0.618752574920654296875e1), SC_(0.159812271595001220703125e0), SC_(6.1103562371576358382673002203839388993107168425553e-09) }}, {{ SC_(0.618752574920654296875e1), SC_(0.297095477581024169921875e0), SC_(1.519636746861460104553494708390828117800452172163e-07) }}, {{ SC_(0.618752574920654296875e1), SC_(0.77344071865081787109375e0), SC_(2.1237148222110387293617790655585931062215718762736e-05) }}, {{ SC_(0.618752574920654296875e1), SC_(0.1992881298065185546875e1), SC_(0.0024588707692055920796691283803993300690882442105627) }}, {{ SC_(0.618752574920654296875e1), SC_(0.3915013790130615234375e1), SC_(0.046142562971005864860944948899495431154518217952264) }}, {{ SC_(0.618752574920654296875e1), SC_(0.79858455657958984375e1), SC_(-0.036548537606470732421518346681033426360824355915209) }}, {{ SC_(0.618752574920654296875e1), SC_(0.1571910858154296875e2), SC_(-0.037440476178607689137062960891986908987275885225747) }}, {{ SC_(0.618752574920654296875e1), SC_(0.31483119964599609375e2), SC_(-0.053576073500905579152051157218411132644761366492076) }}, {{ SC_(0.15943050384521484375e2), SC_(0.553809732082299888134002685546875e-4), SC_(3.5053748870324995265456069209257845719284000016634e-81) }}, {{ SC_(0.15943050384521484375e2), SC_(0.69304020144045352935791015625e-4), SC_(1.0003578068450191800043421410644801174017783442525e-79) }}, {{ SC_(0.15943050384521484375e2), SC_(0.23264062474481761455535888671875e-3), SC_(7.2295444983737221812617930416172046668810632639086e-72) }}, {{ SC_(0.15943050384521484375e2), SC_(0.4480001516640186309814453125e-3), SC_(1.2935778727519334502228823307340051077028641833215e-67) }}, {{ SC_(0.15943050384521484375e2), SC_(0.5502865533344447612762451171875e-3), SC_(2.7949076296376557021885976463896668140336092550744e-66) }}, {{ SC_(0.15943050384521484375e2), SC_(0.19227224402129650115966796875e-2), SC_(3.6757041380152731439397127857389554537960795984033e-58) }}, {{ SC_(0.15943050384521484375e2), SC_(0.37370622158050537109375e-2), SC_(7.5528355643960719116071021399542489454669220709129e-54) }}, {{ SC_(0.15943050384521484375e2), SC_(0.47696642577648162841796875e-2), SC_(2.8935963637630571857817897238455867910507638566588e-52) }}, {{ SC_(0.15943050384521484375e2), SC_(0.1275280676782131195068359375e-1), SC_(6.9804316898025259378717377799203520816940258467987e-46) }}, {{ SC_(0.15943050384521484375e2), SC_(0.20440109074115753173828125e-1), SC_(8.0421875393174843026599169482683520199102109359004e-43) }}, {{ SC_(0.15943050384521484375e2), SC_(0.3429813683032989501953125e-1), SC_(1.8381331544029745344694037671121786066061079707414e-39) }}, {{ SC_(0.15943050384521484375e2), SC_(0.96701286733150482177734375e-1), SC_(9.7973210467711664664952969673463280706045049213375e-33) }}, {{ SC_(0.15943050384521484375e2), SC_(0.159812271595001220703125e0), SC_(1.7833373802207954525116645092242418737555089885756e-29) }}, {{ SC_(0.15943050384521484375e2), SC_(0.297095477581024169921875e0), SC_(1.8824962469467906426300941758297149966409708294099e-25) }}, {{ SC_(0.15943050384521484375e2), SC_(0.77344071865081787109375e0), SC_(3.0224248046138209957759204404908493425528586816012e-19) }}, {{ SC_(0.15943050384521484375e2), SC_(0.1992881298065185546875e1), SC_(3.9661637521587291221956898563816149044021936980709e-13) }}, {{ SC_(0.15943050384521484375e2), SC_(0.3915013790130615234375e1), SC_(7.9002899016129279712962003653587507151377945199827e-09) }}, {{ SC_(0.15943050384521484375e2), SC_(0.79858455657958984375e1), SC_(0.00014361841243492096755775570171774438376661025382511) }}, {{ SC_(0.15943050384521484375e2), SC_(0.1571910858154296875e2), SC_(0.062984203221968378735689416171937661262267669219313) }}, {{ SC_(0.15943050384521484375e2), SC_(0.31483119964599609375e2), SC_(0.048726541788000567271971666259984984863708245546479) }}, {{ SC_(0.31320110321044921875e2), SC_(0.553809732082299888134002685546875e-4), SC_(4.0775347617763827917636312558685682614460296107351e-172) }}, {{ SC_(0.31320110321044921875e2), SC_(0.69304020144045352935791015625e-4), SC_(3.6602525887553747946846569939947031192010308649901e-169) }}, {{ SC_(0.31320110321044921875e2), SC_(0.23264062474481761455535888671875e-3), SC_(3.2335500910719629265098050470900045320840646714859e-153) }}, {{ SC_(0.31320110321044921875e2), SC_(0.4480001516640186309814453125e-3), SC_(1.375811039138230237509060754300309226643944989626e-144) }}, {{ SC_(0.31320110321044921875e2), SC_(0.5502865533344447612762451171875e-3), SC_(7.0221526672657324482881656358705892542540431557517e-142) }}, {{ SC_(0.31320110321044921875e2), SC_(0.19227224402129650115966796875e-2), SC_(2.0903831170965663042808465354655697911514904752221e-125) }}, {{ SC_(0.31320110321044921875e2), SC_(0.37370622158050537109375e-2), SC_(1.1776766990907131544102457790255832296878257403093e-116) }}, {{ SC_(0.31320110321044921875e2), SC_(0.47696642577648162841796875e-2), SC_(1.9216247227927533544279814467673995609976280557166e-113) }}, {{ SC_(0.31320110321044921875e2), SC_(0.1275280676782131195068359375e-1), SC_(1.7136891099016486824251149584090773081176918430606e-100) }}, {{ SC_(0.31320110321044921875e2), SC_(0.20440109074115753173828125e-1), SC_(2.7914984872320211168187337887690887640432614280739e-94) }}, {{ SC_(0.31320110321044921875e2), SC_(0.3429813683032989501953125e-1), SC_(1.8256226510148527935317893516684443597280757769692e-87) }}, {{ SC_(0.31320110321044921875e2), SC_(0.96701286733150482177734375e-1), SC_(8.1345764464977027290798421463540075558737704545228e-74) }}, {{ SC_(0.31320110321044921875e2), SC_(0.159812271595001220703125e0), SC_(3.3531596261917949046621108542546348529678441385801e-67) }}, {{ SC_(0.31320110321044921875e2), SC_(0.297095477581024169921875e0), SC_(4.8978868001918715331354461307339987339721794255557e-59) }}, {{ SC_(0.31320110321044921875e2), SC_(0.77344071865081787109375e0), SC_(1.9370088688037995439389481817923380471357651000902e-46) }}, {{ SC_(0.31320110321044921875e2), SC_(0.1992881298065185546875e1), SC_(5.4737238540903762602781816763163779144308589723619e-34) }}, {{ SC_(0.31320110321044921875e2), SC_(0.3915013790130615234375e1), SC_(3.881678194319896190940421213131620834895771313082e-25) }}, {{ SC_(0.31320110321044921875e2), SC_(0.79858455657958984375e1), SC_(6.3193787632639199392093155246439027531457067096666e-16) }}, {{ SC_(0.31320110321044921875e2), SC_(0.1571910858154296875e2), SC_(1.0757417878047579347014714535384238216124501720368e-07) }}, {{ SC_(0.31320110321044921875e2), SC_(0.31483119964599609375e2), SC_(0.040110799787632381784207142268257697341685918101293) }}, {{ SC_(0.638867645263671875e2), SC_(0.553809732082299888134002685546875e-4), SC_(9.7441627699885499410827511483200119322124780648042e-375) }}, {{ SC_(0.638867645263671875e2), SC_(0.69304020144045352935791015625e-4), SC_(1.2995106109464785944326424074902975173100812521663e-368) }}, {{ SC_(0.638867645263671875e2), SC_(0.23264062474481761455535888671875e-3), SC_(1.5404062639522853160415873118716407582565237381265e-335) }}, {{ SC_(0.638867645263671875e2), SC_(0.4480001516640186309814453125e-3), SC_(1.2154677714932701807701788654862612084731965495875e-317) }}, {{ SC_(0.638867645263671875e2), SC_(0.5502865533344447612762451171875e-3), SC_(5.0258196383445896775189854678057167837900551572717e-312) }}, {{ SC_(0.638867645263671875e2), SC_(0.19227224402129650115966796875e-2), SC_(7.4016350970405039598626088642455006858620983926416e-278) }}, {{ SC_(0.638867645263671875e2), SC_(0.37370622158050537109375e-2), SC_(1.0454698907387783780995294442636270647131473144215e-259) }}, {{ SC_(0.638867645263671875e2), SC_(0.47696642577648162841796875e-2), SC_(4.8154258474909796291892217560161879062331113459005e-253) }}, {{ SC_(0.638867645263671875e2), SC_(0.1275280676782131195068359375e-1), SC_(3.4890053812228262365551933998185601135755662319548e-226) }}, {{ SC_(0.638867645263671875e2), SC_(0.20440109074115753173828125e-1), SC_(2.6716519485260519907154162062382147851855142100751e-213) }}, {{ SC_(0.638867645263671875e2), SC_(0.3429813683032989501953125e-1), SC_(3.6553234108502009052689983290899255876096233293036e-199) }}, {{ SC_(0.638867645263671875e2), SC_(0.96701286733150482177734375e-1), SC_(7.4494817279246493182746623255291237577365435287533e-171) }}, {{ SC_(0.638867645263671875e2), SC_(0.159812271595001220703125e0), SC_(3.9137994342944840648848064301593067243483912784954e-157) }}, {{ SC_(0.638867645263671875e2), SC_(0.297095477581024169921875e0), SC_(3.3651957455367603520477072956196864467681836841573e-140) }}, {{ SC_(0.638867645263671875e2), SC_(0.77344071865081787109375e0), SC_(4.5449584997779609452485892006864158282660967869106e-114) }}, {{ SC_(0.638867645263671875e2), SC_(0.1992881298065185546875e1), SC_(3.1738690593564315149084568119212749276724766074797e-88) }}, {{ SC_(0.638867645263671875e2), SC_(0.3915013790130615234375e1), SC_(8.3876764286771252132826802696540899650253274908687e-70) }}, {{ SC_(0.638867645263671875e2), SC_(0.79858455657958984375e1), SC_(2.0360585647990444278788749162236601635563310041312e-50) }}, {{ SC_(0.638867645263671875e2), SC_(0.1571910858154296875e2), SC_(3.0526073572369540920510993833683057297997072099125e-32) }}, {{ SC_(0.638867645263671875e2), SC_(0.31483119964599609375e2), SC_(1.3013718253615034389340624948143462041150530900802e-14) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.553809732082299888134002685546875e-4), SC_(-8.0352542252744082481307789764332850495725489505518) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.69304020144045352935791015625e-4), SC_(-6.4203614240557396975159598870215603286914369267472) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.23264062474481761455535888671875e-3), SC_(-1.9117166148811325766281752377913954732416206414629) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.4480001516640186309814453125e-3), SC_(-0.99260548284661030715869392644415963191732106033528) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.5502865533344447612762451171875e-3), SC_(-0.80812102308096530154610129316254886762601435421338) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.19227224402129650115966796875e-2), SC_(-0.23204280558098084511900377653875824621676552518528) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.37370622158050537109375e-2), SC_(-0.12072881073365528081110447354284280286097688241442) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.47696642577648162841796875e-2), SC_(-0.09550482234825882986471274711567749300336105446854) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.1275280676782131195068359375e-1), SC_(-0.041200536588552429584692663160666456452528166189948) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.20440109074115753173828125e-1), SC_(-0.031953857997720357584406329160755725345223306098128) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.3429813683032989501953125e-1), SC_(-0.030114397251918849407455448148697810176670467012896) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.96701286733150482177734375e-1), SC_(-0.052943922496156634733598654692054268878542225130523) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.159812271595001220703125e0), SC_(-0.082512406889389859121119964777034049609087542474697) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.297095477581024169921875e0), SC_(-0.1485255232855737930936769690388900259610771996183) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.77344071865081787109375e0), SC_(-0.35921701000936262458882788686129315404924380806201) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.1992881298065185546875e1), SC_(-0.57725076140254553359619035776337545293419911217499) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.3915013790130615234375e1), SC_(0.03344057878006016634512803472601346746069423389441) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.79858455657958984375e1), SC_(-0.23270933528743421315094393225058324641266170812782) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.1571910858154296875e2), SC_(-0.13724241991231743790482116318841294154717999058952) }}, {{ SC_(-0.4430477856658399105072021484375e-3), SC_(0.31483119964599609375e2), SC_(0.09223345027076750470936443925038834150827279095626) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.553809732082299888134002685546875e-4), SC_(-10.066461933961981507792651012082779846170093092464) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.69304020144045352935791015625e-4), SC_(-8.0431411620505830001205801846984349465397924171235) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.23264062474481761455535888671875e-3), SC_(-2.3945631396997411883835874017501010814598653177206) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.4480001516640186309814453125e-3), SC_(-1.24317801002101410502924982177759462923499541887) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.5502865533344447612762451171875e-3), SC_(-1.0120758401869629091718060378244288438918105198374) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.19227224402129650115966796875e-2), SC_(-0.290343027908152859987594626260946647758968814052) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.37370622158050537109375e-2), SC_(-0.15070540484639218955142273115487939108948046279471) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.47696642577648162841796875e-2), SC_(-0.11898654024366730550988334200337880054318356808187) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.1275280676782131195068359375e-1), SC_(-0.0499772596852495244874245461700334882818390416664) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.20440109074115753173828125e-1), SC_(-0.037430108063425835799519590547664772219450450501968) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.3429813683032989501953125e-1), SC_(-0.033380876891004635328352864168353940029550374102897) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.96701286733150482177734375e-1), SC_(-0.054114477302162225953130009474375517188926951365292) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.159812271595001220703125e0), SC_(-0.083232467669685253061367673958149012193392848388591) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.297095477581024169921875e0), SC_(-0.14893075527015439332896904430547462629618745403482) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.77344071865081787109375e0), SC_(-0.35939360026382634840654742706922579497977841714828) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.1992881298065185546875e1), SC_(-0.57727011342927087551404477979110589721068173726712) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.3915013790130615234375e1), SC_(0.033511712938247184637368117516909474935042592541487) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.79858455657958984375e1), SC_(-0.23273755930250967807670274825488612930894587031682) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.1571910858154296875e2), SC_(-0.1372166286029628510440359619069144703727812571868) }}, {{ SC_(-0.554432161152362823486328125e-3), SC_(0.31483119964599609375e2), SC_(0.092214506134989611076380630559393619074408058160705) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.553809732082299888134002685546875e-4), SC_(-34.23181462635478507822028182175431717667781372624) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.69304020144045352935791015625e-4), SC_(-27.343305234815061782266099942561415206187905358958) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.23264062474481761455535888671875e-3), SC_(-8.1273848706336958801247737688897901209292092021741) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.4480001516640186309814453125e-3), SC_(-4.2154668275747577532914376948639503328977697483243) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.5502865533344447612762451171875e-3), SC_(-3.4306834084062242073710579346983737042959836829079) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.19227224402129650115966796875e-2), SC_(-0.98047811481492919485194315319699114598506569880073) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.37370622158050537109375e-2), SC_(-0.50522334567765460611684549984928050137085344804579) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.47696642577648162841796875e-2), SC_(-0.39659709058903377385769093723835590470045000851205) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.1275280676782131195068359375e-1), SC_(-0.15359498622072033524837235497894371364376142666273) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.20440109074115753173828125e-1), SC_(-0.10203933275007621452849842412025700533200021422624) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.3429813683032989501953125e-1), SC_(-0.071890730780152667728329364548984000561104628670664) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.067894161135302898753927696333004765903404565336037) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.159812271595001220703125e0), SC_(-0.091702795042273366918864368933079051253776349615004) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.297095477581024169921875e0), SC_(-0.15369330938238308353603724941747339435790440319313) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.77344071865081787109375e0), SC_(-0.36146603204720034107470261596786851111539114117332) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.1992881298065185546875e1), SC_(-0.57749584025045821649519328067660040724951358425785) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.3915013790130615234375e1), SC_(0.034346238192839986437454661389726380162962796912464) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.79858455657958984375e1), SC_(-0.23306815103996906158022747899333186165145736610782) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.1571910858154296875e2), SC_(-0.13691373838339331226340502813220267438067995036718) }}, {{ SC_(-0.186112499795854091644287109375e-2), SC_(0.31483119964599609375e2), SC_(0.0919920513180825947021514188521270090148213581859) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.553809732082299888134002685546875e-4), SC_(-67.056271870501367994225299855943649508994694008781) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.69304020144045352935791015625e-4), SC_(-53.54175363140112840600408722647405310378615327513) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.23264062474481761455535888671875e-3), SC_(-15.881207988567703715841269602542397948644528477246) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.4480001516640186309814453125e-3), SC_(-8.2277264602230928321577393634479731870258896542248) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.5502865533344447612762451171875e-3), SC_(-6.6935299793980016595106177046127151318109557942752) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.19227224402129650115966796875e-2), SC_(-1.9080343185556542996070263658766565867706699008104) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.37370622158050537109375e-2), SC_(-0.98075508769550439856427681584737488373549344454508) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.47696642577648162841796875e-2), SC_(-0.76869690974782950106133359949158417619515396821915) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.1275280676782131195068359375e-1), SC_(-0.29207097823754910281828673784976328503050496866988) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.20440109074115753173828125e-1), SC_(-0.18826130081197235022050368628059551681437423139242) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.3429813683032989501953125e-1), SC_(-0.12320242306806411399618773723522603088969456177809) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.086196741643040794918353323989169170469643966496374) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.159812271595001220703125e0), SC_(-0.10293588278606317172915919860376209690449043973811) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.297095477581024169921875e0), SC_(-0.15999703383708213928376998492609103192731212394886) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.77344071865081787109375e0), SC_(-0.36420072514576095375697021685081027415781263362758) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.1992881298065185546875e1), SC_(-0.5777897961065323135784411639495384785398961081964) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.3915013790130615234375e1), SC_(0.035446621494767570487811034376588469298122718716537) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.79858455657958984375e1), SC_(-0.23350258387760681986463355584579626915696673116663) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.1571910858154296875e2), SC_(-0.13651347032628514403227301964467648017065563110308) }}, {{ SC_(-0.35840012133121490478515625e-2), SC_(0.31483119964599609375e2), SC_(0.091698142960977290200573339181083827107643995436865) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.553809732082299888134002685546875e-4), SC_(-83.037093324551699684264024514810856743180212901972) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.69304020144045352935791015625e-4), SC_(-66.289631714700939041160686151256998148675866512178) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.23264062474481761455535888671875e-3), SC_(-19.642901163509752389779868654081295474333346675263) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.4480001516640186309814453125e-3), SC_(-10.171088008319663671664133300271419189326470432375) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.5502865533344447612762451171875e-3), SC_(-8.2731052285936332381740047283964449451220912606779) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.19227224402129650115966796875e-2), SC_(-2.3556822683937317247313924442328408419058805410856) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.37370622158050537109375e-2), SC_(-1.2098723277414120717362840825349623627912664595916) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.47696642577648162841796875e-2), SC_(-0.9478703513414677389752274599534819040946861477237) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.1275280676782131195068359375e-1), SC_(-0.35858625576974802550691928581679940729588638492127) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.20440109074115753173828125e-1), SC_(-0.22962801236819251757397379209933685966997055419062) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.3429813683032989501953125e-1), SC_(-0.14778817682245036702917674194825307709095027340792) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.96701286733150482177734375e-1), SC_(-0.094943256228300421415696973236887828585507524283866) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.159812271595001220703125e0), SC_(-0.10829704020665712735091858934626890105404920145588) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.297095477581024169921875e0), SC_(-0.16300070709542560570938729145871767601360179849028) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.77344071865081787109375e0), SC_(-0.3655004483031575939694898478341350666944952239863) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.1992881298065185546875e1), SC_(-0.57792794944990254997704488561736555219857438938245) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.3915013790130615234375e1), SC_(0.035969277603863220159373882638485036321550606702405) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.79858455657958984375e1), SC_(-0.23370834076421522509139405806963960754726703194536) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.1571910858154296875e2), SC_(-0.13632299983189670750128563440512332933275681273293) }}, {{ SC_(-0.44022924266755580902099609375e-2), SC_(0.31483119964599609375e2), SC_(0.091558310240599352987648819858958500654626497622027) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.553809732082299888134002685546875e-4), SC_(-323.45213945463234229013889680154351663561974016062) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.69304020144045352935791015625e-4), SC_(-257.58113725156369155776353286297851561131398667063) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.23264062474481761455535888671875e-3), SC_(-75.317853600830156764876591365747013181276745596686) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.4480001516640186309814453125e-3), SC_(-38.719511928695320833962932311070646235997196088527) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.5502865533344447612762451171875e-3), SC_(-31.422940951603923960515705608615289434032537674218) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.19227224402129650115966796875e-2), SC_(-8.8228739279443535003892578553342007432481062429613) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.37370622158050537109375e-2), SC_(-4.494723735604328765849150940140384573461736537374) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.47696642577648162841796875e-2), SC_(-3.5094625015210048661409444547047934231422637263711) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.1275280676782131195068359375e-1), SC_(-1.2987840043766237769332520032909456200005454056879) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.20440109074115753173828125e-1), SC_(-0.81115532009477097779611346576000499612899829740578) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.3429813683032989501953125e-1), SC_(-0.49133226391051353605553180300057321370516441349176) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.96701286733150482177734375e-1), SC_(-0.2156781193538221291294131700670540860931335417735) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.159812271595001220703125e0), SC_(-0.18185780425851551020497584257730950378764999765613) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.297095477581024169921875e0), SC_(-0.20390584764589693945869205722862488999236954450902) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.77344071865081787109375e0), SC_(-0.38299131775239725628819178645949094448183644930876) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.1992881298065185546875e1), SC_(-0.57968991614193627415054042875367289442368646934083) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.3915013790130615234375e1), SC_(0.042982933758334960569313811710720824706658812629693) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.79858455657958984375e1), SC_(-0.23643275937887443493821264201271578938035690601526) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.1571910858154296875e2), SC_(-0.13374504140868466884225855542680423136816728178356) }}, {{ SC_(-0.153817795217037200927734375e-1), SC_(0.31483119964599609375e2), SC_(0.089667322440366316066610578376619970625122122450226) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.553809732082299888134002685546875e-4), SC_(-725.60388812634502116497577581096174464417453225645) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.69304020144045352935791015625e-4), SC_(-575.95680685121341045918860034843655536920144089988) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.23264062474481761455535888671875e-3), SC_(-165.47781280790728282138565486596148860048073676555) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.4480001516640186309814453125e-3), SC_(-84.263583652514398857809003219385428308331914261355) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.5502865533344447612762451171875e-3), SC_(-68.180449557757530865047254894621656951671344565923) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.19227224402129650115966796875e-2), SC_(-18.798084691116705356273612415274160601829996663749) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.37370622158050537109375e-2), SC_(-9.4830284139916943844187972919233437926322988775231) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.47696642577648162841796875e-2), SC_(-7.3771153920678228700152931806394953960549947325041) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.1275280676782131195068359375e-1), SC_(-2.6855256727116933276782927513072232408947873802069) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.20440109074115753173828125e-1), SC_(-1.659202091637520422183682309841553410776457852149) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.3429813683032989501953125e-1), SC_(-0.98607609795233336610497632483947698925553853348121) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.96701286733150482177734375e-1), SC_(-0.38515834407554964739621903400858160980698817286248) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.159812271595001220703125e0), SC_(-0.28381588884959607872655877768989540276971009686577) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.297095477581024169921875e0), SC_(-0.25970485572060694094796989362887049565598977652468) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.77344071865081787109375e0), SC_(-0.40625023849997096854581923443441253397060457051724) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.1992881298065185546875e1), SC_(-0.58175396157051217096634558063818100887320516756666) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.3915013790130615234375e1), SC_(0.052254646856877522738100400866085077989749826572634) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.79858455657958984375e1), SC_(-0.23992935887127384086006384290591685783732754240095) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.1571910858154296875e2), SC_(-0.13027418083029205026658210487081901945580698823601) }}, {{ SC_(-0.298964977264404296875e-1), SC_(0.31483119964599609375e2), SC_(0.087125939160498837675593513567607234396386781832874) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.553809732082299888134002685546875e-4), SC_(-1004.6859486021017541023203743332692346106393511949) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.69304020144045352935791015625e-4), SC_(-796.00547333588938545445386365357077325403216751374) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.23264062474481761455535888671875e-3), SC_(-226.42336780202248510553958166136698643505130141032) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.4480001516640186309814453125e-3), SC_(-114.67538358156769735145875983000068890294406176426) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.5502865533344447612762451171875e-3), SC_(-92.630113579906723071779947466604561257835459190343) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.19227224402129650115966796875e-2), SC_(-25.276228587228107324012897838280646226306407820917) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.37370622158050537109375e-2), SC_(-12.680763595940505459347521762950057239490506764601) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.47696642577648162841796875e-2), SC_(-9.8445493267327168890329951149142804596902310323753) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.1275280676782131195068359375e-1), SC_(-3.5529657578107153662393107250209547708707297913846) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.20440109074115753173828125e-1), SC_(-2.1845957832490827861233138950362163012593492434232) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.3429813683032989501953125e-1), SC_(-1.289323015773201826960839436618104305738849066685) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.96701286733150482177734375e-1), SC_(-0.486777735591057263230139625364066590512939127167) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.159812271595001220703125e0), SC_(-0.34427980661032442140812840139010665226749007184295) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.297095477581024169921875e0), SC_(-0.29233716519329701131207248408313295340191228187593) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.77344071865081787109375e0), SC_(-0.41954921569620798110383102549818658320238954428757) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.1992881298065185546875e1), SC_(-0.58279172954206145900906677183569582602038176823114) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.3915013790130615234375e1), SC_(0.05752957287882339804261284805013815435471324917482) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.79858455657958984375e1), SC_(-0.2418651953573152386189066686655477217073650188379) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.1571910858154296875e2), SC_(-0.12826743181414229865637491792217895852855237873308) }}, {{ SC_(-0.381573140621185302734375e-1), SC_(0.31483119964599609375e2), SC_(0.085658882263130460924983003926708821343532049465639) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.553809732082299888134002685546875e-4), SC_(-5021.4388835985321077822197612494180215228611508713) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.69304020144045352935791015625e-4), SC_(-3921.8734307134052994591437509299821025250295550788) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.23264062474481761455535888671875e-3), SC_(-1032.5478352822006422528531545457632557402051621165) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.4480001516640186309814453125e-3), SC_(-501.51400874744938819546320667109536265200736389128) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.5502865533344447612762451171875e-3), SC_(-399.8166333544894648442811208436079709080356432968) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.19227224402129650115966796875e-2), SC_(-100.71848232122494924067861671571417782212617327175) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.37370622158050537109375e-2), SC_(-48.425426594435213772677350265517725377950510169043) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.47696642577648162841796875e-2), SC_(-37.01056268120809544427519087487383951231992638864) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.1275280676782131195068359375e-1), SC_(-12.529870507977695417379290742548380462554156354031) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.20440109074115753173828125e-1), SC_(-7.4600218209139626431874029585042163259340745663875) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.3429813683032989501953125e-1), SC_(-4.2336827459776509543039633593470530591144486647929) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.96701286733150482177734375e-1), SC_(-1.4076911758039395419438678561352416140994516102487) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.159812271595001220703125e0), SC_(-0.87364245158685752884071312682168379947181270610304) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.297095477581024169921875e0), SC_(-0.56581981271073774131848134488035157368952382106283) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.77344071865081787109375e0), SC_(-0.52334641335918569867220708820460190469418647348557) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.1992881298065185546875e1), SC_(-0.58733582447097000423159278592022563252973067325037) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.3915013790130615234375e1), SC_(0.098148426611487347492824812034647890766195227954355) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.79858455657958984375e1), SC_(-0.25545685118167396706373254697883910424384005529709) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.1571910858154296875e2), SC_(-0.11202340417340619861504442217252110116788114834578) }}, {{ SC_(-0.10202245414257049560546875e0), SC_(0.31483119964599609375e2), SC_(0.073839678247298834355739968654379935792127228391286) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.553809732082299888134002685546875e-4), SC_(-14591.064213061089165837423518828097507666158372983) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.69304020144045352935791015625e-4), SC_(-11239.902564268926556604507173940790761066763746957) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.23264062474481761455535888671875e-3), SC_(-2746.8530583911553657584614056005107923329244981864) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.4480001516640186309814453125e-3), SC_(-1281.4633935425504671800390512188925490804517939886) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.5502865533344447612762451171875e-3), SC_(-1008.7683405233342969507420679482719911493815317167) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.19227224402129650115966796875e-2), SC_(-235.30073204152926713716247008806375707592231157316) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.37370622158050537109375e-2), SC_(-108.60007981381217337152204100307858589475338051002) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.47696642577648162841796875e-2), SC_(-81.76344982413764784378525698316628482243640292672) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.1275280676782131195068359375e-1), SC_(-26.049679340717903315713103086676133509501408128064) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.20440109074115753173828125e-1), SC_(-15.058953341128067901598825812053678646049489146363) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.3429813683032989501953125e-1), SC_(-8.2670895889416687400487118206671710803622383007887) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.96701286733150482177734375e-1), SC_(-2.5425726441082783539097226104706324323282907944463) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.159812271595001220703125e0), SC_(-1.4914567252730700937853154883220220116181475377399) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.297095477581024169921875e0), SC_(-0.8632725176533903359858477333142360141675842731196) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.77344071865081787109375e0), SC_(-0.6234292886729097644681651354134756448566678345503) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.1992881298065185546875e1), SC_(-0.58558610668515311817834536848864645073035983132359) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.3915013790130615234375e1), SC_(0.13668651414168138934340967404720630620976656638158) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.79858455657958984375e1), SC_(-0.26612983518078324262431516120429976552320108816765) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.1571910858154296875e2), SC_(-0.095264523648592787444884232574176294732450669999133) }}, {{ SC_(-0.163520872592926025390625e0), SC_(0.31483119964599609375e2), SC_(0.06173752066484881976914818698955446252942030874574) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.553809732082299888134002685546875e-4), SC_(-70055.006417124017455883308196763018161565032369383) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.69304020144045352935791015625e-4), SC_(-52640.113594817198684386936391750444029168036133061) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.23264062474481761455535888671875e-3), SC_(-11248.203674019324536337199438466846592947765997285) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.4480001516640186309814453125e-3), SC_(-4879.8080035283893388040441594092795260474557634959) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.5502865533344447612762451171875e-3), SC_(-3754.7978085981910388267899865471598402118360736627) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.19227224402129650115966796875e-2), SC_(-762.39674662423880098867949611441126696630528369554) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.37370622158050537109375e-2), SC_(-326.87797411097895366160065584324895997801172344437) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.47696642577648162841796875e-2), SC_(-239.53186080281830983579670418013199291682381608593) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.1275280676782131195068359375e-1), SC_(-68.419850156793746757830431816786088124775866273892) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.20440109074115753173828125e-1), SC_(-37.525744669245238756963541430758905495168843320176) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.3429813683032989501953125e-1), SC_(-19.434623426150950622526401338014245375205379266868) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.96701286733150482177734375e-1), SC_(-5.278256043476905240140508445981318287783880252522) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.159812271595001220703125e0), SC_(-2.8777308956382304556048192286347294935922191210744) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.297095477581024169921875e0), SC_(-1.4710226796697763010123257766717571882497401271846) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.77344071865081787109375e0), SC_(-0.79642432308663174707004503487712244732812484279319) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.1992881298065185546875e1), SC_(-0.56612269402057352361688016332508188545049675733684) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.3915013790130615234375e1), SC_(0.20336091423685768783909328601206788571790985202848) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.79858455657958984375e1), SC_(-0.27894883313028255267330235996664759672024535305973) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.1571910858154296875e2), SC_(-0.062780398462795947357271687241684592413572950434451) }}, {{ SC_(-0.27438509464263916015625e0), SC_(0.31483119964599609375e2), SC_(0.03849732252340896827395694578850472049659073379106) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.553809732082299888134002685546875e-4), SC_(-11643371.160466587585669407134435084427919016477159) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.69304020144045352935791015625e-4), SC_(-7822272.1898300553801367114473307038320493340483874) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.23264062474481761455535888671875e-3), SC_(-913152.25026118026767706305376317815062318601678415) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.4480001516640186309814453125e-3), SC_(-285618.89217363187058048532649939516725880162268906) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.5502865533344447612762451171875e-3), SC_(-198328.24134808742495322686233204368763113096517048) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.19227224402129650115966796875e-2), SC_(-21564.309161499202266153010760285217055861424115293) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.37370622158050537109375e-2), SC_(-6635.2160485548545867927262596655119927287446001148) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.47696642577648162841796875e-2), SC_(-4304.6165067879596667544757848951548833552069326892) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.1275280676782131195068359375e-1), SC_(-752.48867462527562508752217575030123403028930518054) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.20440109074115753173828125e-1), SC_(-326.07771358935044259815120056192030387572987185451) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.3429813683032989501953125e-1), SC_(-130.38021269958001460550773617540933755870967270791) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.96701286733150482177734375e-1), SC_(-21.03494823343058616292489481214304589704518288651) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.159812271595001220703125e0), SC_(-8.8677490983754768902167272470145959243449594675605) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.297095477581024169921875e0), SC_(-3.2536197142376517989250287598790633341464382798799) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.77344071865081787109375e0), SC_(-0.97659448586055620157617924635446593965742594980785) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.1992881298065185546875e1), SC_(-0.20809799037495579932186690745545983420313992822374) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.3915013790130615234375e1), SC_(0.39703968367637254438174957792930593034151463586959) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.79858455657958984375e1), SC_(-0.22554028330521586002605540735602991496631898015283) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.1571910858154296875e2), SC_(0.093633855470003473208809563463409739430069350910437) }}, {{ SC_(-0.773610293865203857421875e0), SC_(0.31483119964599609375e2), SC_(-0.070461745595949681092731243985402876714254585230743) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.553809732082299888134002685546875e-4), SC_(3411563292.9669796968942111028927746747449026912013) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.69304020144045352935791015625e-4), SC_(2046598362.3380277794050000226232431427674677129183) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.23264062474481761455535888671875e-3), SC_(129630922.50446339331155017819677365672220689660444) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.4480001516640186309814453125e-3), SC_(29124927.143476381060749270075197015061256245381856) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.5502865533344447612762451171875e-3), SC_(18229319.979238976100645658531262040951818547006941) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.19227224402129650115966796875e-2), SC_(1053897.956929569185955175319621657818949265062221) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.37370622158050537109375e-2), SC_(231841.1058891395815352896585377817238414867631727) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.47696642577648162841796875e-2), SC_(132973.34058880932283158982294999835148475126525153) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.1275280676782131195068359375e-1), SC_(14143.154724499012452193671302600271852897387117945) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.20440109074115753173828125e-1), SC_(4827.0002138856521246867589597595652858439787350198) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.3429813683032989501953125e-1), SC_(1483.6553845873024913995747798876739824063717521137) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.96701286733150482177734375e-1), SC_(139.26739836871849880232137398143962623378368507862) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.159812271595001220703125e0), SC_(43.976463496518941763685458110029121972927739474599) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.297095477581024169921875e0), SC_(10.387458193796098091458741004438449603082306315889) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.77344071865081787109375e0), SC_(0.99240849019214068933320060350367869050615793023443) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.1992881298065185546875e1), SC_(0.38007621281164781816882276366718911085812475276781) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.3915013790130615234375e1), SC_(0.29403596953295701246022014094101894218001927703594) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.79858455657958984375e1), SC_(-0.01837951078983691561532112217348471277074821384291) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.1571910858154296875e2), SC_(0.19427115245753018672180398439230100630688488506532) }}, {{ SC_(-0.1278498172760009765625e1), SC_(0.31483119964599609375e2), SC_(-0.13799728876142446935574975446216803968015474106104) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.553809732082299888134002685546875e-4), SC_(-1052534856334011.1715539380253442490393529354168594) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.69304020144045352935791015625e-4), SC_(-493567972016271.98593229233453766283237137175644106) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.23264062474481761455535888671875e-3), SC_(-8268281865770.6799723507075477047670236530702536031) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.4480001516640186309814453125e-3), SC_(-904509767542.57871242723570720295130551599003784941) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.5502865533344447612762451171875e-3), SC_(-451681172344.62275199563178724755053271724610716152) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.19227224402129650115966796875e-2), SC_(-6609106181.9315655323865091360718866593066117802884) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.37370622158050537109375e-2), SC_(-700748933.32738239550418059678170023119352690168661) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.47696642577648162841796875e-2), SC_(-307446225.29443781072879309174993795877958539308929) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.1275280676782131195068359375e-1), SC_(-11104382.334915614447662856663000022842550526037284) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.20440109074115753173828125e-1), SC_(-2257745.0631981596507978280357107785541246723841944) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.3429813683032989501953125e-1), SC_(-393215.54108344107745778732644950546167752024313407) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.96701286733150482177734375e-1), SC_(-11875.215377301361527607788678372426690815266675372) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.159812271595001220703125e0), SC_(-2178.2043791543280008244860279137202543771878307036) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.297095477581024169921875e0), SC_(-268.80841515377336154846614677034462642010213198625) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.77344071865081787109375e0), SC_(-10.653831565503460653054171073382042711333639447853) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.1992881298065185546875e1), SC_(-0.46405184762078718718459838928519754469724229927788) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.3915013790130615234375e1), SC_(-0.37388358442212335882627303155170282309105103172024) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.79858455657958984375e1), SC_(0.2605248427954328669351611971306267348449505723959) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.1571910858154296875e2), SC_(-0.0044288367831751747332630422754772844341893323667545) }}, {{ SC_(-0.2376763820648193359375e1), SC_(0.31483119964599609375e2), SC_(-0.0034984374041546566085717607248133391319551924960149) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.553809732082299888134002685546875e-4), SC_(-51998884562397766833638082608780563.737710080783588) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.69304020144045352935791015625e-4), SC_(-10373958678561228310418298843892260.299325543471815) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.23264062474481761455535888671875e-3), SC_(-1721193673013960740632763534764.5228214424091055852) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.4480001516640186309814453125e-3), SC_(-15499334906533236567606620530.200191728031049025026) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.5502865533344447612762451171875e-3), SC_(-3535003298421510578639833490.1298202600643335995787) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.19227224402129650115966796875e-2), SC_(-439752257691660682841541.75551794749699979175321037) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.37370622158050537109375e-2), SC_(-3705011706337639112308.1152209359387228834835931875) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.47696642577648162841796875e-2), SC_(-641530904911065947149.99803989774066863308464555235) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.1275280676782131195068359375e-1), SC_(-546132673072666047.00762658792974245303347213408634) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.20440109074115753173828125e-1), SC_(-18396701945112916.384895654825593702168225876869444) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.3429813683032989501953125e-1), SC_(-445744577892577.55674541900235843479039451134156993) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.96701286733150482177734375e-1), SC_(-259210670573.87288769946854267773996879304687746878) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.159812271595001220703125e0), SC_(-7010082148.1406965960052632072139869221477975711535) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.297095477581024169921875e0), SC_(-81491453.188992740300521508908029235919983115000153) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.77344071865081787109375e0), SC_(-85445.976575401714336017146103914454068580259978837) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.1992881298065185546875e1), SC_(-105.85384695262030240377338945392033413256061144355) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.3915013790130615234375e1), SC_(-1.1183215030957860901241466804409166833411563137547) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.79858455657958984375e1), SC_(-0.15924647968524992013750712539382612404853915739277) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.1571910858154296875e2), SC_(-0.13646497651694413062087338033835273332177981957281) }}, {{ SC_(-0.618752574920654296875e1), SC_(0.31483119964599609375e2), SC_(0.027827355903320065863025843071254167156921275283086) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.553809732082299888134002685546875e-4), SC_(8.4001523341827038432231402722998721443142330918029e+88) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.69304020144045352935791015625e-4), SC_(1.8796222553522528946620379625259071351108320901138e+87) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.23264062474481761455535888671875e-3), SC_(2.3081325916347882778073752606750486492668025854818e+78) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.4480001516640186309814453125e-3), SC_(3.478515150118406691595592053627769982231673500328e+73) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.5502865533344447612762451171875e-3), SC_(1.0670813727575964549272980712377341426694937581102e+72) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.19227224402129650115966796875e-2), SC_(6.6461334772063947653408668199451299578982343030567e+62) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.37370622158050537109375e-2), SC_(8.5619384530651836961194424228825518552684541970703e+57) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.47696642577648162841796875e-2), SC_(1.3719213377554659464306815751401633848492260535841e+56) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.1275280676782131195068359375e-1), SC_(7955158190212178420335468368124232663880717342110.2) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.20440109074115753173828125e-1), SC_(2687830185054672115670778035161362230550317234.9171) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.3429813683032989501953125e-1), SC_(417660847046267243923149265721102299918747.3327615) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.96701286733150482177734375e-1), SC_(9857412566370820437179391176824948.4480973116452753) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.159812271595001220703125e0), SC_(1982746222928083889201392122860.5529495215191051141) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.297095477581024169921875e0), SC_(54342658614656265715301011.291462576149999975040162) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.77344071865081787109375e0), SC_(4989069325897041578.9287143951601924931745358960062) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.1992881298065185546875e1), SC_(568820654109.75213716307392588957540692056153767208) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.3915013790130615234375e1), SC_(7228733.3457096840440213548757017280593929621744697) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.79858455657958984375e1), SC_(85.218410883780746589554552518759217135548634643101) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.1571910858154296875e2), SC_(0.083138583238802217337982342423668412467885504693672) }}, {{ SC_(-0.15943050384521484375e2), SC_(0.31483119964599609375e2), SC_(0.026092609809789979593703213872413724681414333167314) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.553809732082299888134002685546875e-4), SC_(6.732265130331118411406210733134040868570474523393e+180) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.69304020144045352935791015625e-4), SC_(4.7890805105156653308354285280134561894764616686371e+177) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.23264062474481761455535888671875e-3), SC_(4.8109334124012977057393970639279785207684445563722e+160) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.4480001516640186309814453125e-3), SC_(3.049052750399900587178257099373852751425565819684e+151) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.5502865533344447612762451171875e-3), SC_(3.9594237279973587787148322093805851499714508240285e+148) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.19227224402129650115966796875e-2), SC_(1.0894842839824276085850763917542395186000660442094e+131) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.37370622158050537109375e-2), SC_(5.1190963995973892592278162982935522403814915185721e+121) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.47696642577648162841796875e-2), SC_(1.9259093785260067277950959762634816738979484178694e+118) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.1275280676782131195068359375e-1), SC_(3.0209004816077561502611340316195266897611051320687e+104) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.20440109074115753173828125e-1), SC_(7.2189850508763419944174046157635499799131383398434e+97) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.3429813683032989501953125e-1), SC_(3.9203759513806755842698539491059510914538050043793e+90) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.96701286733150482177734375e-1), SC_(1.1068238961489066737178853560695046742443653655441e+76) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.159812271595001220703125e0), SC_(9.8310501753961151205121686731703916211875717169597e+68) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.297095477581024169921875e0), SC_(1.9474201739442400194932589993162245643234473214871e+60) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.77344071865081787109375e0), SC_(72637648749801605640594500299031420664728634405.057) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.1992881298065185546875e1), SC_(3865026197564005029397831991829306.6380852182772186) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.3915013790130615234375e1), SC_(1404011109550035690853366.2231718837052560358837621) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.79858455657958984375e1), SC_(201998574478312.5859314533387877544464625179036473) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.1571910858154296875e2), SC_(273866.85062463153642269420825285461481145130239201) }}, {{ SC_(-0.31320110321044921875e2), SC_(0.31483119964599609375e2), SC_(0.040177706317001652135569144163854139601049432365744) }}, #if LDBL_MAX_10_EXP > 370 {{ SC_(-0.638867645263671875e2), SC_(0.553809732082299888134002685546875e-4), SC_(2.3698927678173738831066761972137110281877681762679e+383) }}, {{ SC_(-0.638867645263671875e2), SC_(0.69304020144045352935791015625e-4), SC_(1.1347435085188848198271269654218346241788725670797e+377) }}, {{ SC_(-0.638867645263671875e2), SC_(0.23264062474481761455535888671875e-3), SC_(8.4954816338456215028286500709836088758658594626306e+342) }}, {{ SC_(-0.638867645263671875e2), SC_(0.4480001516640186309814453125e-3), SC_(2.9033181046257357700429477801583184943123438667291e+324) }}, {{ SC_(-0.638867645263671875e2), SC_(0.5502865533344447612762451171875e-3), SC_(4.6538211817343001183895076979754694438753107525127e+318) }}, #endif {{ SC_(-0.638867645263671875e2), SC_(0.19227224402129650115966796875e-2), SC_(2.5884127570342517807802184680833064189350946360272e+283) }}, {{ SC_(-0.638867645263671875e2), SC_(0.37370622158050537109375e-2), SC_(4.8508986987836801234656433955696736929307399214621e+264) }}, {{ SC_(-0.638867645263671875e2), SC_(0.47696642577648162841796875e-2), SC_(6.4652313804985336441271270491093075957693244755895e+257) }}, {{ SC_(-0.638867645263671875e2), SC_(0.1275280676782131195068359375e-1), SC_(1.2481913994843204247151724194175209513818899114211e+230) }}, {{ SC_(-0.638867645263671875e2), SC_(0.20440109074115753173828125e-1), SC_(6.3452402812155401507978956824225465373086743151221e+216) }}, {{ SC_(-0.638867645263671875e2), SC_(0.3429813683032989501953125e-1), SC_(1.6471284344367667896225149421358528479494425365156e+202) }}, {{ SC_(-0.638867645263671875e2), SC_(0.96701286733150482177734375e-1), SC_(1.0167245949532858220681726036512131689235250729876e+173) }}, {{ SC_(-0.638867645263671875e2), SC_(0.159812271595001220703125e0), SC_(7.0855606144842314101921479749180352596328021493921e+158) }}, {{ SC_(-0.638867645263671875e2), SC_(0.297095477581024169921875e0), SC_(2.3844448492985196529635784175504063632397857898622e+141) }}, {{ SC_(-0.638867645263671875e2), SC_(0.77344071865081787109375e0), SC_(2.6048251069659582851724058248351336224666813212987e+114) }}, {{ SC_(-0.638867645263671875e2), SC_(0.1992881298065185546875e1), SC_(5.6160513564930999055692078692461392613591823835801e+87) }}, {{ SC_(-0.638867645263671875e2), SC_(0.3915013790130615234375e1), SC_(5.498812871670615045881011453415585469720132723112e+68) }}, {{ SC_(-0.638867645263671875e2), SC_(0.79858455657958984375e1), SC_(5411799740662393319191711873139592736080843868560.4) }}, {{ SC_(-0.638867645263671875e2), SC_(0.1571910858154296875e2), SC_(910129039949789177025388333870.53660912834462595725) }}, {{ SC_(-0.638867645263671875e2), SC_(0.31483119964599609375e2), SC_(477742493665.49170927134873191131936373256371654668) }}, }};
#pragma once #include <Glad/glad/glad.h> #include <vector> namespace cage { template <class VertexType> class VertexBuffer { public: VertexBuffer(bool storeLocalCopy = false) : m_id(0), m_local(storeLocalCopy), m_size(0) { glCreateBuffers(1, &m_id); } inline void Bind() { glBindBuffer(GL_ARRAY_BUFFER, m_id); } inline void Fill(const std::vector<VertexType>& data) { Bind(); m_size = data.size(); if (m_local) { m_localData = data; } glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(VertexType), &data[0], GL_DYNAMIC_DRAW); } inline void Rebuffer() { glBufferSubData(GL_ARRAY_BUFFER, 0, m_localData.size() * sizeof(VertexType), &m_localData[0]); } inline void UpdateRange(int startIndex, std::vector<VertexType>& data) { int length = data.size(); if (length == 0) return; glBufferSubData(GL_ARRAY_BUFFER, startIndex * sizeof(VertexType), length * sizeof(VertexType), &data[0]); } ~VertexBuffer() { glDeleteBuffers(1, &m_id); UnbindAll(); } VertexType& operator[](int i) { return m_localData[i]; } inline size_t GetSize() const { return m_size; } inline unsigned int GetID() const { return m_id; } static void UnbindAll() { glBindBuffer(GL_ARRAY_BUFFER, 0); } private: // OpenGL id or "name" for this vbo unsigned int m_id; // Local copy of the data if we want to hold it software side std::vector<VertexType> m_localData; // Should we store the vertex data software side? bool m_local; size_t m_size; }; }
// automaticly generated by update_resources.py #include <html_images_uptime_svg.h> REGISTRY_RESOURCE_FILE(RES_html_images_uptime_svg) const std::string &RES_html_images_uptime_svg::filename() { static const std::string s = "html/images/uptime.svg"; return s; } const int RES_html_images_uptime_svg::bufferSize() { return 3581; } const char *RES_html_images_uptime_svg::buffer() { static const std::string sRet = // size: 3581 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" "<!-- Created with Inkscape (http://www.inkscape.org/) -->\n" "\n" "<svg\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" " xmlns:cc=\"http://creativecommons.org/ns#\"\n" " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" " xmlns:svg=\"http://www.w3.org/2000/svg\"\n" " xmlns=\"http://www.w3.org/2000/svg\"\n" " xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n" " xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n" " width=\"100\"\n" " height=\"100\"\n" " viewBox=\"0 0 26.458333 26.458334\"\n" " version=\"1.1\"\n" " id=\"svg8\"\n" " inkscape:version=\"0.92.3 (2405546, 2018-03-11)\"\n" " sodipodi:docname=\"uptime.svg\">\n" " <defs\n" " id=\"defs2\" />\n" " <sodipodi:namedview\n" " id=\"base\"\n" " pagecolor=\"#ffffff\"\n" " bordercolor=\"#666666\"\n" " borderopacity=\"1.0\"\n" " inkscape:pageopacity=\"0.0\"\n" " inkscape:pageshadow=\"2\"\n" " inkscape:zoom=\"2.8\"\n" " inkscape:cx=\"-43.7796\"\n" " inkscape:cy=\"48.59797\"\n" " inkscape:document-units=\"px\"\n" " inkscape:current-layer=\"layer1\"\n" " showgrid=\"false\"\n" " units=\"px\"\n" " inkscape:window-width=\"1853\"\n" " inkscape:window-height=\"1025\"\n" " inkscape:window-x=\"67\"\n" " inkscape:window-y=\"27\"\n" " inkscape:window-maximized=\"1\"\n" " inkscape:snap-global=\"false\" />\n" " <metadata\n" " id=\"metadata5\">\n" " <rdf:RDF>\n" " <cc:Work\n" " rdf:about=\"\">\n" " <dc:format>image/svg+xml</dc:format>\n" " <dc:type\n" " rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n" " <dc:title></dc:title>\n" " </cc:Work>\n" " </rdf:RDF>\n" " </metadata>\n" " <g\n" " inkscape:label=\"Layer 1\"\n" " inkscape:groupmode=\"layer\"\n" " id=\"layer1\"\n" " transform=\"translate(0,-270.54166)\">\n" " <g\n" " transform=\"translate(0,-198.96085)\"\n" " id=\"layer1-3\"\n" " inkscape:label=\"Layer 1\" />\n" " <g\n" " transform=\"translate(0,-198.96085)\"\n" " id=\"layer1-1\"\n" " inkscape:label=\"Layer 1\" />\n" " <path\n" " style=\"opacity:1;fill:#fffffe;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal\"\n" " d=\"m 17.144937,292.73005 c -1.326658,0.71939 -2.76941,0.99263 -4.370745,0.99262 -5.2905921,-2.6e-4 -9.5793165,-4.44191 -9.5792595,-9.92084 -5.7e-5,-5.47893 4.2886674,-9.92058 9.5792595,-9.92084 4.168875,-3e-5 7.749207,2.65745 9.065981,6.50744 l 3.632295,-0.97183 c -1.768908,-5.17395 -6.629687,-8.7428 -12.390284,-8.74265 -7.2512125,1e-4 -13.12942834,5.89336 -13.12943054,13.16302 2.2e-6,7.26966 5.87821804,13.16292 13.12943054,13.16302 1.42805,4e-5 2.802856,-0.2285 4.090004,-0.6511 z\"\n" " id=\"path845\"\n" " inkscape:connector-curvature=\"0\"\n" " sodipodi:nodetypes=\"cccccccsccc\" />\n" " <path\n" " style=\"fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n" " d=\"m 8.9881099,288.02503 2.7427021,2.12443 4.167811,-4.77223 -0.02362,-7.40284 -3.998105,-0.0115 0.07661,6.02052 z\"\n" " id=\"path850\"\n" " inkscape:connector-curvature=\"0\"\n" " sodipodi:nodetypes=\"ccccccc\" />\n" " <path\n" " style=\"fill:#fffffe;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n" " d=\"m 20.363468,295.93693 5.480653,5e-5 -1.285673,-3.14164 -0.273485,-6.33139 1.700893,0.23619 -2.976563,-5.00818 -2.929315,5.43341 1.74814,-0.66141 -0.05786,6.16602 z\"\n" " id=\"path852\"\n" " inkscape:connector-curvature=\"0\"\n" " sodipodi:nodetypes=\"cccccccccc\" />\n" " </g>\n" "</svg>\n" ; return sRet.c_str(); } //::buffer()
#include "blinkpch.h" #include "Log.h" #include "spdlog/sinks/stdout_color_sinks.h" namespace Blink { std::shared_ptr<spdlog::logger> Log::s_CoreLogger; std::shared_ptr<spdlog::logger> Log::s_ClentLogger; void Log::Init() { spdlog::set_pattern("%^[%T] %n: %v%$"); s_CoreLogger = spdlog::stdout_color_mt("BLINK"); s_CoreLogger->set_level(spdlog::level::trace); s_ClentLogger = spdlog::stdout_color_mt("APP"); s_CoreLogger->set_level(spdlog::level::trace); } }
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 <gtest/gtest.h> #include <acsdkCodecUtils/Hex.h> namespace alexaClientSDK { namespace acsdkCodecUtils { namespace test { using namespace ::testing; const std::string HEX_STR = "0123456789"; const Bytes HEX_STR_BINARY{0x01, 0x23, 0x45, 0x67, 0x89}; const Bytes HEX_STR_BINARY2{0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89}; // Test string. static const std::string TEST_STR{"A quick brown fox jumps over the lazy dog."}; // Test string encoded in hex (uppercase). static const std::string TEST_STR_HEX_U{ "4120717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E"}; // Test string encoded in hex (lowercase). static const std::string TEST_STR_HEX_L{ "4120717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e"}; // Verify hex decoding works and resets the output buffer. TEST(HexCodecTest, test_hexDecode) { Bytes decoded; ASSERT_TRUE(decodeHex(HEX_STR, decoded)); ASSERT_EQ(HEX_STR_BINARY, decoded); } // Verify hex decoding works up for lowercase letter values TEST(HexCodecTest, test_hexDecodeAFLowerCase) { Bytes decoded; ASSERT_TRUE(decodeHex("ab", decoded)); ASSERT_TRUE(decodeHex("cd", decoded)); ASSERT_TRUE(decodeHex("ef", decoded)); ASSERT_EQ((Bytes{0xAB, 0xCD, 0xEF}), decoded); } // Verify hex decoding works up for uppercase letter values TEST(HexCodecTest, test_hexDecodeAFUpperCase) { Bytes decoded; ASSERT_TRUE(decodeHex("AB", decoded)); ASSERT_TRUE(decodeHex("CD", decoded)); ASSERT_TRUE(decodeHex("EF", decoded)); ASSERT_EQ((Bytes{0xAB, 0xCD, 0xEF}), decoded); } // Verify hex decoding works up for mixed case letter values TEST(HexCodecTest, test_hexDecodeAFMixedCase) { Bytes decoded; ASSERT_TRUE(decodeHex("Ab", decoded)); ASSERT_TRUE(decodeHex("cD", decoded)); ASSERT_TRUE(decodeHex("eF", decoded)); ASSERT_EQ((Bytes{0xAB, 0xCD, 0xEF}), decoded); } // Verify hex decoding works with larger input TEST(HexCodecTest, test_hexDecodeTestStringUpperCase) { Bytes decoded; ASSERT_TRUE(decodeHex(TEST_STR_HEX_U, decoded)); std::string decodedStr{decoded.data(), decoded.data() + decoded.size()}; ASSERT_EQ(TEST_STR, decodedStr); } // Verify hex decoding works with larger input TEST(HexCodecTest, test_hexDecodeTestStringLowerCase) { Bytes decoded; ASSERT_TRUE(decodeHex(TEST_STR_HEX_L, decoded)); std::string decodedStr{decoded.data(), decoded.data() + decoded.size()}; ASSERT_EQ(TEST_STR, decodedStr); } // Verify hex decoding can append data to buffer TEST(HexCodecTest, test_hexDecodeAppend) { Bytes decoded; ASSERT_TRUE(decodeHex(HEX_STR, decoded)); ASSERT_TRUE(decodeHex(HEX_STR, decoded)); ASSERT_EQ(HEX_STR_BINARY2, decoded); } // Verify hex decoding fails on bad size TEST(HexCodecTest, test_hexDecodeBadSize) { Bytes decoded; ASSERT_FALSE(decodeHex("012", decoded)); } // Verify hex decoding fails on bad size TEST(HexCodecTest, test_hexDecodeBadChar) { Bytes decoded; ASSERT_FALSE(decodeHex("AZ", decoded)); } // Verify hex encoding works and resets the buffer TEST(HexCodecTest, test_hexEncode) { std::string encoded{}; ASSERT_TRUE(encodeHex(HEX_STR_BINARY, encoded)); ASSERT_EQ(HEX_STR, encoded); } // Verify hex encoding works and can append to buffer TEST(HexCodecTest, test_hexEncodeAppend) { std::string encoded; ASSERT_TRUE(encodeHex(HEX_STR_BINARY, encoded)); ASSERT_TRUE(encodeHex(HEX_STR_BINARY, encoded)); ASSERT_EQ(HEX_STR + HEX_STR, encoded); } // Verify hex encode works for A-F TEST(HexCodecTest, test_hexEncodeAF) { std::string encoded; ASSERT_TRUE(encodeHex(Bytes{0xab}, encoded)); ASSERT_TRUE(encodeHex(Bytes{0xcd}, encoded)); ASSERT_TRUE(encodeHex(Bytes{0xef}, encoded)); ASSERT_EQ("abcdef", encoded); } // Verify hex encode works with test string TEST(HexCodecTest, test_hexEncodeTestString) { std::string encoded; ASSERT_TRUE(encodeHex(Bytes{TEST_STR.data(), TEST_STR.data() + TEST_STR.size()}, encoded)); ASSERT_EQ(TEST_STR_HEX_L, encoded); } // Verify hex decoding works up for whitespace values TEST(HexCodecTest, test_hexDecodeWithWhitespace) { Bytes decoded; ASSERT_TRUE(decodeHex("\rA B\tC\nD\n", decoded)); ASSERT_EQ((Bytes{0xAB, 0xCD}), decoded); } } // namespace test } // namespace acsdkCodecUtils } // namespace alexaClientSDK
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ====================================================================== // #include <portinfo> #include "VertexFilterVecNorm.hh" // Implementation of class methods #include "pylith/topology/Field.hh" // USES Field #include "pylith/topology/Stratum.hh" // USES Stratum #include "pylith/topology/VisitorMesh.hh" \ // USES VecVisitorMesh // ---------------------------------------------------------------------- // Constructor pylith::meshio::VertexFilterVecNorm::VertexFilterVecNorm(void) : _fieldVecNorm(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor pylith::meshio::VertexFilterVecNorm::~VertexFilterVecNorm(void) { // destructor deallocate(); } // destructor // ---------------------------------------------------------------------- // Deallocate PETSc and local data structures. void pylith::meshio::VertexFilterVecNorm::deallocate(void) { // deallocate PYLITH_METHOD_BEGIN; VertexFilter::deallocate(); delete _fieldVecNorm; _fieldVecNorm = 0; PYLITH_METHOD_END; } // deallocate // ---------------------------------------------------------------------- // Copy constructor. pylith::meshio::VertexFilterVecNorm::VertexFilterVecNorm(const VertexFilterVecNorm& f) : VertexFilter(f), _fieldVecNorm(0) { // copy constructor } // copy constructor // ---------------------------------------------------------------------- // Create copy of filter. pylith::meshio::VertexFilter* pylith::meshio::VertexFilterVecNorm::clone(void) const { // clone return new VertexFilterVecNorm(*this); } // clone // ---------------------------------------------------------------------- // Filter field. pylith::topology::Field& pylith::meshio::VertexFilterVecNorm::filter(const topology::Field& fieldIn) { // filter PYLITH_METHOD_BEGIN; PetscDM dmMesh = fieldIn.mesh().dmMesh();assert(dmMesh); topology::Stratum verticesStratum(dmMesh, topology::Stratum::DEPTH, 0); const PetscInt vStart = verticesStratum.begin(); const PetscInt vEnd = verticesStratum.end(); topology::VecVisitorMesh fieldInVisitor(fieldIn); // Only processors with cells for output get the correct fiber dimension. PetscInt fiberDimIn = (verticesStratum.size() > 0) ? fieldInVisitor.sectionDof(vStart) : 0; const int fiberDimNorm = 1; // Allocate field if necessary if (!_fieldVecNorm) { _fieldVecNorm = new topology::Field(fieldIn.mesh()); _fieldVecNorm->label("vector norm"); _fieldVecNorm->newSection(fieldIn, fiberDimNorm); _fieldVecNorm->allocate(); _fieldVecNorm->label(fieldIn.label()); //_fieldVecNorm->scale(fieldIn.scale()); #if 0 // :TODO: FIX THIS. switch (fieldIn.vectorFieldType()) { // switch case topology::FieldBase::SCALAR: case topology::FieldBase::VECTOR: _fieldVecNorm->vectorFieldType(topology::FieldBase::SCALAR); break; case topology::FieldBase::MULTI_SCALAR: case topology::FieldBase::MULTI_VECTOR: case topology::FieldBase::MULTI_TENSOR: case topology::FieldBase::MULTI_OTHER: case topology::FieldBase::TENSOR: case topology::FieldBase::OTHER: default: std::ostringstream msg; msg << "Bad vector field type '" << fieldIn.vectorFieldType() << " for VertexFilterVecNorm'." << std::endl; throw std::logic_error(msg.str()); } // switch #endif } // if const PetscScalar* fieldInArray = fieldInVisitor.localArray(); topology::VecVisitorMesh fieldNormVisitor(*_fieldVecNorm); PetscScalar* fieldNormArray = fieldNormVisitor.localArray(); // Loop over vertices for (PetscInt v = vStart; v < vEnd; ++v) { const PetscInt ioff = fieldInVisitor.sectionOffset(v); assert(fiberDimIn == fieldInVisitor.sectionDof(v)); const PetscInt noff = fieldNormVisitor.sectionOffset(v); PylithScalar norm = 0.0; for (PetscInt d = 0; d < fiberDimIn; ++d) { norm += fieldInArray[ioff+d]*fieldInArray[ioff+d]; } // for fieldNormArray[noff] = sqrt(norm); } // for PetscLogFlops((vEnd-vStart) * (1 + 2*fiberDimIn)); PYLITH_METHOD_RETURN(*_fieldVecNorm); } // filter // End of file
#ifndef _CISCO_IOS_XE_NATIVE_193_ #define _CISCO_IOS_XE_NATIVE_193_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> #include "Cisco_IOS_XE_native_0.hpp" #include "Cisco_IOS_XE_native_133.hpp" #include "Cisco_IOS_XE_native_175.hpp" #include "Cisco_IOS_XE_native_192.hpp" namespace cisco_ios_xe { namespace Cisco_IOS_XE_native { class Native::Router::Lisp::Ipv4::MapResolver::MapRequest : public ydk::Entity { public: MapRequest(); ~MapRequest(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Validate; //type: Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate> validate; }; // Native::Router::Lisp::Ipv4::MapResolver::MapRequest class Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate : public ydk::Entity { public: Validate(); ~Validate(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Source; //type: Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate::Source std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate::Source> source; }; // Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate class Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate::Source : public ydk::Entity { public: Source(); ~Source(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf list; //type: empty ydk::YLeaf registered; //type: empty ydk::YLeaf ipv4; //type: string ydk::YLeaf ipv6; //type: string }; // Native::Router::Lisp::Ipv4::MapResolver::MapRequest::Validate::Source class Native::Router::Lisp::Ipv4::MapServer : public ydk::Entity { public: MapServer(); ~MapServer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapRegister; //type: Native::Router::Lisp::Ipv4::MapServer::MapRegister std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::MapServer::MapRegister> map_register; }; // Native::Router::Lisp::Ipv4::MapServer class Native::Router::Lisp::Ipv4::MapServer::MapRegister : public ydk::Entity { public: MapRegister(); ~MapRegister(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Validate; //type: Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate> validate; }; // Native::Router::Lisp::Ipv4::MapServer::MapRegister class Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate : public ydk::Entity { public: Validate(); ~Validate(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Source; //type: Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate::Source std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate::Source> source; }; // Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate class Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate::Source : public ydk::Entity { public: Source(); ~Source(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf allowed_locator; //type: empty }; // Native::Router::Lisp::Ipv4::MapServer::MapRegister::Validate::Source class Native::Router::Lisp::Ipv4::PathMtuDiscovery : public ydk::Entity { public: PathMtuDiscovery(); ~PathMtuDiscovery(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf max; //type: uint16 ydk::YLeaf min; //type: uint16 }; // Native::Router::Lisp::Ipv4::PathMtuDiscovery class Native::Router::Lisp::Ipv4::RouteExport : public ydk::Entity { public: RouteExport(); ~RouteExport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf site_registrations; //type: empty ydk::YLeaf away_eids; //type: empty }; // Native::Router::Lisp::Ipv4::RouteExport class Native::Router::Lisp::Ipv4::RouteImport : public ydk::Entity { public: RouteImport(); ~RouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Database; //type: Native::Router::Lisp::Ipv4::RouteImport::Database class MapCache; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database> database; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache> map_cache; }; // Native::Router::Lisp::Ipv4::RouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database : public ydk::Entity { public: Database(); ~Database(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Bgp; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp class Connected; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Connected class Eigrp; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp class Isis; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Isis class MaximumPrefix; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::MaximumPrefix class Ospf; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf class Ospfv3; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3 class Rip; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Rip class Static; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Static ydk::YList bgp; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Connected> connected; ydk::YList eigrp; ydk::YList isis; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::MaximumPrefix> maximum_prefix; ydk::YList ospf; ydk::YList ospfv3; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Rip> rip; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Static> static_; }; // Native::Router::Lisp::Ipv4::RouteImport::Database class Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp : public ydk::Entity { public: Bgp(); ~Bgp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: one of uint32, string class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp class Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Bgp::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Connected : public ydk::Entity { public: Connected(); ~Connected(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Connected::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Connected::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Connected class Native::Router::Lisp::Ipv4::RouteImport::Database::Connected::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Connected::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp : public ydk::Entity { public: Eigrp(); ~Eigrp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp class Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Eigrp::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Isis : public ydk::Entity { public: Isis(); ~Isis(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Isis::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Isis::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Isis class Native::Router::Lisp::Ipv4::RouteImport::Database::Isis::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Isis::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::MaximumPrefix : public ydk::Entity { public: MaximumPrefix(); ~MaximumPrefix(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf number; //type: int32 ydk::YLeaf warning_only; //type: empty ydk::YLeaf threshold; //type: uint8 ydk::YLeaf threshold1; //type: uint8 ydk::YLeaf warning_only1; //type: empty }; // Native::Router::Lisp::Ipv4::RouteImport::Database::MaximumPrefix class Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf : public ydk::Entity { public: Ospf(); ~Ospf(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf class Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Ospf::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3 : public ydk::Entity { public: Ospfv3(); ~Ospfv3(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3 class Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Ospfv3::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Rip : public ydk::Entity { public: Rip(); ~Rip(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Rip::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Rip::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Rip class Native::Router::Lisp::Ipv4::RouteImport::Database::Rip::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Rip::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::Database::Static : public ydk::Entity { public: Static(); ~Static(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv4::RouteImport::Database::Static::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::Database::Static::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Static class Native::Router::Lisp::Ipv4::RouteImport::Database::Static::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::Database::Static::LispIpRouteImport class Native::Router::Lisp::Ipv4::RouteImport::MapCache : public ydk::Entity { public: MapCache(); ~MapCache(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Bgp; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp class Connected; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected class Eigrp; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp class Isis; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis class MaximumPrefix; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::MaximumPrefix class Ospf; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf class Ospfv3; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3 class Rip; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip class Static; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static ydk::YList bgp; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected> connected; // presence node ydk::YList eigrp; ydk::YList isis; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::MaximumPrefix> maximum_prefix; ydk::YList ospf; ydk::YList ospfv3; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip> rip; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static> static_; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp : public ydk::Entity { public: Bgp(); ~Bgp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: one of uint32, string class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Bgp::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected : public ydk::Entity { public: Connected(); ~Connected(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Connected::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp : public ydk::Entity { public: Eigrp(); ~Eigrp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Eigrp::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis : public ydk::Entity { public: Isis(); ~Isis(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Isis::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::MaximumPrefix : public ydk::Entity { public: MaximumPrefix(); ~MaximumPrefix(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf number; //type: int32 ydk::YLeaf warning_only; //type: empty ydk::YLeaf threshold; //type: uint8 ydk::YLeaf threshold1; //type: uint8 ydk::YLeaf warning_only1; //type: empty }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::MaximumPrefix class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf : public ydk::Entity { public: Ospf(); ~Ospf(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospf::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3 : public ydk::Entity { public: Ospfv3(); ~Ospfv3(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3 class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Ospfv3::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip : public ydk::Entity { public: Rip(); ~Rip(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Rip::MapCacheContainer class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static : public ydk::Entity { public: Static(); ~Static(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static class Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv4::RouteImport::MapCache::Static::MapCacheContainer class Native::Router::Lisp::Ipv4::SiteRegistration : public ydk::Entity { public: SiteRegistration(); ~SiteRegistration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf limit; //type: uint32 ydk::YLeaf warning_threshold; //type: uint8 }; // Native::Router::Lisp::Ipv4::SiteRegistration class Native::Router::Lisp::Ipv4::SolicitMapRequest : public ydk::Entity { public: SolicitMapRequest(); ~SolicitMapRequest(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ignore; //type: empty ydk::YLeaf max_per_entry; //type: uint8 ydk::YLeaf suppression_time; //type: uint16 }; // Native::Router::Lisp::Ipv4::SolicitMapRequest class Native::Router::Lisp::Ipv4::SourceLocator : public ydk::Entity { public: SourceLocator(); ~SourceLocator(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf appnav_compress; //type: uint16 ydk::YLeaf appnav_uncompress; //type: uint16 ydk::YLeaf atm; //type: string ydk::YLeaf atm_acr; //type: string ydk::YLeaf bdi; //type: string ydk::YLeaf cem; //type: string ydk::YLeaf cem_acr; //type: uint8 ydk::YLeaf embedded_service_engine; //type: string ydk::YLeaf ethernet; //type: string ydk::YLeaf fastethernet; //type: string ydk::YLeaf gigabitethernet; //type: string ydk::YLeaf fivegigabitethernet; //type: string ydk::YLeaf twentyfivegige; //type: string ydk::YLeaf twogigabitethernet; //type: string ydk::YLeaf fortygigabitethernet; //type: string ydk::YLeaf hundredgige; //type: string ydk::YLeaf lisp; //type: string ydk::YLeaf loopback; //type: uint32 ydk::YLeaf multilink; //type: uint16 ydk::YLeaf nve; //type: uint16 ydk::YLeaf overlay; //type: uint16 ydk::YLeaf port_channel; //type: uint32 ydk::YLeaf pseudowire; //type: uint32 ydk::YLeaf sm; //type: string ydk::YLeaf cellular; //type: string ydk::YLeaf serial; //type: string ydk::YLeaf tengigabitethernet; //type: string ydk::YLeaf tunnel; //type: uint32 ydk::YLeaf virtual_template; //type: uint16 ydk::YLeaf vlan; //type: uint16 ydk::YLeaf virtualportgroup; //type: uint16 ydk::YLeaf vasileft; //type: uint16 ydk::YLeaf vasiright; //type: uint16 class ATMSubinterface; //type: Native::Router::Lisp::Ipv4::SourceLocator::ATMSubinterface class ATMACRsubinterface; //type: Native::Router::Lisp::Ipv4::SourceLocator::ATMACRsubinterface class LISPSubinterface; //type: Native::Router::Lisp::Ipv4::SourceLocator::LISPSubinterface class PortChannelSubinterface; //type: Native::Router::Lisp::Ipv4::SourceLocator::PortChannelSubinterface std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::SourceLocator::ATMSubinterface> atm_subinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::SourceLocator::ATMACRsubinterface> atm_acrsubinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::SourceLocator::LISPSubinterface> lisp_subinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv4::SourceLocator::PortChannelSubinterface> port_channel_subinterface; }; // Native::Router::Lisp::Ipv4::SourceLocator class Native::Router::Lisp::Ipv4::SourceLocator::ATMSubinterface : public ydk::Entity { public: ATMSubinterface(); ~ATMSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf atm; //type: string }; // Native::Router::Lisp::Ipv4::SourceLocator::ATMSubinterface class Native::Router::Lisp::Ipv4::SourceLocator::ATMACRsubinterface : public ydk::Entity { public: ATMACRsubinterface(); ~ATMACRsubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf atm_acr; //type: string }; // Native::Router::Lisp::Ipv4::SourceLocator::ATMACRsubinterface class Native::Router::Lisp::Ipv4::SourceLocator::LISPSubinterface : public ydk::Entity { public: LISPSubinterface(); ~LISPSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf lisp; //type: string }; // Native::Router::Lisp::Ipv4::SourceLocator::LISPSubinterface class Native::Router::Lisp::Ipv4::SourceLocator::PortChannelSubinterface : public ydk::Entity { public: PortChannelSubinterface(); ~PortChannelSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf port_channel; //type: string }; // Native::Router::Lisp::Ipv4::SourceLocator::PortChannelSubinterface class Native::Router::Lisp::Ipv4::UsePetr : public ydk::Entity { public: UsePetr(); ~UsePetr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf locator_address; //type: string ydk::YLeaf priority; //type: uint8 ydk::YLeaf weight; //type: uint8 }; // Native::Router::Lisp::Ipv4::UsePetr class Native::Router::Lisp::Ipv6 : public ydk::Entity { public: Ipv6(); ~Ipv6(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf alt_vrf; //type: string ydk::YLeaf map_request_source; //type: string ydk::YLeaf proxy_etr; //type: empty ydk::YLeaf sgt; //type: empty ydk::YLeafList proxy_itr; //type: list of string class DatabaseMapping; //type: Native::Router::Lisp::Ipv6::DatabaseMapping class Distance; //type: Native::Router::Lisp::Ipv6::Distance class Itr; //type: Native::Router::Lisp::Ipv6::Itr class ItrEnable; //type: Native::Router::Lisp::Ipv6::ItrEnable class Etr; //type: Native::Router::Lisp::Ipv6::Etr class EtrEnable; //type: Native::Router::Lisp::Ipv6::EtrEnable class Locator; //type: Native::Router::Lisp::Ipv6::Locator class MapCache; //type: Native::Router::Lisp::Ipv6::MapCache class MapCacheLimit; //type: Native::Router::Lisp::Ipv6::MapCacheLimit class MapCachePersistent; //type: Native::Router::Lisp::Ipv6::MapCachePersistent class MapResolver; //type: Native::Router::Lisp::Ipv6::MapResolver class MapServer; //type: Native::Router::Lisp::Ipv6::MapServer class PathMtuDiscovery; //type: Native::Router::Lisp::Ipv6::PathMtuDiscovery class RouteExport; //type: Native::Router::Lisp::Ipv6::RouteExport class RouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport class SiteRegistration; //type: Native::Router::Lisp::Ipv6::SiteRegistration class SolicitMapRequest; //type: Native::Router::Lisp::Ipv6::SolicitMapRequest class SourceLocator; //type: Native::Router::Lisp::Ipv6::SourceLocator class UsePetr; //type: Native::Router::Lisp::Ipv6::UsePetr std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::DatabaseMapping> database_mapping; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Distance> distance; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Itr> itr; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::ItrEnable> itr_enable; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Etr> etr; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::EtrEnable> etr_enable; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Locator> locator; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapCache> map_cache; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapCacheLimit> map_cache_limit; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapCachePersistent> map_cache_persistent; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapResolver> map_resolver; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapServer> map_server; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::PathMtuDiscovery> path_mtu_discovery; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteExport> route_export; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport> route_import; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SiteRegistration> site_registration; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SolicitMapRequest> solicit_map_request; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SourceLocator> source_locator; ydk::YList use_petr; }; // Native::Router::Lisp::Ipv6 class Native::Router::Lisp::Ipv6::DatabaseMapping : public ydk::Entity { public: DatabaseMapping(); ~DatabaseMapping(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Limit; //type: Native::Router::Lisp::Ipv6::DatabaseMapping::Limit std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::DatabaseMapping::Limit> limit; }; // Native::Router::Lisp::Ipv6::DatabaseMapping class Native::Router::Lisp::Ipv6::DatabaseMapping::Limit : public ydk::Entity { public: Limit(); ~Limit(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf dynamic; //type: uint32 ydk::YLeaf warning_threshold; //type: uint8 }; // Native::Router::Lisp::Ipv6::DatabaseMapping::Limit class Native::Router::Lisp::Ipv6::Distance : public ydk::Entity { public: Distance(); ~Distance(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf alt; //type: uint8 ydk::YLeaf dyn_eid; //type: uint8 ydk::YLeaf site_registrations; //type: uint8 }; // Native::Router::Lisp::Ipv6::Distance class Native::Router::Lisp::Ipv6::Itr : public ydk::Entity { public: Itr(); ~Itr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapResolver; //type: Native::Router::Lisp::Ipv6::Itr::MapResolver ydk::YList map_resolver; }; // Native::Router::Lisp::Ipv6::Itr class Native::Router::Lisp::Ipv6::Itr::MapResolver : public ydk::Entity { public: MapResolver(); ~MapResolver(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ip_addr; //type: string }; // Native::Router::Lisp::Ipv6::Itr::MapResolver class Native::Router::Lisp::Ipv6::ItrEnable : public ydk::Entity { public: ItrEnable(); ~ItrEnable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf itr; //type: empty }; // Native::Router::Lisp::Ipv6::ItrEnable class Native::Router::Lisp::Ipv6::Etr : public ydk::Entity { public: Etr(); ~Etr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapServer; //type: Native::Router::Lisp::Ipv6::Etr::MapServer ydk::YList map_server; }; // Native::Router::Lisp::Ipv6::Etr class Native::Router::Lisp::Ipv6::Etr::MapServer : public ydk::Entity { public: MapServer(); ~MapServer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ip_addr; //type: string ydk::YLeaf proxy_reply; //type: empty class Key; //type: Native::Router::Lisp::Ipv6::Etr::MapServer::Key std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Etr::MapServer::Key> key; }; // Native::Router::Lisp::Ipv6::Etr::MapServer class Native::Router::Lisp::Ipv6::Etr::MapServer::Key : public ydk::Entity { public: Key(); ~Key(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key_0; //type: string ydk::YLeaf key_6; //type: string ydk::YLeaf key_7; //type: string ydk::YLeaf pwd; //type: string }; // Native::Router::Lisp::Ipv6::Etr::MapServer::Key class Native::Router::Lisp::Ipv6::EtrEnable : public ydk::Entity { public: EtrEnable(); ~EtrEnable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf etr; //type: empty }; // Native::Router::Lisp::Ipv6::EtrEnable class Native::Router::Lisp::Ipv6::Locator : public ydk::Entity { public: Locator(); ~Locator(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Reachability; //type: Native::Router::Lisp::Ipv6::Locator::Reachability std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::Locator::Reachability> reachability; }; // Native::Router::Lisp::Ipv6::Locator class Native::Router::Lisp::Ipv6::Locator::Reachability : public ydk::Entity { public: Reachability(); ~Reachability(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf exclude_default; //type: empty }; // Native::Router::Lisp::Ipv6::Locator::Reachability class Native::Router::Lisp::Ipv6::MapCache : public ydk::Entity { public: MapCache(); ~MapCache(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf site_registration; //type: empty }; // Native::Router::Lisp::Ipv6::MapCache class Native::Router::Lisp::Ipv6::MapCacheLimit : public ydk::Entity { public: MapCacheLimit(); ~MapCacheLimit(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf max_map_cache_entries; //type: uint32 ydk::YLeaf reserve_list; //type: string ydk::YLeaf warning_threshold; //type: uint8 }; // Native::Router::Lisp::Ipv6::MapCacheLimit class Native::Router::Lisp::Ipv6::MapCachePersistent : public ydk::Entity { public: MapCachePersistent(); ~MapCachePersistent(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf interval; //type: uint16 }; // Native::Router::Lisp::Ipv6::MapCachePersistent class Native::Router::Lisp::Ipv6::MapResolver : public ydk::Entity { public: MapResolver(); ~MapResolver(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapRequest; //type: Native::Router::Lisp::Ipv6::MapResolver::MapRequest std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapResolver::MapRequest> map_request; }; // Native::Router::Lisp::Ipv6::MapResolver class Native::Router::Lisp::Ipv6::MapResolver::MapRequest : public ydk::Entity { public: MapRequest(); ~MapRequest(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Validate; //type: Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate> validate; }; // Native::Router::Lisp::Ipv6::MapResolver::MapRequest class Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate : public ydk::Entity { public: Validate(); ~Validate(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Source; //type: Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate::Source std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate::Source> source; }; // Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate class Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate::Source : public ydk::Entity { public: Source(); ~Source(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf list; //type: empty ydk::YLeaf registered; //type: empty ydk::YLeaf ipv4; //type: string ydk::YLeaf ipv6; //type: string }; // Native::Router::Lisp::Ipv6::MapResolver::MapRequest::Validate::Source class Native::Router::Lisp::Ipv6::MapServer : public ydk::Entity { public: MapServer(); ~MapServer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapRegister; //type: Native::Router::Lisp::Ipv6::MapServer::MapRegister std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapServer::MapRegister> map_register; }; // Native::Router::Lisp::Ipv6::MapServer class Native::Router::Lisp::Ipv6::MapServer::MapRegister : public ydk::Entity { public: MapRegister(); ~MapRegister(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Validate; //type: Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate> validate; }; // Native::Router::Lisp::Ipv6::MapServer::MapRegister class Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate : public ydk::Entity { public: Validate(); ~Validate(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Source; //type: Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate::Source std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate::Source> source; }; // Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate class Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate::Source : public ydk::Entity { public: Source(); ~Source(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf allowed_locator; //type: empty }; // Native::Router::Lisp::Ipv6::MapServer::MapRegister::Validate::Source class Native::Router::Lisp::Ipv6::PathMtuDiscovery : public ydk::Entity { public: PathMtuDiscovery(); ~PathMtuDiscovery(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf max; //type: uint16 ydk::YLeaf min; //type: uint16 }; // Native::Router::Lisp::Ipv6::PathMtuDiscovery class Native::Router::Lisp::Ipv6::RouteExport : public ydk::Entity { public: RouteExport(); ~RouteExport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf site_registrations; //type: empty ydk::YLeaf away_eids; //type: empty }; // Native::Router::Lisp::Ipv6::RouteExport class Native::Router::Lisp::Ipv6::RouteImport : public ydk::Entity { public: RouteImport(); ~RouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Database; //type: Native::Router::Lisp::Ipv6::RouteImport::Database class MapCache; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database> database; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache> map_cache; }; // Native::Router::Lisp::Ipv6::RouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database : public ydk::Entity { public: Database(); ~Database(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Bgp; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp class Connected; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Connected class Eigrp; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp class Isis; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Isis class MaximumPrefix; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::MaximumPrefix class Ospf; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf class Ospfv3; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3 class Rip; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Rip class Static; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Static ydk::YList bgp; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Connected> connected; ydk::YList eigrp; ydk::YList isis; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::MaximumPrefix> maximum_prefix; ydk::YList ospf; ydk::YList ospfv3; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Rip> rip; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Static> static_; }; // Native::Router::Lisp::Ipv6::RouteImport::Database class Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp : public ydk::Entity { public: Bgp(); ~Bgp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: one of uint32, string class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp class Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Bgp::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Connected : public ydk::Entity { public: Connected(); ~Connected(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Connected::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Connected::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Connected class Native::Router::Lisp::Ipv6::RouteImport::Database::Connected::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Connected::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp : public ydk::Entity { public: Eigrp(); ~Eigrp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp class Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Eigrp::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Isis : public ydk::Entity { public: Isis(); ~Isis(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Isis::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Isis::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Isis class Native::Router::Lisp::Ipv6::RouteImport::Database::Isis::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Isis::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::MaximumPrefix : public ydk::Entity { public: MaximumPrefix(); ~MaximumPrefix(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf number; //type: int32 ydk::YLeaf warning_only; //type: empty ydk::YLeaf threshold; //type: uint8 ydk::YLeaf threshold1; //type: uint8 ydk::YLeaf warning_only1; //type: empty }; // Native::Router::Lisp::Ipv6::RouteImport::Database::MaximumPrefix class Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf : public ydk::Entity { public: Ospf(); ~Ospf(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf class Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Ospf::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3 : public ydk::Entity { public: Ospfv3(); ~Ospfv3(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3 class Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Ospfv3::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Rip : public ydk::Entity { public: Rip(); ~Rip(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Rip::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Rip::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Rip class Native::Router::Lisp::Ipv6::RouteImport::Database::Rip::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Rip::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::Database::Static : public ydk::Entity { public: Static(); ~Static(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LispIpRouteImport; //type: Native::Router::Lisp::Ipv6::RouteImport::Database::Static::LispIpRouteImport std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::Database::Static::LispIpRouteImport> lisp_ip_route_import; }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Static class Native::Router::Lisp::Ipv6::RouteImport::Database::Static::LispIpRouteImport : public ydk::Entity { public: LispIpRouteImport(); ~LispIpRouteImport(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::Database::Static::LispIpRouteImport class Native::Router::Lisp::Ipv6::RouteImport::MapCache : public ydk::Entity { public: MapCache(); ~MapCache(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Bgp; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp class Connected; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected class Eigrp; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp class Isis; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis class MaximumPrefix; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::MaximumPrefix class Ospf; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf class Ospfv3; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3 class Rip; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip class Static; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static ydk::YList bgp; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected> connected; // presence node ydk::YList eigrp; ydk::YList isis; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::MaximumPrefix> maximum_prefix; ydk::YList ospf; ydk::YList ospfv3; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip> rip; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static> static_; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp : public ydk::Entity { public: Bgp(); ~Bgp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: one of uint32, string class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Bgp::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected : public ydk::Entity { public: Connected(); ~Connected(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Connected::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp : public ydk::Entity { public: Eigrp(); ~Eigrp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Eigrp::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis : public ydk::Entity { public: Isis(); ~Isis(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Isis::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::MaximumPrefix : public ydk::Entity { public: MaximumPrefix(); ~MaximumPrefix(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf number; //type: int32 ydk::YLeaf warning_only; //type: empty ydk::YLeaf threshold; //type: uint8 ydk::YLeaf threshold1; //type: uint8 ydk::YLeaf warning_only1; //type: empty }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::MaximumPrefix class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf : public ydk::Entity { public: Ospf(); ~Ospf(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospf::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3 : public ydk::Entity { public: Ospfv3(); ~Ospfv3(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: uint16 class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3 class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Ospfv3::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip : public ydk::Entity { public: Rip(); ~Rip(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Rip::MapCacheContainer class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static : public ydk::Entity { public: Static(); ~Static(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MapCacheContainer; //type: Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static::MapCacheContainer std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static::MapCacheContainer> map_cache_container; // presence node }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static class Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static::MapCacheContainer : public ydk::Entity { public: MapCacheContainer(); ~MapCacheContainer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf route_map; //type: string }; // Native::Router::Lisp::Ipv6::RouteImport::MapCache::Static::MapCacheContainer class Native::Router::Lisp::Ipv6::SiteRegistration : public ydk::Entity { public: SiteRegistration(); ~SiteRegistration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf limit; //type: uint32 ydk::YLeaf warning_threshold; //type: uint8 }; // Native::Router::Lisp::Ipv6::SiteRegistration class Native::Router::Lisp::Ipv6::SolicitMapRequest : public ydk::Entity { public: SolicitMapRequest(); ~SolicitMapRequest(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ignore; //type: empty ydk::YLeaf max_per_entry; //type: uint8 ydk::YLeaf suppression_time; //type: uint16 }; // Native::Router::Lisp::Ipv6::SolicitMapRequest class Native::Router::Lisp::Ipv6::SourceLocator : public ydk::Entity { public: SourceLocator(); ~SourceLocator(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf appnav_compress; //type: uint16 ydk::YLeaf appnav_uncompress; //type: uint16 ydk::YLeaf atm; //type: string ydk::YLeaf atm_acr; //type: string ydk::YLeaf bdi; //type: string ydk::YLeaf cem; //type: string ydk::YLeaf cem_acr; //type: uint8 ydk::YLeaf embedded_service_engine; //type: string ydk::YLeaf ethernet; //type: string ydk::YLeaf fastethernet; //type: string ydk::YLeaf gigabitethernet; //type: string ydk::YLeaf fivegigabitethernet; //type: string ydk::YLeaf twentyfivegige; //type: string ydk::YLeaf twogigabitethernet; //type: string ydk::YLeaf fortygigabitethernet; //type: string ydk::YLeaf hundredgige; //type: string ydk::YLeaf lisp; //type: string ydk::YLeaf loopback; //type: uint32 ydk::YLeaf multilink; //type: uint16 ydk::YLeaf nve; //type: uint16 ydk::YLeaf overlay; //type: uint16 ydk::YLeaf port_channel; //type: uint32 ydk::YLeaf pseudowire; //type: uint32 ydk::YLeaf sm; //type: string ydk::YLeaf cellular; //type: string ydk::YLeaf serial; //type: string ydk::YLeaf tengigabitethernet; //type: string ydk::YLeaf tunnel; //type: uint32 ydk::YLeaf virtual_template; //type: uint16 ydk::YLeaf vlan; //type: uint16 ydk::YLeaf virtualportgroup; //type: uint16 ydk::YLeaf vasileft; //type: uint16 ydk::YLeaf vasiright; //type: uint16 class ATMSubinterface; //type: Native::Router::Lisp::Ipv6::SourceLocator::ATMSubinterface class ATMACRsubinterface; //type: Native::Router::Lisp::Ipv6::SourceLocator::ATMACRsubinterface class LISPSubinterface; //type: Native::Router::Lisp::Ipv6::SourceLocator::LISPSubinterface class PortChannelSubinterface; //type: Native::Router::Lisp::Ipv6::SourceLocator::PortChannelSubinterface std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SourceLocator::ATMSubinterface> atm_subinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SourceLocator::ATMACRsubinterface> atm_acrsubinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SourceLocator::LISPSubinterface> lisp_subinterface; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::Ipv6::SourceLocator::PortChannelSubinterface> port_channel_subinterface; }; // Native::Router::Lisp::Ipv6::SourceLocator class Native::Router::Lisp::Ipv6::SourceLocator::ATMSubinterface : public ydk::Entity { public: ATMSubinterface(); ~ATMSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf atm; //type: string }; // Native::Router::Lisp::Ipv6::SourceLocator::ATMSubinterface class Native::Router::Lisp::Ipv6::SourceLocator::ATMACRsubinterface : public ydk::Entity { public: ATMACRsubinterface(); ~ATMACRsubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf atm_acr; //type: string }; // Native::Router::Lisp::Ipv6::SourceLocator::ATMACRsubinterface class Native::Router::Lisp::Ipv6::SourceLocator::LISPSubinterface : public ydk::Entity { public: LISPSubinterface(); ~LISPSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf lisp; //type: string }; // Native::Router::Lisp::Ipv6::SourceLocator::LISPSubinterface class Native::Router::Lisp::Ipv6::SourceLocator::PortChannelSubinterface : public ydk::Entity { public: PortChannelSubinterface(); ~PortChannelSubinterface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf port_channel; //type: string }; // Native::Router::Lisp::Ipv6::SourceLocator::PortChannelSubinterface class Native::Router::Lisp::Ipv6::UsePetr : public ydk::Entity { public: UsePetr(); ~UsePetr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf locator_address; //type: string ydk::YLeaf priority; //type: uint8 ydk::YLeaf weight; //type: uint8 }; // Native::Router::Lisp::Ipv6::UsePetr class Native::Router::Lisp::LocReachAlgorithm : public ydk::Entity { public: LocReachAlgorithm(); ~LocReachAlgorithm(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf rloc_probing; //type: empty class LsbReports; //type: Native::Router::Lisp::LocReachAlgorithm::LsbReports std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::LocReachAlgorithm::LsbReports> lsb_reports; }; // Native::Router::Lisp::LocReachAlgorithm class Native::Router::Lisp::LocReachAlgorithm::LsbReports : public ydk::Entity { public: LsbReports(); ~LsbReports(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf do_not_transmit; //type: empty ydk::YLeaf ignore; //type: empty }; // Native::Router::Lisp::LocReachAlgorithm::LsbReports class Native::Router::Lisp::LocatorDown : public ydk::Entity { public: LocatorDown(); ~LocatorDown(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf address; //type: string ydk::YLeaf ipv4_interface; //type: string ydk::YLeaf ipv6_interface; //type: string }; // Native::Router::Lisp::LocatorDown class Native::Router::Lisp::LocatorTable : public ydk::Entity { public: LocatorTable(); ~LocatorTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf vrf_name; //type: string ydk::YLeaf default_; //type: empty ydk::YLeaf vrf; //type: string }; // Native::Router::Lisp::LocatorTable class Native::Router::Lisp::MapRequest : public ydk::Entity { public: MapRequest(); ~MapRequest(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf itr_rlocs; //type: string }; // Native::Router::Lisp::MapRequest class Native::Router::Lisp::MapServer : public ydk::Entity { public: MapServer(); ~MapServer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Rloc; //type: Native::Router::Lisp::MapServer::Rloc class SiteRegistration; //type: Native::Router::Lisp::MapServer::SiteRegistration class Nmr; //type: Native::Router::Lisp::MapServer::Nmr class Session; //type: Native::Router::Lisp::MapServer::Session std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::Rloc> rloc; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::SiteRegistration> site_registration; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::Nmr> nmr; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::Session> session; }; // Native::Router::Lisp::MapServer class Native::Router::Lisp::MapServer::Rloc : public ydk::Entity { public: Rloc(); ~Rloc(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Members; //type: Native::Router::Lisp::MapServer::Rloc::Members std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::Rloc::Members> members; }; // Native::Router::Lisp::MapServer::Rloc class Native::Router::Lisp::MapServer::Rloc::Members : public ydk::Entity { public: Members(); ~Members(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf distribute; //type: empty class ModifyDiscovered; //type: Native::Router::Lisp::MapServer::Rloc::Members::ModifyDiscovered std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::MapServer::Rloc::Members::ModifyDiscovered> modify_discovered; }; // Native::Router::Lisp::MapServer::Rloc::Members class Native::Router::Lisp::MapServer::Rloc::Members::ModifyDiscovered : public ydk::Entity { public: ModifyDiscovered(); ~ModifyDiscovered(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf operator_; //type: Operator_ ydk::YLeaf locator_set; //type: string class Operator_; }; // Native::Router::Lisp::MapServer::Rloc::Members::ModifyDiscovered class Native::Router::Lisp::MapServer::SiteRegistration : public ydk::Entity { public: SiteRegistration(); ~SiteRegistration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf limit; //type: uint32 ydk::YLeaf warning_threshold; //type: uint8 }; // Native::Router::Lisp::MapServer::SiteRegistration class Native::Router::Lisp::MapServer::Nmr : public ydk::Entity { public: Nmr(); ~Nmr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf non_site_ttl; //type: uint16 }; // Native::Router::Lisp::MapServer::Nmr class Native::Router::Lisp::MapServer::Session : public ydk::Entity { public: Session(); ~Session(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf passive_open; //type: string }; // Native::Router::Lisp::MapServer::Session class Native::Router::Lisp::OtherXtrProbe : public ydk::Entity { public: OtherXtrProbe(); ~OtherXtrProbe(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf period; //type: uint16 }; // Native::Router::Lisp::OtherXtrProbe class Native::Router::Lisp::RemoteRlocProbe : public ydk::Entity { public: RemoteRlocProbe(); ~RemoteRlocProbe(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf on_membership_change; //type: empty ydk::YLeaf on_route_change; //type: empty }; // Native::Router::Lisp::RemoteRlocProbe class Native::Router::Lisp::EidTable : public ydk::Entity { public: EidTable(); ~EidTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class InstanceList; //type: Native::Router::Lisp::EidTable::InstanceList ydk::YList instance_list; }; // Native::Router::Lisp::EidTable class Native::Router::Lisp::EidTable::InstanceList : public ydk::Entity { public: InstanceList(); ~InstanceList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf instance_id; //type: uint32 ydk::YLeaf vrf_name; //type: string ydk::YLeaf default_; //type: empty ydk::YLeaf vrf; //type: string ydk::YLeaf disable_ttl_propagate; //type: empty class DatabaseMapping; //type: Native::Router::Lisp::EidTable::InstanceList::DatabaseMapping class DynamicEid; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid class Alt; //type: Native::Router::Lisp::EidTable::InstanceList::Alt class ControlPacket; //type: Native::Router::Lisp::EidTable::InstanceList::ControlPacket class Ddt; //type: Native::Router::Lisp::EidTable::InstanceList::Ddt class Decapsulation; //type: Native::Router::Lisp::EidTable::InstanceList::Decapsulation class Etr; //type: Native::Router::Lisp::EidTable::InstanceList::Etr class Ipv4; //type: Native::Router::Lisp::EidTable::InstanceList::Ipv4 class Ipv6; //type: Native::Router::Lisp::EidTable::InstanceList::Ipv6 class LocReachAlgorithm; //type: Native::Router::Lisp::EidTable::InstanceList::LocReachAlgorithm class LocatorDown; //type: Native::Router::Lisp::EidTable::InstanceList::LocatorDown class LocatorTable; //type: Native::Router::Lisp::EidTable::InstanceList::LocatorTable class MapRequest; //type: Native::Router::Lisp::EidTable::InstanceList::MapRequest class MapServer; //type: Native::Router::Lisp::EidTable::InstanceList::MapServer class OtherXtrProbe; //type: Native::Router::Lisp::EidTable::InstanceList::OtherXtrProbe class RemoteRlocProbe; //type: Native::Router::Lisp::EidTable::InstanceList::RemoteRlocProbe class MapCache; //type: Native::Router::Lisp::EidTable::InstanceList::MapCache ydk::YList database_mapping; ydk::YList dynamic_eid; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Alt> alt; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::ControlPacket> control_packet; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Ddt> ddt; // presence node std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Decapsulation> decapsulation; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Etr> etr; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Ipv4> ipv4; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::Ipv6> ipv6; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::LocReachAlgorithm> loc_reach_algorithm; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::LocatorDown> locator_down; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::LocatorTable> locator_table; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::MapRequest> map_request; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::MapServer> map_server; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::OtherXtrProbe> other_xtr_probe; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::RemoteRlocProbe> remote_rloc_probe; ydk::YList map_cache; }; // Native::Router::Lisp::EidTable::InstanceList class Native::Router::Lisp::EidTable::InstanceList::DatabaseMapping : public ydk::Entity { public: DatabaseMapping(); ~DatabaseMapping(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf eid_prefix; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::EidTable::InstanceList::DatabaseMapping class Native::Router::Lisp::EidTable::InstanceList::DynamicEid : public ydk::Entity { public: DynamicEid(); ~DynamicEid(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf map_notify_group; //type: string class DatabaseMapping; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::DatabaseMapping class EidNotify; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify class MapServer; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer ydk::YList database_mapping; std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify> eid_notify; ydk::YList map_server; }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::DatabaseMapping : public ydk::Entity { public: DatabaseMapping(); ~DatabaseMapping(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf eid_prefix; //type: string ydk::YLeaf locator_set; //type: string }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::DatabaseMapping class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify : public ydk::Entity { public: EidNotify(); ~EidNotify(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AuthenticationKey; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::AuthenticationKey class GatewayKey; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::GatewayKey std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::AuthenticationKey> authentication_key; ydk::YList gateway_key; }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::AuthenticationKey : public ydk::Entity { public: AuthenticationKey(); ~AuthenticationKey(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ak_0; //type: string ydk::YLeaf ak_6; //type: string ydk::YLeaf unc_pwd; //type: string }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::AuthenticationKey class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::GatewayKey : public ydk::Entity { public: GatewayKey(); ~GatewayKey(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf gateway_ip; //type: string ydk::YLeaf ak_0; //type: string ydk::YLeaf ak_6; //type: string ydk::YLeaf unc_pwd; //type: string ydk::YLeaf hash_function; //type: HashFunction class HashFunction; }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::GatewayKey class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer : public ydk::Entity { public: MapServer(); ~MapServer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ip; //type: string ydk::YLeaf proxy_reply; //type: empty class Key; //type: Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer::Key std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer::Key> key; }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer::Key : public ydk::Entity { public: Key(); ~Key(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key_0; //type: string ydk::YLeaf key_6; //type: string ydk::YLeaf key_7; //type: string ydk::YLeaf pwd; //type: string ydk::YLeaf hash_function; //type: HashFunction class HashFunction; }; // Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer::Key class Native::Router::Lisp::EidTable::InstanceList::Alt : public ydk::Entity { public: Alt(); ~Alt(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class SummaryRoute; //type: Native::Router::Lisp::EidTable::InstanceList::Alt::SummaryRoute ydk::YList summary_route; }; // Native::Router::Lisp::EidTable::InstanceList::Alt class Native::Router::Lisp::MapServer::Rloc::Members::ModifyDiscovered::Operator_ : public ydk::Enum { public: static const ydk::Enum::YLeaf add; static const ydk::Enum::YLeaf override; static int get_enum_value(const std::string & name) { if (name == "add") return 0; if (name == "override") return 1; return -1; } }; class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::EidNotify::GatewayKey::HashFunction : public ydk::Enum { public: static const ydk::Enum::YLeaf sha1; static const ydk::Enum::YLeaf sha2; static int get_enum_value(const std::string & name) { if (name == "sha1") return 0; if (name == "sha2") return 1; return -1; } }; class Native::Router::Lisp::EidTable::InstanceList::DynamicEid::MapServer::Key::HashFunction : public ydk::Enum { public: static const ydk::Enum::YLeaf sha1; static const ydk::Enum::YLeaf sha2; static int get_enum_value(const std::string & name) { if (name == "sha1") return 0; if (name == "sha2") return 1; return -1; } }; } } #endif /* _CISCO_IOS_XE_NATIVE_193_ */
/** @file lcr4500.cpp * @brief Contains methods to interface with DLP LightCrafter 4500 EVM * @copyright 2014 Texas Instruments Incorporated - http://www.ti.com/ ALL RIGHTS RESERVED */ #include <projector/dlp/common/returncode.hpp> #include <projector/dlp/common/debug.hpp> #include <projector/dlp/common/other.hpp> #include <projector/dlp/common/image/image.hpp> #include <projector/dlp/common/parameters.hpp> #include <projector/dlp/common/pattern/pattern.hpp> #include <vector> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <atomic> #include <ctime> #include <projector/dlp/dlp_platforms/lightcrafter_4500/common.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/error.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/dlpc350_usb.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/dlpc350_firmware.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/flashdevice.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/dlpc350_api.hpp> #include <projector/dlp/dlp_platforms/dlp_platform.hpp> #include <projector/dlp/dlp_platforms/lightcrafter_4500/lcr4500.hpp> /** @brief Contains all DLP SDK classes, functions, etc. */ namespace dlp{ const unsigned char LCr4500::Led::MAXIMUM_CURRENT = 255; const unsigned int LCr4500::ImageIndex::MAXIMUM_INDEX = MAX_SPLASH_IMAGES; const unsigned int LCr4500::Video::TestPattern::COLOR_MAXIMUM = 1023; const unsigned long int LCr4500::Pattern::Exposure::MAXIMUM = 200000000; const unsigned long int LCr4500::Pattern::Exposure::PERIOD_DIFFERENCE_MINIMUM = 230; const unsigned int LCr4500::PATTERN_LUT_SIZE = MAX_VAR_EXP_PAT_LUT_ENTRIES; const unsigned int LCr4500::IMAGE_LUT_SIZE = MAX_VAR_EXP_IMAGE_LUT_ENTRIES; const unsigned int LCr4500::BUFFER_IMAGE_SIZE = 2; unsigned long int LCr4500::Pattern::Exposure::MININUM(const dlp::Pattern::Bitdepth &bitdepth){ switch(bitdepth){ case dlp::Pattern::Bitdepth::MONO_1BPP: return 235; case dlp::Pattern::Bitdepth::MONO_2BPP: return 700; case dlp::Pattern::Bitdepth::MONO_3BPP: return 1570; case dlp::Pattern::Bitdepth::MONO_4BPP: return 1700; case dlp::Pattern::Bitdepth::MONO_5BPP: return 2000; case dlp::Pattern::Bitdepth::MONO_6BPP: return 2500; case dlp::Pattern::Bitdepth::MONO_7BPP: return 4500; case dlp::Pattern::Bitdepth::MONO_8BPP: return 8333; case dlp::Pattern::Bitdepth::RGB_3BPP: return 705; case dlp::Pattern::Bitdepth::RGB_6BPP: return 2100; case dlp::Pattern::Bitdepth::RGB_9BPP: return 4710; case dlp::Pattern::Bitdepth::RGB_12BPP: return 5100; case dlp::Pattern::Bitdepth::RGB_15BPP: return 6000; case dlp::Pattern::Bitdepth::RGB_18BPP: return 7500; case dlp::Pattern::Bitdepth::RGB_21BPP: return 13500; case dlp::Pattern::Bitdepth::RGB_24BPP: return 24999; case dlp::Pattern::Bitdepth::INVALID: default: return MAXIMUM; } } /** @brief Constructs empty object */ LCr4500::LCr4500() { // Set the debug name this->debug_.SetName("LCR4500_DEBUG(" + dlp::Number::ToString(this)+ "): "); // Set the platform this->SetPlatform(Platform::LIGHTCRAFTER_4500); // Set default values this->previous_command_in_progress = false; this->firmware_upload_restart_needed = false; this->pattern_sequence_prepared_ = false; this->firmware_upload_percent_erased_ = 0; this->firmware_upload_percent_complete_ = 0; this->previous_sequence_start_ = 0; this->previous_sequence_patterns_ = 0; this->previous_sequence_repeat_ = false; this->debug_.Msg(1,"Object constructed"); } /** @brief Connects to a DLP LightCrafter 4500 EVM * @param[in] device assigned ID of individual projector * * Functionality of multiple projectors * NOT yet implemented but will allow multiple * projectors to be connected to the DLP SDK. */ ReturnCode LCr4500::Connect(std::string id){ ReturnCode ret; // If A firmware upload is in progress, do NOT send any commands until upload is complete! and does not // need a restard return and error if( this->FirmwareUploadInProgress() && !this->firmware_upload_restart_needed){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // First initialize the HID USB interface if(DLPC350_USB_IsConnected()){ DLPC350_USB_Close(); DLPC350_USB_Exit(); } // Initialize the USB interface this->debug_.Msg("Initializing USB HID interface..."); DLPC350_USB_Init(); // If the HID Interface has been connected already close it if(DLPC350_USB_IsConnected()) DLPC350_USB_Close(); // Attempt to open the LCr4500 USB interface this->debug_.Msg("Opening USB HID interface..."); DLPC350_USB_Open(); // Workaround for DLPC350 error DLPC350_USB_Close(); DLPC350_USB_Open(); // Check if the connection succeeded if(!DLPC350_USB_IsConnected()){ // Connection failed this->debug_.Msg("USB connection failed"); DLPC350_USB_Close(); DLPC350_USB_Exit(); ret.AddError(LCR4500_CONNECTION_FAILED); } else{ // Connection was successful this->debug_.Msg("USB connected successfully"); this->SetID(id); } return ret; } /** @brief Disconnects from the DLP LightCrafter 4500 EVM * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED A LightCrafter 4500 EVM has NOT enumerated on the USB */ ReturnCode LCr4500::Disconnect(){ ReturnCode ret; // If A firmware upload is in progress and does not // need a restard return and error if( this->FirmwareUploadInProgress() && !this->firmware_upload_restart_needed){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // If the HID Interface has been connected already close it if(!DLPC350_USB_IsConnected()){ // The device wasn't connected this->debug_.Msg("Could NOT disconnect USB because it was NOT connected"); ret.AddError(LCR4500_NOT_CONNECTED); } // Close the USB interface this->debug_.Msg("Closing USB HID interface"); DLPC350_USB_Close(); DLPC350_USB_Exit(); return ret; } /** @brief Returns true if the projector object is connected via USB. */ bool LCr4500::isConnected() const{ bool ret = DLPC350_USB_IsConnected(); if(ret){ this->debug_.Msg("USB is connected"); } else{ this->debug_.Msg("USB is NOT connected"); } return ret; } /** @brief Sends a parameters object containing LightCrafter 4500 options * to a LightCrafter 4500 device. * @param[in] arg_parameters Takes an input object of dlp::Parameters type to set LightCrafter 4500 EVM * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED A LightCrafter 4500 EVM has NOT been enumerated on the USB * @retval LCR4500_SETUP_POWER_STANDBY_FAILED The power mode could NOT be set on the LightCrafter 4500 * @retval LCR4500_SETUP_SHORT_AXIS_FLIP_FAILED The short axis flip could NOT be set * @retval LCR4500_SETUP_LONG_AXIS_FLIP_FAILED The long axis flip could NOT be set * @retval LCR4500_SETUP_LED_SEQUENCE_AND_ENABLES_FAILED LED sequence and enables could NOT be set * @retval LCR4500_SETUP_INVERT_LED_PWM_FAILED The inversion of the LED PWM signal could NOT be set * @retval LCR4500_SETUP_LED_CURRENTS_FAILED The LED current values could NOT be set * @retval LCR4500_SETUP_LED_RED_EDGE_DELAYS_FAILED The red LED edge delay could NOT be set * @retval LCR4500_SETUP_LED_GREEN_EDGE_DELAYS_FAILED The green LED edge delay could NOT be set * @retval LCR4500_SETUP_LED_BLUE_EDGE_DELAYS_FAILED The blue LED edge delay could NOT be set * @retval LCR4500_SETUP_INPUT_SOURCE_FAILED The input source could NOT be set * @retval LCR4500_SETUP_PARALLEL_PORT_CLOCK_FAILED The parallel port clock could NOT be set * @retval LCR4500_SETUP_DATA_SWAP_FAILED The color data swap could NOT be set * @retval LCR4500_SETUP_INVERT_DATA_FAILED The inverted color image could NOT be set * @retval LCR4500_SETUP_DISPLAY_MODE_FAILED The display mode could NOT be set * @retval LCR4500_SETUP_TEST_PATTERN_COLOR_FAILED The test pattern color could NOT be set * @retval LCR4500_SETUP_POWER_STANDBY_FAILED The power standby could NOT be set * @retval LCR4500_SETUP_DISPLAY_MODE_FAILED The display mode could NOT be set * @retval LCR4500_SETUP_INPUT_SOURCE_FAILED The input source could NOT be set * @retval LCR4500_SETUP_TEST_PATTERN_FAILED The test pattern could NOT be set * @retval LCR4500_SETUP_FLASH_IMAGE_FAILED The flash image could NOT be set * @retval LCR4500_SETUP_TRIGGER_INPUT_1_DELAY_FAILED The input delay for trigger 1 could NOT be set * @retval LCR4500_SETUP_TRIGGER_OUTPUT_1_FAILED The trigger 1 output could NOT be set * @retval LCR4500_SETUP_TRIGGER_OUTPUT_2_FAILED The trigger 2 output could NOT be set */ ReturnCode LCr4500::Setup(const dlp::Parameters &settings){ ReturnCode ret; bool setup_default = false; // If A firmware upload is in progress return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that LCr4500 is connected if(!this->isConnected()){ this->debug_.Msg("Device is NOT connected"); return ret.AddError(LCR4500_NOT_CONNECTED); } // Stop the display this->debug_.Msg("Stopping pattern display"); if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP)<0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); // Should default values be set? settings.Get(&this->use_default_); if(this->use_default_.Get()){ this->debug_.Msg("Setting the default values..."); setup_default = this->use_default_.Get(); } // Load DLPC350 related file locations if(settings.Contains(this->dlpc350_firmware_)) settings.Get(&this->dlpc350_firmware_); if(settings.Contains(this->dlpc350_flash_parameters_)) settings.Get(&this->dlpc350_flash_parameters_); settings.Get(&this->dlpc350_image_compression_); if(settings.Contains(this->pattern_sequence_firmware_)) settings.Get(&this->pattern_sequence_firmware_); if(settings.Contains(this->verify_image_load_)) settings.Get(&this->verify_image_load_); // Check if parameters contains setup instructions if(setup_default || settings.Contains(this->power_standby_)){ settings.Get(&this->power_standby_); // Send command and check if it succeeded this->debug_.Msg("Setting power mode = " + this->power_standby_.GetEntryValue()); if(DLPC350_SetPowerMode(this->power_standby_.Get()) < 0){ this->debug_.Msg("Setting power mode FAILED"); return ret.AddError(LCR4500_SETUP_POWER_STANDBY_FAILED); } } if(setup_default || settings.Contains(this->short_axis_flip_)){ // Get the value settings.Get(&this->short_axis_flip_); // Send command and check if it succeeded this->debug_.Msg("Setting short axis image flip = " + this->short_axis_flip_.GetEntryValue()); if(DLPC350_SetShortAxisImageFlip(this->short_axis_flip_.Get()) < 0 ){ this->debug_.Msg("Setting short axis image flip FAILED"); return ret.AddError(LCR4500_SETUP_SHORT_AXIS_FLIP_FAILED); } } if(setup_default || settings.Contains(this->long_axis_flip_)){ // Get the value settings.Get(&this->long_axis_flip_); // Send command and check if it succeeded this->debug_.Msg("Setting long axis image flip = " + this->long_axis_flip_.GetEntryValue()); if(DLPC350_SetLongAxisImageFlip(this->long_axis_flip_.Get()) < 0 ){ this->debug_.Msg("Setting long axis image flip FAILED"); return ret.AddError(LCR4500_SETUP_LONG_AXIS_FLIP_FAILED); } } if(setup_default || settings.Contains(this->led_sequence_mode_) || settings.Contains(this->led_red_enable_) || settings.Contains(this->led_green_enable_) || settings.Contains(this->led_blue_enable_)){ // Get the values settings.Get(&this->led_sequence_mode_); settings.Get(&this->led_red_enable_); settings.Get(&this->led_green_enable_); settings.Get(&this->led_blue_enable_); // Send command and check if it succeeded this->debug_.Msg("Setting LED auto sequence = " + this->led_sequence_mode_.GetEntryValue()); this->debug_.Msg("Setting LED enable red = " + this->led_red_enable_.GetEntryValue()); this->debug_.Msg("Setting LED enable green = " + this->led_green_enable_.GetEntryValue()); this->debug_.Msg("Setting LED enable blue = " + this->led_blue_enable_.GetEntryValue()); if(DLPC350_SetLedEnables( this->led_sequence_mode_.Get(), this->led_red_enable_.Get(), this->led_green_enable_.Get(), this->led_blue_enable_.Get()) < 0){ this->debug_.Msg("Setting LED sequence and enables FAILED"); return ret.AddError(LCR4500_SETUP_LED_SEQUENCE_AND_ENABLES_FAILED); } } if(setup_default || settings.Contains(this->led_invert_pwm_)){ // Get the value settings.Get(&this->led_invert_pwm_); // Send command and check if it succeeded if(DLPC350_SetLEDPWMInvert(this->led_invert_pwm_.Get()) < 0) return ret.AddError(LCR4500_SETUP_INVERT_LED_PWM_FAILED); } if(setup_default || settings.Contains(this->led_red_current_) || settings.Contains(this->led_green_current_) || settings.Contains(this->led_blue_current_)){ // Get the value settings.Get(&this->led_red_current_); settings.Get(&this->led_green_current_); settings.Get(&this->led_blue_current_); // Send command and check if it succeeded // Invert the currents for LightCrafter 4500 circuitry if(DLPC350_SetLedCurrents( Led::MAXIMUM_CURRENT - this->led_red_current_.Get(), Led::MAXIMUM_CURRENT - this->led_green_current_.Get(), Led::MAXIMUM_CURRENT - this->led_blue_current_.Get()) < 0) return ret.AddError(LCR4500_SETUP_LED_CURRENTS_FAILED); } if(setup_default || settings.Contains(this->led_red_edge_delay_falling_) || settings.Contains(this->led_red_edge_delay_rising_)){ // Get the settings settings.Get(&this->led_red_edge_delay_rising_); settings.Get(&this->led_red_edge_delay_falling_); // Send command and check if it succeeded if(DLPC350_SetRedLEDStrobeDelay( this->led_red_edge_delay_rising_.Get(), this->led_red_edge_delay_falling_.Get()) < 0) return ret.AddError(LCR4500_SETUP_LED_RED_EDGE_DELAYS_FAILED); } if(setup_default || settings.Contains(this->led_green_edge_delay_falling_) || settings.Contains(this->led_green_edge_delay_rising_)){ // Get the settings settings.Get(&this->led_green_edge_delay_rising_); settings.Get(&this->led_green_edge_delay_falling_); // Send command and check if it succeeded if(DLPC350_SetGreenLEDStrobeDelay( this->led_green_edge_delay_rising_.Get(), this->led_green_edge_delay_falling_.Get()) < 0) return ret.AddError(LCR4500_SETUP_LED_GREEN_EDGE_DELAYS_FAILED); } if(setup_default || settings.Contains(this->led_blue_edge_delay_falling_) || settings.Contains(this->led_blue_edge_delay_rising_)){ // Get the settings settings.Get(&this->led_blue_edge_delay_rising_); settings.Get(&this->led_blue_edge_delay_falling_); // Send command and check if it succeeded if(DLPC350_SetBlueLEDStrobeDelay( this->led_blue_edge_delay_rising_.Get(), this->led_blue_edge_delay_falling_.Get()) < 0) return ret.AddError(LCR4500_SETUP_LED_BLUE_EDGE_DELAYS_FAILED); } if(setup_default || settings.Contains(this->input_source_) || settings.Contains(this->parallel_port_width_)){ // Get the value settings.Get(&this->input_source_); settings.Get(&this->parallel_port_width_); if(DLPC350_SetInputSource(this->input_source_.Get(), this->parallel_port_width_.Get()) < 0) return ret.AddError(LCR4500_SETUP_INPUT_SOURCE_FAILED); } if(setup_default || settings.Contains(this->parallel_port_clock_)){ // Get the value settings.Get(&this->parallel_port_clock_); if(DLPC350_SetPortClock(this->parallel_port_clock_.Get()) < 0) return ret.AddError(LCR4500_SETUP_PARALLEL_PORT_CLOCK_FAILED); } /* if(setup_default || settings.Contains(this->parallel_data_swap_)){ // Get the value settings.Get(&this->parallel_data_swap_); if(DLPC350_SetDataChannelSwap(LCr4500::Video::DataSwap::Port::PARALLEL_INTERFACE, this->parallel_data_swap_.Get()) < 0) return ret.AddError(LCR4500_SETUP_DATA_SWAP_FAILED); } */ if(setup_default || settings.Contains(this->invert_data_)){ // Get the value and check that it existed settings.Get(&this->invert_data_); // Send command and check if it succeeded if(DLPC350_SetInvertData(this->invert_data_.Get()) < 0) return ret.AddError(LCR4500_SETUP_INVERT_DATA_FAILED); } if(setup_default || settings.Contains(this->display_mode_)){ bool mode_previous; // Set power mode to normal if(DLPC350_SetPowerMode(PowerStandbyMode::NORMAL) < 0) return ret.AddError(LCR4500_SETUP_POWER_STANDBY_FAILED); // Get the pattern settings.Get(&this->display_mode_); // Check the current mode if(DLPC350_GetMode(&mode_previous)<0) return ret.AddError(LCR4500_GET_OPERATING_MODE_FAILED); // The current mode is different from the requested setting change it if(mode_previous != this->display_mode_.Get()){ if(DLPC350_SetMode(this->display_mode_.Get()) < 0) return ret.AddError(LCR4500_SETUP_DISPLAY_MODE_FAILED); } } if(setup_default || settings.Contains(this->test_pattern_foreground_red) || settings.Contains(this->test_pattern_foreground_green) || settings.Contains(this->test_pattern_foreground_blue) || settings.Contains(this->test_pattern_background_red) || settings.Contains(this->test_pattern_background_green) || settings.Contains(this->test_pattern_background_blue)) { // Get the test pattern foreground and background colors settings.Get(&this->test_pattern_foreground_red); settings.Get(&this->test_pattern_foreground_green); settings.Get(&this->test_pattern_foreground_blue); settings.Get(&this->test_pattern_background_red); settings.Get(&this->test_pattern_background_green); settings.Get(&this->test_pattern_background_blue); // Send command to LCr4500 if(DLPC350_SetTPGColor(this->test_pattern_foreground_red.Get(), this->test_pattern_foreground_green.Get(), this->test_pattern_foreground_blue.Get(), this->test_pattern_background_red.Get(), this->test_pattern_background_green.Get(), this->test_pattern_background_blue.Get()) < 0) return ret.AddError(LCR4500_SETUP_TEST_PATTERN_COLOR_FAILED); } if(settings.Contains(Parameters::VideoTestPattern())){ // Get the value Parameters::VideoTestPattern test_pattern; // Get the test pattern settings.Get(&test_pattern); // Set the current power mode if(DLPC350_SetPowerMode(PowerStandbyMode::NORMAL) < 0) return ret.AddError(LCR4500_SETUP_POWER_STANDBY_FAILED); // Check the display mode bool mode; if(DLPC350_GetMode(&mode)<0) return ret.AddError(LCR4500_GET_OPERATING_MODE_FAILED); // If the display mode is NOT video switch it if(mode != OperatingMode::VIDEO){ if(DLPC350_SetMode(OperatingMode::VIDEO) < 0) return ret.AddError(LCR4500_SETUP_DISPLAY_MODE_FAILED); } dlp::Time::Sleep::Milliseconds(10); if(DLPC350_SetInputSource(Video::InputSource::INTERNAL_TEST_PATTERNS, Video::ParallelPortWidth::BITS_30) < 0) return ret.AddError(LCR4500_SETUP_INPUT_SOURCE_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_SetTPGColor(0,0,0,1023,1023,1023) < 0) return ret.AddError(LCR4500_SETUP_TEST_PATTERN_COLOR_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_SetTPGSelect(test_pattern.Get()) < 0) return ret.AddError(LCR4500_SETUP_TEST_PATTERN_FAILED); } if(settings.Contains(Parameters::VideoFlashImage())){ // Get the value Parameters::VideoFlashImage flash_image; bool mode; unsigned int source; unsigned int portWidth; settings.Get(&flash_image); if(DLPC350_SetPowerMode(PowerStandbyMode::NORMAL) < 0) return ret.AddError(LCR4500_SETUP_POWER_STANDBY_FAILED); // Check the display mode if(DLPC350_GetMode(&mode)<0) return ret.AddError(LCR4500_GET_OPERATING_MODE_FAILED); // If the display mode is NOT video switch it if(mode != OperatingMode::VIDEO){ if(DLPC350_SetMode(OperatingMode::VIDEO) < 0) return ret.AddError(LCR4500_SETUP_DISPLAY_MODE_FAILED); } dlp::Time::Sleep::Milliseconds(10); DLPC350_GetInputSource(&source, &portWidth); if (source != Video::InputSource::FLASH_IMAGES){ if(DLPC350_SetInputSource(Video::InputSource::FLASH_IMAGES, Video::ParallelPortWidth::BITS_30) < 0) return ret.AddError(LCR4500_SETUP_INPUT_SOURCE_FAILED); } dlp::Time::Sleep::Milliseconds(10); if(DLPC350_LoadImageIndex(flash_image.Get()) < 0) return ret.AddError(LCR4500_SETUP_FLASH_IMAGE_FAILED); } if(settings.Contains(this->trigger_source_)){ // Get the value and check that it existed settings.Get(&this->trigger_source_); } if(settings.Contains(this->sequence_prepared_)){ // Get the value and check that it existed settings.Get(&this->sequence_prepared_); } if(settings.Contains(this->sequence_exposure_)){ // Get the value and check that it existed settings.Get(&this->sequence_exposure_); } if(settings.Contains(this->sequence_period_)){ // Get the value and check that it existed settings.Get(&this->sequence_period_); } if(settings.Contains(this->trigger_in_1_delay_)){ // Get the value and check that it existed settings.Get(&this->trigger_in_1_delay_); if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); // Send command and check if it succeeded if(DLPC350_SetTrigIn1Delay(this->trigger_in_1_delay_.Get()) == -1 ) return ret.AddError(LCR4500_SETUP_TRIGGER_INPUT_1_DELAY_FAILED); } if( settings.Contains(this->trigger_out_1_invert_) || settings.Contains(this->trigger_out_1_rising_) || settings.Contains(this->trigger_out_1_falling_)){ // Get the value and check that it existed settings.Get(&this->trigger_out_1_invert_); settings.Get(&this->trigger_out_1_rising_); settings.Get(&this->trigger_out_1_falling_); if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); // Send command and check if it succeeded if(DLPC350_SetTrigOutConfig( LCR4500_TRIGGER_OUT_1, this->trigger_out_1_invert_.Get(), this->trigger_out_1_rising_.Get(), this->trigger_out_1_falling_.Get()) == -1 ) return ret.AddError(LCR4500_SETUP_TRIGGER_OUTPUT_1_FAILED); } if( settings.Contains(this->trigger_out_2_invert_) || settings.Contains(this->trigger_out_2_rising_)){ // Get the value and check that it existed settings.Get(&this->trigger_out_2_invert_); settings.Get(&this->trigger_out_2_rising_); if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); // Send command and check if it succeeded if(DLPC350_SetTrigOutConfig( LCR4500_TRIGGER_OUT_2, this->trigger_out_2_invert_.Get(), this->trigger_out_2_rising_.Get(), 0) == -1 ) return ret.AddError(LCR4500_SETUP_TRIGGER_OUTPUT_2_FAILED); } this->is_setup_ = true; return ret; } /** @brief Retrieves object settings * @param[out] ret_parameters Pointer to return \ref dlp::Parameters object containing setup for LightCrafter 4500 * * @retval LCR4500_NULL_POINT_ARGUMENT_PARAMETERS The pointer is null * @retval DLP_PLATFORM_NOT_SETUP The LightCrafter 4500 has NOT been set up */ ReturnCode LCr4500::GetSetup(dlp::Parameters* settings) const{ ReturnCode ret; // Check that pointer is NOT null if(!settings) return ret.AddError(LCR4500_NULL_POINT_ARGUMENT_PARAMETERS); if(!this->isPlatformSetup()) return ret.AddError(DLP_PLATFORM_NOT_SETUP); // Clear the parameters list settings->Clear(); settings->Set(this->dlpc350_firmware_); settings->Set(this->dlpc350_flash_parameters_); settings->Set(this->dlpc350_image_compression_); settings->Set(this->pattern_sequence_firmware_); settings->Set(this->use_default_); settings->Set(this->power_standby_); settings->Set(this->display_mode_); settings->Set(this->input_source_); settings->Set(this->parallel_port_width_); settings->Set(this->parallel_port_clock_); settings->Set(this->parallel_data_swap_); settings->Set(this->invert_data_); settings->Set(this->short_axis_flip_); settings->Set(this->long_axis_flip_); settings->Set(this->led_sequence_mode_); settings->Set(this->led_invert_pwm_); settings->Set(this->led_red_enable_); settings->Set(this->led_red_current_); settings->Set(this->led_red_edge_delay_rising_); settings->Set(this->led_red_edge_delay_falling_); settings->Set(this->led_green_enable_); settings->Set(this->led_green_current_); settings->Set(this->led_green_edge_delay_rising_); settings->Set(this->led_green_edge_delay_falling_); settings->Set(this->led_blue_enable_); settings->Set(this->led_blue_current_); settings->Set(this->led_blue_edge_delay_rising_); settings->Set(this->led_blue_edge_delay_falling_); settings->Set(this->trigger_in_1_delay_); settings->Set(this->trigger_out_1_invert_); settings->Set(this->trigger_out_2_invert_); settings->Set(this->trigger_out_1_rising_); settings->Set(this->trigger_out_1_falling_); settings->Set(this->trigger_out_2_rising_); settings->Set(this->verify_image_load_); return ret; } /** @brief Projects a continuous solid white pattern from a connected LightCrafter 4500 * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED A LightCrafter 4500 EVM has NOT enumerated on the USB */ ReturnCode LCr4500::ProjectSolidWhitePattern(){ ReturnCode ret; // If A firmware upload is in progress return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that LCr4500 is connected if(this->isConnected()){ dlp::Pattern::Sequence sequence; dlp::Pattern white_pattern; // Setup Pattern white_pattern.id = 0; white_pattern.exposure = this->sequence_exposure_.Get(); white_pattern.period = this->sequence_period_.Get(); white_pattern.bitdepth = dlp::Pattern::Bitdepth::MONO_1BPP; white_pattern.color = dlp::Pattern::Color::WHITE; white_pattern.data_type = dlp::Pattern::DataType::PARAMETERS; white_pattern.parameters.Set(Parameters::PatternNumber(LCr4500::Pattern::Number::Mono_1BPP::BLACK)); white_pattern.parameters.Set(Parameters::PatternImageIndex(0)); white_pattern.parameters.Set(Parameters::PatternInvert(true)); white_pattern.parameters.Set(Parameters::PatternShareExposure(false)); white_pattern.parameters.Set(this->trigger_source_); // Add pattern to sequence sequence.Add(white_pattern); sequence.parameters.Set(Parameters::PatternSequenceRepeat(true)); // Pattern LUT will be updated so reset these values this->previous_sequence_start_ = 0; this->previous_sequence_patterns_ = 0; this->previous_sequence_repeat_ = false; // Send the LUT and start the sequence ret = this->CreateSendStartSequenceLut(sequence); } else{ // Device NOT connected ret.AddError(LCR4500_NOT_CONNECTED); } return ret; } /** @brief Projects a continuous solid black pattern from a connected LightCrafter 4500 * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED A LightCrafter 4500 EVM has NOT enumerated on the USB */ ReturnCode LCr4500::ProjectSolidBlackPattern(){ ReturnCode ret; // If A firmware upload is in progress return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that LCr4500 is connected if(this->isConnected()){ dlp::Pattern::Sequence sequence; dlp::Pattern black_pattern; // Setup Pattern black_pattern.id = 0; black_pattern.exposure = this->sequence_exposure_.Get(); black_pattern.period = this->sequence_period_.Get(); black_pattern.bitdepth = dlp::Pattern::Bitdepth::MONO_1BPP; black_pattern.color = dlp::Pattern::Color::WHITE; black_pattern.data_type = dlp::Pattern::DataType::PARAMETERS; black_pattern.parameters.Set(Parameters::PatternNumber(LCr4500::Pattern::Number::Mono_1BPP::BLACK)); black_pattern.parameters.Set(Parameters::PatternImageIndex(0)); black_pattern.parameters.Set(Parameters::PatternInvert(false)); black_pattern.parameters.Set(Parameters::PatternShareExposure(false)); black_pattern.parameters.Set(this->trigger_source_); // Add pattern to sequence sequence.Add(black_pattern); sequence.parameters.Set(Parameters::PatternSequenceRepeat(true)); // Pattern LUT will be updated so reset these values this->previous_sequence_start_ = 0; this->previous_sequence_patterns_ = 0; this->previous_sequence_repeat_ = false; // Send the LUT and start the sequence ret = this->CreateSendStartSequenceLut(sequence); } else{ // Device NOT connected ret.AddError(LCR4500_NOT_CONNECTED); } return ret; } /** @brief Checks for valid pattern settings in \ref dlp::Pattern object * @param[in] arg_pattern \ref dlp::Pattern object to verify * * @retval PATTERN_EXPOSURE_TOO_SHORT Pattern exposure time is set too short * @retval PATTERN_EXPOSURE_TOO_LONG Pattern exposure time is set too long * @retval PATTERN_BITDEPTH_INVALID The pattern's bit depth is an invalid value * @retval PATTERN_EXPOSURE_INVALID Pattern exposure period is an invalid value * @retval FILE_DOES_NOT_EXIST The pattern's image file could NOT be found * @retval LCR4500_IMAGE_RESOLUTION_INVALID The image is of an invalid resolution. Please use the native LCr4500 resolution 912x1140 * @retval LCR4500_IMAGE_FORMAT_INVALID The image format does NOT match the pattern settings color type * @retval LCR4500_PATTERN_NUMBER_PARAMETER_MISSING The pattern is missing the number parameter * @retval LCR4500_PATTERN_FLASH_INDEX_PARAMETER_MISSING The pattern is missing the flash image index * @retval PATTERN_DATA_TYPE_INVALID The pattern isn't of a valid data type */ ReturnCode LCr4500::PatternSettingsValid(dlp::Pattern &arg_pattern){ ReturnCode ret; unsigned int exposure = arg_pattern.exposure; unsigned int period = arg_pattern.period; // Check that exposure time is equal to period time or at meets delta requirement if((exposure == period) || (exposure <= (period - dlp::LCr4500::Pattern::Exposure::PERIOD_DIFFERENCE_MINIMUM))){ if(arg_pattern.bitdepth != dlp::Pattern::Bitdepth::INVALID){ if(exposure < dlp::LCr4500::Pattern::Exposure::MININUM(arg_pattern.bitdepth )) ret.AddError(PATTERN_EXPOSURE_TOO_SHORT); if(exposure > dlp::LCr4500::Pattern::Exposure::MAXIMUM) ret.AddError(PATTERN_EXPOSURE_TOO_LONG); } else{ ret.AddError(PATTERN_BITDEPTH_INVALID); } } else{ // Exposure period was invalid ret.AddError(PATTERN_EXPOSURE_INVALID); } // Check image resolution if image data or image file supplied if(!ret.hasErrors()){ Image::Format temp_format; if(arg_pattern.data_type == dlp::Pattern::DataType::IMAGE_FILE){ Image temp_image; // Check if file exists if(!dlp::File::Exists(arg_pattern.image_file)) return ret.AddError(FILE_DOES_NOT_EXIST); // Load the image file temp_image.Load(arg_pattern.image_file); // Check image resolution if(!this->ImageResolutionCorrect(temp_image)){ return ret.AddError(LCR4500_IMAGE_RESOLUTION_INVALID); } // Get it's data format temp_image.GetDataFormat(&temp_format); // If RGB pattern make sure image is RGB also if(arg_pattern.color == dlp::Pattern::Color::RGB){ if(temp_format != Image::Format::RGB_UCHAR) return ret.AddError(LCR4500_IMAGE_FORMAT_INVALID); } // Clear the image temp_image.Clear(); } else if(arg_pattern.data_type == dlp::Pattern::DataType::IMAGE_DATA){ // Check image resolution if(!this->ImageResolutionCorrect(arg_pattern.image_data)){ return ret.AddError(LCR4500_IMAGE_RESOLUTION_INVALID); } // Get the image data format arg_pattern.image_data.GetDataFormat(&temp_format); // If RGB pattern make sure image is also RGB if(arg_pattern.color == dlp::Pattern::Color::RGB){ if(temp_format != Image::Format::RGB_UCHAR) return ret.AddError(LCR4500_IMAGE_FORMAT_INVALID); } } else if(arg_pattern.data_type == dlp::Pattern::DataType::PARAMETERS){ // No Image resolution check required // Check if pattern is RGB or monochrome if(arg_pattern.color != dlp::Pattern::Color::RGB){ // Patern is monochrome // Check for pattern number if(!arg_pattern.parameters.Contains(Parameters::PatternNumber())) return ret.AddError(LCR4500_PATTERN_NUMBER_PARAMETER_MISSING); // Check for image number if(!arg_pattern.parameters.Contains(Parameters::PatternImageIndex())) return ret.AddError(LCR4500_PATTERN_FLASH_INDEX_PARAMETER_MISSING); } else{ // Pattern is RGB // Check for red channel parameters // Check for pattern number if(!arg_pattern.parameters.Contains(Parameters::PatternNumberRed())) return ret.AddError(LCR4500_PATTERN_NUMBER_PARAMETER_MISSING); // Check for image number if(!arg_pattern.parameters.Contains(Parameters::PatternImageIndexRed())) return ret.AddError(LCR4500_PATTERN_FLASH_INDEX_PARAMETER_MISSING); // Check for green channel paramaters // Check for pattern number if(!arg_pattern.parameters.Contains(Parameters::PatternNumberGreen())) return ret.AddError(LCR4500_PATTERN_NUMBER_PARAMETER_MISSING); // Check for image number if(!arg_pattern.parameters.Contains(Parameters::PatternImageIndexGreen())) return ret.AddError(LCR4500_PATTERN_FLASH_INDEX_PARAMETER_MISSING); // Check for blue channel parameters // Check for pattern number if(!arg_pattern.parameters.Contains(Parameters::PatternNumberBlue())) return ret.AddError(LCR4500_PATTERN_NUMBER_PARAMETER_MISSING); // Check for image number if(!arg_pattern.parameters.Contains(Parameters::PatternImageIndexBlue())) return ret.AddError(LCR4500_PATTERN_FLASH_INDEX_PARAMETER_MISSING); } } else{ return ret.AddError(PATTERN_DATA_TYPE_INVALID); } } return ret; } /** @brief Creates, sends, and starts a sequence of patterns using the * LightCrafter 4500 look up table format * \note This function should only be used by experienced DLPC350 programmers * \note The supplied \ref dlp::Pattern::Sequence MUST use LCr4500 parameters * @param[in] arg_pattern_sequence object of \ref dlp::Pattern::Sequence type containing sequence * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED The LightCrafter 4500 EVM is NOT connected * @retval PATTERN_SEQUENCE_EMPTY The pattern sequence sent contains no patterns * @retval PATTERN_SEQUENCE_EXPOSURES_NOT_EQUAL The exposure times are NOT equal for each pattern in the sequence * @retval PATTERN_SEQUENCE_PERIODS_NOT_EQUAL The periods are NOT equal for each pattern in the sequence * @retval PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL The pattern types are NOT equal for each pattern in the sequence * @retval PATTERN_DATA_TYPE_INVALID The data type of the pattern is invalid * @retval PATTERN_SEQUENCE_TOO_LONG The pattern sequence excedes the supported number of patterns * @retval LCR4500_FLASH_IMAGE_INDEX_INVALID A flash image with the specified index is NOT valid * @retval LCR4500_IMAGE_LIST_TOO_LONG Too many images have been created to fit in LightCrafter 4500 flash * @retval LCR4500_PATTERN_SEQUENCE_BUFFERSWAP_TIME_ERROR Buffer swap has occured prematurely */ ReturnCode LCr4500::CreateSendStartSequenceLut(const dlp::Pattern::Sequence &arg_pattern_sequence){ ReturnCode ret; unsigned int sequence_count = arg_pattern_sequence.GetCount(); dlp::Pattern::DataType sequence_type = dlp::Pattern::DataType::INVALID; unsigned int sequence_exposure = 0; unsigned int sequence_period = 0; unsigned int sequence_validation = 0; std::vector<LCR4500_LUT_Entry> sequence_LUT; std::vector<unsigned char> sequence_image_LUT; Parameters::PatternImageIndex flash_image; Parameters::PatternImageIndex flash_image_previous; dlp::Pattern temp_pattern; // If A firmware upload is in progress return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that LCr4500 is connected if(!this->isConnected()){ // Device NOT connected return ret.AddError(LCR4500_NOT_CONNECTED); } // Check that the sequence has entries if(sequence_count == 0) return ret.AddError(PATTERN_SEQUENCE_EMPTY); // Check that all pattern types are equal if(!arg_pattern_sequence.EqualDataTypes()) return ret.AddError(PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL); // Get the sequence type ret = arg_pattern_sequence.Get(0,&temp_pattern); sequence_type = temp_pattern.data_type; // Create the new pattern sequence that the LCr4500 can use dlp::Pattern::Sequence sequence_to_project; switch(sequence_type){ case dlp::Pattern::DataType::INVALID: case dlp::Pattern::DataType::IMAGE_DATA: case dlp::Pattern::DataType::IMAGE_FILE: return ret.AddError(PATTERN_DATA_TYPE_INVALID); case dlp::Pattern::DataType::PARAMETERS: sequence_to_project.Add(arg_pattern_sequence); break; } // Stop the display if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - Pattern display stop"); // Get and set the exposure and trigger time sequence_exposure = this->sequence_exposure_.Get(); sequence_period = this->sequence_period_.Get(); // If the first pattern does not have a set exposure or period // assume the entire sequence should use the timing parameters // defined during the LCr4500::Setup() method // Check if exposure and period have been entered if(temp_pattern.exposure == 0 || temp_pattern.period == 0){ sequence_to_project.SetExposures(sequence_exposure); sequence_to_project.SetPeriods(sequence_period); } // Check pattern sequence timing and create LUT for(unsigned int iPat = 0; iPat < sequence_count; iPat++){ // Check that maximum sequence has NOT been exceeded if( sequence_LUT.size() > LCr4500::PATTERN_LUT_SIZE ) return ret.AddError(PATTERN_SEQUENCE_TOO_LONG); // Get the pattern temp_pattern.parameters.Clear(); ret = sequence_to_project.Get(iPat,&temp_pattern); if( ret.hasErrors()) return ret; // Check the pattern timing ret = PatternSettingsValid(temp_pattern); if( ret.hasErrors()) return ret; // Increment sequence pattern count if(temp_pattern.color != dlp::Pattern::Color::RGB){ // Setup the LUT entry LCR4500_LUT_Entry pattern_entry; // Copy the pattern timings pattern_entry.exposure = temp_pattern.exposure; pattern_entry.period = temp_pattern.period; // Determine trigger type Parameters::TriggerSource pattern_trigger; temp_pattern.parameters.Get(&pattern_trigger); pattern_entry.trigger_type = pattern_trigger.Get(); // Determine bit depth pattern_entry.bit_depth = DlpPatternBitdepthToLCr4500Bitdepth(temp_pattern.bitdepth); // Determine LED select pattern_entry.LED_select = DlpPatternColorToLCr4500Led(temp_pattern.color); // Determine pattern should be inverted Parameters::PatternInvert pattern_invert; temp_pattern.parameters.Get(&pattern_invert); pattern_entry.invert_pattern = pattern_invert.Get(); // Insert black fill should be used if period and exposure are NOT equal // or external triggers are used if((temp_pattern.exposure != temp_pattern.period) || (pattern_entry.trigger_type != LCr4500::Pattern::TriggerSource::INTERNAL)){ pattern_entry.insert_black = true; } else{ pattern_entry.insert_black = false; } // Determine pattern number Parameters::PatternNumber pattern_number; temp_pattern.parameters.Get(&pattern_number); pattern_entry.pattern_number = pattern_number.Get(); // Determine pattern image temp_pattern.parameters.Get(&flash_image); // Check that pattern image is valid if(flash_image.Get() >= LCr4500::IMAGE_LUT_SIZE ) return ret.AddError(LCR4500_FLASH_IMAGE_INDEX_INVALID); // Does this pattern have the same image as the previous one? if((flash_image.Get() == flash_image_previous.Get()) && (iPat != 0)){ // The first pattern should always have a buffer swap // Same image used so buffer swap is NOT needed pattern_entry.buffer_swap = false; } else{ // Different image so buffer swap is needed pattern_entry.buffer_swap = true; // Add the image number to the Image LUT sequence_image_LUT.push_back(flash_image.Get()); flash_image_previous.Set(flash_image.Get()); } // Determine share previous trigger out (exposure sharing) Parameters::PatternShareExposure share_exposure; temp_pattern.parameters.Get(&share_exposure); pattern_entry.trigger_out_share_prev = share_exposure.Get(); // If exposure is shared disable black post-fill if( pattern_entry.trigger_out_share_prev ){ pattern_entry.insert_black = false; } // If using external trigger and NOT the first pattern, set the // previous pattern to clear the DMD after its exposure if( (sequence_LUT.size() != 0) && ((pattern_entry.trigger_type == LCr4500::Pattern::TriggerSource::EXTERNAL_NEGATIVE) || (pattern_entry.trigger_type == LCr4500::Pattern::TriggerSource::EXTERNAL_POSITIVE))){ sequence_LUT.at(sequence_LUT.size()-1).insert_black = true; } // Non RGB patterns only use one entry slot in LUT sequence_LUT.push_back(pattern_entry); } else{ // Setup the LUT entry LCR4500_LUT_Entry pattern_entry_red; LCR4500_LUT_Entry pattern_entry_green; LCR4500_LUT_Entry pattern_entry_blue; // Copy the pattern timings // For the red channel use a third of the pattern exposure // time and set the period equal to its channel exposure time // so that the green channel displays immediately afterwards pattern_entry_red.exposure = temp_pattern.exposure / 3; pattern_entry_red.period = temp_pattern.exposure / 3; // For the green channel use a third of the pattern exposure // time and set the period equal to its channel exposure time // so that the blue channel displays immediately afterwards pattern_entry_green.exposure = temp_pattern.exposure / 3; pattern_entry_green.period = temp_pattern.exposure / 3; // For the blue channel use a third of the pattern exposure // time and set the blue channels period equal such that the // total RGB pattern period will terminate at the same moment pattern_entry_blue.exposure = temp_pattern.exposure / 3; pattern_entry_blue.period = (temp_pattern.period - temp_pattern.exposure) + (temp_pattern.exposure / 3); // Red pattern determines the overall RGB trigger type Parameters::TriggerSource pattern_trigger_red; temp_pattern.parameters.Get(&pattern_trigger_red); pattern_entry_red.trigger_type = pattern_trigger_red.Get(); // Green and blue patterns don't have a trigger because // they are a continuation of the RGB pattern pattern_entry_green.trigger_type = LCr4500::Pattern::TriggerSource::NONE; pattern_entry_blue.trigger_type = LCr4500::Pattern::TriggerSource::NONE; // Determine bit depth. SDK only enables equal color channel bitdepths for RGB pattern_entry_red.bit_depth = DlpPatternBitdepthToLCr4500Bitdepth(temp_pattern.bitdepth); pattern_entry_green.bit_depth = pattern_entry_red.bit_depth; pattern_entry_blue.bit_depth = pattern_entry_red.bit_depth; // Determine LED select pattern_entry_red.LED_select = LCr4500::Pattern::Led::RED; pattern_entry_green.LED_select = LCr4500::Pattern::Led::GREEN; pattern_entry_blue.LED_select = LCr4500::Pattern::Led::BLUE; // Determine invert pattern Parameters::PatternInvert rgb_pattern_invert; temp_pattern.parameters.Get(&rgb_pattern_invert); pattern_entry_red.invert_pattern = rgb_pattern_invert.Get(); pattern_entry_green.invert_pattern = pattern_entry_red.invert_pattern; pattern_entry_blue.invert_pattern = pattern_entry_red.invert_pattern; // Determine pattern number Parameters::PatternNumberRed pattern_number_red; Parameters::PatternNumberGreen pattern_number_green; Parameters::PatternNumberBlue pattern_number_blue; temp_pattern.parameters.Get(&pattern_number_red); pattern_entry_red.pattern_number = pattern_number_red.Get(); temp_pattern.parameters.Get(&pattern_number_green); pattern_entry_green.pattern_number = pattern_number_green.Get(); temp_pattern.parameters.Get(&pattern_number_blue); pattern_entry_blue.pattern_number = pattern_number_blue.Get(); // Determine buffer swap by if the image changed or not Parameters::PatternImageIndexRed flash_image_red; Parameters::PatternImageIndexGreen flash_image_green; Parameters::PatternImageIndexBlue flash_image_blue; temp_pattern.parameters.Get(&flash_image_red); // Check that pattern image is valid if(flash_image_red.Get() >= LCr4500::IMAGE_LUT_SIZE ) return ret.AddError(LCR4500_FLASH_IMAGE_INDEX_INVALID); // Does this pattern have the same image as the previous one? if((flash_image_previous.Get() == flash_image_red.Get()) && (iPat != 0)){ // If this is the first pattern add a buffer swap // Same image used so buffer swap is NOT needed pattern_entry_red.buffer_swap = false; } else{ // Different image so buffer swap is needed pattern_entry_red.buffer_swap = true; // Add the image number to the Image LUT sequence_image_LUT.push_back(flash_image_red.Get()); flash_image_previous.Set(flash_image_red.Get()); } // Determine buffer swap by if the image changed or not temp_pattern.parameters.Get(&flash_image_green); // Check that pattern image is valid if(flash_image_green.Get() >= LCr4500::IMAGE_LUT_SIZE ) return ret.AddError(LCR4500_FLASH_IMAGE_INDEX_INVALID); // Does this pattern have the same image as the previous one? // No need to check if first pattern because red portion already // would add required buffer swap if(flash_image_previous.Get() == flash_image_green.Get() ){ // Same image used so buffer swap is NOT needed pattern_entry_green.buffer_swap = false; } else{ // Different image so buffer swap is needed pattern_entry_green.buffer_swap = true; // Add the image number to the Image LUT sequence_image_LUT.push_back(flash_image_green.Get()); flash_image_previous.Set(flash_image_green.Get()); } // Determine buffer swap by if the image changed or not temp_pattern.parameters.Get(&flash_image_blue); // Check that pattern image is valid if(flash_image_blue.Get() >= LCr4500::IMAGE_LUT_SIZE ) return ret.AddError(LCR4500_FLASH_IMAGE_INDEX_INVALID); // Does this pattern have the same image as the previous one? if(flash_image_previous.Get() == flash_image_blue.Get() ){ // Same image used so buffer swap is NOT needed pattern_entry_blue.buffer_swap = false; } else{ // Different image so buffer swap is needed pattern_entry_blue.buffer_swap = true; // Add the image number to the Image LUT sequence_image_LUT.push_back(flash_image_blue.Get()); flash_image_previous.Set(flash_image_blue.Get()); } // Determine share previous trigger out (exposure sharing) Parameters::PatternShareExposure share_exposure_rgb; temp_pattern.parameters.Get(&share_exposure_rgb); pattern_entry_red.trigger_out_share_prev = share_exposure_rgb.Get(); pattern_entry_green.trigger_out_share_prev = true; pattern_entry_blue.trigger_out_share_prev = true; // Insert black fill should be used if period and exposure are NOT equal if((temp_pattern.exposure != temp_pattern.period) || (pattern_entry_red.trigger_type != LCr4500::Pattern::TriggerSource::INTERNAL)){ pattern_entry_red.insert_black = false; pattern_entry_green.insert_black = false; pattern_entry_blue.insert_black = true; } else{ pattern_entry_red.insert_black = false; pattern_entry_green.insert_black = false; pattern_entry_blue.insert_black = false; } // If using external trigger and NOT the first pattern, set the // previous pattern to clear the DMD after its exposure if( (sequence_LUT.size() != 0) && ((pattern_entry_red.trigger_type == LCr4500::Pattern::TriggerSource::EXTERNAL_NEGATIVE) || (pattern_entry_red.trigger_type == LCr4500::Pattern::TriggerSource::EXTERNAL_POSITIVE))){ sequence_LUT.at(sequence_LUT.size()-1).insert_black = true; } // Add each single color pattern to create the RGB pattern sequence_LUT.push_back(pattern_entry_red); sequence_LUT.push_back(pattern_entry_green); sequence_LUT.push_back(pattern_entry_blue); } } // Check number of patterns is NOT greater than the LUT size if( sequence_LUT.size() > LCr4500::PATTERN_LUT_SIZE ) return ret.AddError(PATTERN_SEQUENCE_TOO_LONG); // Check that the number of images is NOT greater than the image LUT size if( sequence_image_LUT.size() > LCr4500::IMAGE_LUT_SIZE) return ret.AddError(LCR4500_IMAGE_LIST_TOO_LONG); // Check the image load times if there are more than two images // If there are more images than the buffer can hold, only one image is preloaded if( (sequence_image_LUT.size() > LCr4500::BUFFER_IMAGE_SIZE) && (this->verify_image_load_.Get() > 0)){ unsigned long long time_since_buffer_swap = 0; // in microseconds unsigned int jImage = 0; for(unsigned int iPat = 0; iPat < sequence_LUT.size(); iPat++){ // Check for bufferswap (do NOT check first pattern because that flash index is always preloaded) if(sequence_LUT.at(iPat).buffer_swap && iPat > 0){ double max_time; // Get the average image load time this->GetImageLoadTime(jImage,this->verify_image_load_.Get(),&max_time); this->debug_.Msg("Image "+dlp::Number::ToString(jImage)+" load time\t= " + dlp::Number::ToString(max_time)); this->debug_.Msg("Time since buffer swap\t= " + dlp::Number::ToString(time_since_buffer_swap)); // Check if buffer had enough time to load image if(max_time > time_since_buffer_swap) return ret.AddError(LCR4500_PATTERN_SEQUENCE_BUFFERSWAP_TIME_ERROR); // Reset time counter time_since_buffer_swap = 0; // Increment Image index counter jImage++; } time_since_buffer_swap = time_since_buffer_swap + sequence_LUT.at(iPat).period; } } // Stop the sequence if something is already running if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); // Set power mode to normal if(DLPC350_SetPowerMode(PowerStandbyMode::NORMAL) < 0 ) return ret.AddError(LCR4500_SET_POWER_MODE_FAILED); // Change device to pattern sequence mode // Check the current mode bool mode_previous; if(DLPC350_GetMode(&mode_previous)<0) return ret.AddError(LCR4500_GET_OPERATING_MODE_FAILED); // The current mode is different from the requested setting change it if(mode_previous != OperatingMode::PATTERN_SEQUENCE){ if(DLPC350_SetMode(OperatingMode::PATTERN_SEQUENCE) < 0) return ret.AddError(LCR4500_SET_OPERATING_MODE_FAILED); } dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - get mode or set mode"); if(DLPC350_SetTrigOutConfig( LCR4500_TRIGGER_OUT_1, this->trigger_out_1_invert_.Get(), this->trigger_out_1_rising_.Get(), this->trigger_out_1_falling_.Get())< 0) return ret.AddError(LCR4500_SET_TRIGGER_OUTPUT_CONFIG_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - set trigger out config 1"); if(DLPC350_SetTrigOutConfig( LCR4500_TRIGGER_OUT_2, this->trigger_out_2_invert_.Get(), this->trigger_out_2_rising_.Get(), 0)< 0) return ret.AddError(LCR4500_SET_TRIGGER_OUTPUT_CONFIG_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - set trigger out config 2"); // Clear the LUT DLPC350_ClearExpLut(); // Hardcoded return value // Send the add the LUT entries for(unsigned int iEntry = 0; iEntry < sequence_LUT.size(); iEntry++ ){ if(DLPC350_AddToExpLut(sequence_LUT.at(iEntry).trigger_type, sequence_LUT.at(iEntry).pattern_number, sequence_LUT.at(iEntry).bit_depth, sequence_LUT.at(iEntry).LED_select, sequence_LUT.at(iEntry).invert_pattern, sequence_LUT.at(iEntry).insert_black, sequence_LUT.at(iEntry).buffer_swap, sequence_LUT.at(iEntry).trigger_out_share_prev, sequence_LUT.at(iEntry).exposure, sequence_LUT.at(iEntry).period)<0) return ret.AddError(LCR4500_ADD_EXP_LUT_ENTRY_FAILED); } // Currently only flash image source sequences are supported in this LCr4500 module // Set device to use flash images if(DLPC350_SetPatternDisplayMode(LCr4500::Pattern::Source::FLASH_IMAGES)<0) return ret.AddError(LCR4500_SET_PATTERN_DISPLAY_MODE_FAILED); // Get the pattern sequence display mode (play once or repeat) Parameters::PatternSequenceRepeat repeat_sequence; sequence_to_project.parameters.Get(&repeat_sequence); // Set the trigger mode this->debug_.Msg("Set pattern trigger mode..."); if(DLPC350_SetPatternTriggerMode(LCr4500::Pattern::TriggerMode::MODE_3_EXP_INT_OR_EXT)<0) return ret.AddError(LCR4500_SET_PATTERN_TRIGGER_MODE_FAILED); // Send the image LUT this->debug_.Msg("Sending image lookup table..."); if(DLPC350_SendVarExpImageLut( sequence_image_LUT.data(), sequence_image_LUT.size())<0) return ret.AddError(LCR4500_SEND_EXP_IMAGE_LUT_FAILED); // Send the pattern LUT this->debug_.Msg("Sending extended pattern lookup table..."); if(DLPC350_SendVarExpPatLut()<0) return ret.AddError(LCR4500_SEND_EXP_PATTERN_LUT_FAILED); // Setup the pattern sequence this->debug_.Msg("Configure pattern sequence..."); if(temp_pattern.color != dlp::Pattern::Color::RGB){ if(DLPC350_SetVarExpPatternConfig(sequence_LUT.size(), sequence_LUT.size(), sequence_image_LUT.size(), repeat_sequence.Get())<0) return ret.AddError(LCR4500_SET_VAR_EXP_PATTERN_CONFIG_FAILED); } else{ // Adjust the number of patterns to display because the green and blue // patterns share their trigger with the red. if(DLPC350_SetVarExpPatternConfig(sequence_LUT.size(), sequence_LUT.size()/3, sequence_image_LUT.size(), repeat_sequence.Get())<0) return ret.AddError(LCR4500_SET_VAR_EXP_PATTERN_CONFIG_FAILED); } // Validate the sequence if(DLPC350_StartPatLutValidate() < 0) return ret.AddError(LCR4500_PATTERN_SEQUENCE_VALIDATION_FAILED); dlp::Time::Sleep::Milliseconds(100); bool dlpc350_ready = false; while(!dlpc350_ready){ dlp::Time::Sleep::Milliseconds(10); if(DLPC350_CheckPatLutValidate(&dlpc350_ready,&sequence_validation) < 0) return ret.AddError(LCR4500_PATTERN_SEQUENCE_VALIDATION_FAILED); } // Display validation data if there was an error if( sequence_validation != 0 ){ this->debug_.Msg("Sequence validation FAILED!"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_FAILED); if((sequence_validation & BIT0) == BIT0){ this->debug_.Msg("- Exposure or frame period OUT OF RANGE"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_EXP_OR_PERIOD_OOO); } if((sequence_validation & BIT1) == BIT1){ this->debug_.Msg("- Pattern number in lookup table INVALID"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_PATTERN_NUMBER_INVALID); } if((sequence_validation & BIT2) == BIT2){ this->debug_.Msg("- Continued output trigger OVERLAPS black vector"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_OVERLAP_BLACK); } if((sequence_validation & BIT3) == BIT3){ this->debug_.Msg("- Black vector MISSING when exposure less than frame period"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_BLACK_MISSING); } if((sequence_validation & BIT4) == BIT4){ this->debug_.Msg("Difference between exposure and frame period less than 230us"); ret.AddError(LCR4500_SEQUENCE_VALIDATION_EXP_PERIOD_DELTA_INVALID); } return ret; } dlp::Time::Sleep::Milliseconds(10); this->debug_.Msg("Start pattern sequence..."); if( DLPC350_PatternDisplay(Pattern::DisplayControl::START) < 0) return ret.AddError(LCR4500_PATTERN_SEQUENCE_START_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - pattern display start"); return ret; } /** @brief Creates a sequence of patterns and firmware images for the LightCrafter 4500, * then uploads the new firmware * @param[in] arg_pattern_sequence object of \ref dlp::Pattern::Sequence type containing sequence * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_NOT_CONNECTED The LightCrafter 4500 EVM is NOT connected * @retval PATTERN_SEQUENCE_EMPTY The supplied sequence contains no patterns * @retval PATTERN_SEQUENCE_EXPOSURES_NOT_EQUAL The exposure times are NOT equal for each pattern in the sequence * @retval PATTERN_SEQUENCE_PERIODS_NOT_EQUAL The periods are NOT equal for each pattern in the sequence * @retval PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL The pattern types are NOT equal for each pattern in the sequence */ ReturnCode LCr4500::PreparePatternSequence(const dlp::Pattern::Sequence &pattern_sequence){ ReturnCode ret; unsigned int sequnce_count = pattern_sequence.GetCount(); dlp::Pattern::DataType sequence_type = dlp::Pattern::DataType::INVALID; // If A firmware upload is in progress, do NOT send any commands until upload is complete! return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that LCr4500 is connected if(!this->isConnected()){ // Device NOT connected return ret.AddError(LCR4500_NOT_CONNECTED); } // Check that the sequence has entries if(sequnce_count == 0) return ret.AddError(PATTERN_SEQUENCE_EMPTY); // Reset these values since pattern LUT will be updated this->previous_sequence_start_ = 0; this->previous_sequence_patterns_ = 0; this->previous_sequence_repeat_ = false; // Check that all pattern types are equal if(!pattern_sequence.EqualDataTypes()) return ret.AddError(PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL); // Get the sequence type from the first pattern dlp::Pattern temp_pattern; ret = pattern_sequence.Get(0,&temp_pattern); sequence_type = temp_pattern.data_type; // Create the new pattern sequence that the LCr4500 can use std::vector<std::string> lcr4500_firmware_image_list; switch(sequence_type){ case dlp::Pattern::DataType::INVALID: return ret.AddError(PATTERN_DATA_TYPE_INVALID); case dlp::Pattern::DataType::IMAGE_DATA: case dlp::Pattern::DataType::IMAGE_FILE: { // Need to make a new pattern sequence of parameters type // Create new firmware images and sequence std::string firmware_image_file_base = this->pattern_sequence_firmware_.Get() + ".flash_image_"; ret = this->CreateFirmwareImages( pattern_sequence, firmware_image_file_base, this->pattern_sequence_, lcr4500_firmware_image_list); if(ret.hasErrors()) return ret; // Upload the firmware if(!this->sequence_prepared_.Get()){ this->pattern_sequence_prepared_ = false; // Create firmware ret = this->CreateFirmware(this->pattern_sequence_firmware_.Get(),lcr4500_firmware_image_list); if(ret.hasErrors()) return ret; // Upload the firmware ret = this->UploadFirmware(this->pattern_sequence_firmware_.Get()); if(ret.hasErrors()) return ret; // Set flag that firmware has been uploaded this->sequence_prepared_.Set(true); } // Stop the display if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError(LCR4500_GET_STATUS_FAILED); // Change device to pattern sequence mode if(DLPC350_SetPowerMode(PowerStandbyMode::NORMAL)<0) return ret.AddError(LCR4500_SET_POWER_MODE_FAILED); if(DLPC350_SetMode(OperatingMode::PATTERN_SEQUENCE)<0) return ret.AddError(LCR4500_SET_OPERATING_MODE_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError(LCR4500_GET_STATUS_FAILED); break; } case dlp::Pattern::DataType::PARAMETERS: this->pattern_sequence_.Clear(); this->pattern_sequence_.Add(pattern_sequence); break; } this->pattern_sequence_prepared_ = true; return ret; } /** @brief Displays a previously prepared pattern sequence * @param[in] repeat If true, the sequence repeats after completing * @warning Must call \ref LCr4500::PreparePatternSequence() before using this method * @retval LCR4500_PATTERN_SEQUENCE_NOT_PREPARED The pattern sequence has NOT been prepared and sent to the LightCrafter 4500 * @retval LCR4500_IN_CALIBRATION_MODE The LightCrafter 4500 is in calibration mode and the sequence cannot be started */ ReturnCode LCr4500::StartPatternSequence(const unsigned int &start, const unsigned int &patterns, const bool &repeat){ ReturnCode ret; // Check that sequence has been prepared and that it is NOT a calibration sequence if(!this->pattern_sequence_prepared_ ) return ret.AddError(LCR4500_PATTERN_SEQUENCE_NOT_PREPARED); // Check that sequence is NOT too long if(patterns > LCr4500::PATTERN_LUT_SIZE) return ret.AddError(PATTERN_SEQUENCE_TOO_LONG); // Check that the indices are NOT out of range if((start + patterns) > this->pattern_sequence_.GetCount()) return ret.AddError(PATTERN_SEQUENCE_INDEX_OUT_OF_RANGE); if((start != this->previous_sequence_start_) || (patterns != this->previous_sequence_patterns_) || (repeat != this->previous_sequence_repeat_)){ // Create the sequence dlp::Pattern::Sequence sequence; for(unsigned int iPat = start; iPat < start+patterns; iPat++){ dlp::Pattern temp; // Get the pattern this->pattern_sequence_.Get(iPat,&temp); // Add it to new sequence sequence.Add(temp); } // Add repeat requence command if needed sequence.parameters.Set(Parameters::PatternSequenceRepeat(repeat)); // Load and start the sequence ret = this->CreateSendStartSequenceLut(sequence); this->previous_sequence_start_ = start; this->previous_sequence_patterns_ = patterns; this->previous_sequence_repeat_ = repeat; } else{ this->debug_.Msg("Start pattern sequence..."); if( DLPC350_PatternDisplay(Pattern::DisplayControl::START) < 0) return ret.AddError(LCR4500_PATTERN_SEQUENCE_START_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError("LCR4500_GET_STATUS_FAILED - pattern display start"); } return ret; } /** @brief Displays a specific pattern in a previously prepared sequence * @warning Must call \ref LCr4500::PreparePatternSequence() before using this method * @param[in] pattern_index index for the pattern to be displayed * @param[in] repeat bool value, if true, repeat the display of the pattern * * @retval LCR4500_PATTERN_SEQUENCE_NOT_PREPARED The pattern sequence has NOT been prepared and sent to the LightCrafter 4500 * @retval PATTERN_SEQUENCE_INDEX_OUT_OF_RANGE The pattern index number is NOT valid */ ReturnCode LCr4500::DisplayPatternInSequence(const unsigned int &pattern_index, const bool &repeat){ return this->StartPatternSequence(pattern_index,1,repeat); // ReturnCode ret; // // Check that sequence has been prepared // if(!this->pattern_sequence_prepared_) // return ret.AddError(LCR4500_PATTERN_SEQUENCE_NOT_PREPARED); // // Check that pattern is in range // if(pattern_index >= this->pattern_sequence_.GetCount()) // return ret.AddError(PATTERN_SEQUENCE_INDEX_OUT_OF_RANGE); // // Load only next pattern // dlp::Pattern next_pattern; // // Clear the parameters // next_pattern.parameters.Clear(); // ret = this->pattern_sequence_.Get( pattern_index, &next_pattern); // // Check for error // if(ret.hasErrors()) return ret; // // Load the first pattern as a sequence // dlp::Pattern::Sequence single_pattern_sequence; // single_pattern_sequence.Clear(); // single_pattern_sequence.Add(next_pattern); // // Add repeat requence command if needed // single_pattern_sequence.parameters.Set(Parameters::PatternSequenceRepeat(repeat)); // // Create and Send the LCr4500 LUT's // ret = this->CreateSendStartSequenceLut(single_pattern_sequence); // return ret; } /** @brief Stops the current display of a pattern sequence * @retval LCR4500_NOT_CONNECTED The LightCrafter 4500 EVM is NOT connected */ ReturnCode LCr4500::StopPatternSequence(){ ReturnCode ret; // Check that LCr4500 is connected if(!this->isConnected()){ // Device NOT connected return ret.AddError(LCR4500_NOT_CONNECTED); } // Stop the display if(DLPC350_PatternDisplay(Pattern::DisplayControl::STOP) < 0) return ret.AddError(LCR4500_PATTERN_DISPLAY_FAILED); dlp::Time::Sleep::Milliseconds(10); if(DLPC350_GetStatus(&this->status_hw_,&this->status_sys_,&this->status_main_)<0) return ret.AddError(LCR4500_GET_STATUS_FAILED); return ret; } /** @brief Determines which LightCrafter 4500 LED configuration to use * based on the supplied pattern color setting * @param[in] color color setting in a \ref dlp::Pattern object * * @retval LCR4500_COMMAND_FAILED Could NOT find a valid LED for the color */ int LCr4500::DlpPatternColorToLCr4500Led(const dlp::Pattern::Color &color){ switch(color){ case dlp::Pattern::Color::RED: return dlp::LCr4500::Pattern::Led::RED; case dlp::Pattern::Color::GREEN: return dlp::LCr4500::Pattern::Led::GREEN; case dlp::Pattern::Color::BLUE: return dlp::LCr4500::Pattern::Led::BLUE; case dlp::Pattern::Color::CYAN: return dlp::LCr4500::Pattern::Led::CYAN; case dlp::Pattern::Color::YELLOW: return dlp::LCr4500::Pattern::Led::YELLOW; case dlp::Pattern::Color::MAGENTA: return dlp::LCr4500::Pattern::Led::MAGENTA; case dlp::Pattern::Color::WHITE: return dlp::LCr4500::Pattern::Led::WHITE; case dlp::Pattern::Color::NONE: return dlp::LCr4500::Pattern::Led::NONE; case dlp::Pattern::Color::BLACK: return dlp::LCr4500::Pattern::Led::NONE; case dlp::Pattern::Color::RGB: return dlp::LCr4500::Pattern::Led::NONE; case dlp::Pattern::Color::INVALID: return dlp::LCr4500::Pattern::Led::NONE; } return LCR4500_COMMAND_FAILED; } /** @brief Determines which LightCrafter 4500 bit depth to use based on * the supplied pattern bit depth setting * @param[in] depth bit depth setting in a \ref dlp::Pattern object * * @retval LCR4500_COMMAND_FAILED Could NOT find a valid bit depth for the pattern */ int LCr4500::DlpPatternBitdepthToLCr4500Bitdepth(const dlp::Pattern::Bitdepth &depth){ switch(depth){ case dlp::Pattern::Bitdepth::INVALID: return 0; case dlp::Pattern::Bitdepth::MONO_1BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_1BPP; case dlp::Pattern::Bitdepth::MONO_2BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_2BPP; case dlp::Pattern::Bitdepth::MONO_3BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_3BPP; case dlp::Pattern::Bitdepth::MONO_4BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_4BPP; case dlp::Pattern::Bitdepth::MONO_5BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_5BPP; case dlp::Pattern::Bitdepth::MONO_6BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_6BPP; case dlp::Pattern::Bitdepth::MONO_7BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_7BPP; case dlp::Pattern::Bitdepth::MONO_8BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_8BPP; case dlp::Pattern::Bitdepth::RGB_3BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_1BPP; case dlp::Pattern::Bitdepth::RGB_6BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_2BPP; case dlp::Pattern::Bitdepth::RGB_9BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_3BPP; case dlp::Pattern::Bitdepth::RGB_12BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_4BPP; case dlp::Pattern::Bitdepth::RGB_15BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_5BPP; case dlp::Pattern::Bitdepth::RGB_18BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_6BPP; case dlp::Pattern::Bitdepth::RGB_21BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_7BPP; case dlp::Pattern::Bitdepth::RGB_24BPP: return dlp::LCr4500::Pattern::Bitdepth::MONO_8BPP; } return LCR4500_COMMAND_FAILED; } /** @brief Uploads firmware file to LightCrafter 4500 EVM * @param[in] firmware_filename Input file path * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_FIRMWARE_FILE_NOT_FOUND Could NOT find firmware file * @retval LCR4500_FIRMWARE_FLASH_PARAMETERS_FILE_NOT_FOUND LightCrafter 4500 flash device parameters file does NOT exist * @retval LCR4500_NOT_CONNECTED The LightCrafter 4500 EVM is NOT connected * @retval LCR4500_UNABLE_TO_ENTER_PROGRAMMING_MODE The LightCrafter 4500 was NOT able to enter programming mode * @retval LCR4500_GET_FLASH_MANUFACTURER_ID_FAILED The flash manufacturer ID could NOT be read * @retval LCR4500_GET_FLASH_DEVICE_ID_FAILED The flash device ID could NOT be read * @retval LCR4500_FLASHDEVICE_PARAMETERS_NOT_FOUND The flash parameters are NOT valid * @retval LCR4500_COMMAND_FAILED The LightCrafter 4500 command failed * @retval LCR4500_FIRMWARE_FLASH_ERASE_FAILED The firmware on the LightCrafter 4500 could NOT be erased * @retval LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED Memory could NOT be allocated on the LightCrafter 4500 * @retval LCR4500_FIRMWARE_UPLOAD_FAILED The firmware upload failed * @retval LCR4500_FIRMWARE_CHECKSUM_VERIFICATION_FAILED The firmware checksum could NOT be verified * @retval LCR4500_FIRMWARE_CHECKSUM_MISMATCH The uploaded firmware's checksum does NOT match the firmware on the LightCrafter 4500 */ ReturnCode LCr4500::UploadFirmware(std::string firmware_filename){ ReturnCode ret; std::string flash_parameters_filename = this->dlpc350_flash_parameters_.Get(); // If A firmware upload is in progress, do NOT send any commands until upload is complete! already return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot upload firmware because upload already in progress"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } else{ // Set the firmware uploading flag since upload has NOT started yet while(this->firmware_upload_in_progress.test_and_set()){}; } this->pattern_sequence_prepared_ = false; this->firmware_upload_restart_needed = false; // Check that the firmware file exists this->debug_.Msg("Checking that firmware file " + firmware_filename +" exists..."); if(!dlp::File::Exists(firmware_filename)){ this->debug_.Msg("Firmware file " + firmware_filename + " NOT found"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_FILE_NOT_FOUND); } this->firmwarePath = firmware_filename; // Check that the flash parameters file exists this->debug_.Msg("Checking that flash parameters file "+ flash_parameters_filename +" exists..."); if(!dlp::File::Exists(flash_parameters_filename)){ this->debug_.Msg("Flash parameters file " + flash_parameters_filename + " NOT found"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_FLASH_PARAMETERS_FILE_NOT_FOUND); } // Note the firmware upload process has begun this->firmware_upload_percent_erased_ = 0; this->firmware_upload_percent_complete_ = 0; unsigned short manID = 0; unsigned long long devID = 0; int startSector = 0; int i; int BLsize = 0; int lastSectorToErase; unsigned char *pByteArray=NULL; long long dataLen = 0; long long dataLen_full = 0; int bytesSent; unsigned int expectedChecksum = 0; unsigned int checksum = 0; bool skip_bootloader = true; // Check that LCr4500 is connected this->debug_.Msg("Checking that device is connected..."); if(!this->isConnected()){ // isConnected() contains debug messages this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_NOT_CONNECTED); } // Enter programming mode this->debug_.Msg("Putting device in programming mode..."); if(DLPC350_EnterProgrammingMode() < 0){ this->debug_.Msg("Device did NOT enter programming mode"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_UNABLE_TO_ENTER_PROGRAMMING_MODE); } // Wait for 5 seconds this->firmware_upload_restart_needed = true; this->debug_.Msg("Waiting for 5 seconds..."); dlp::Time::Sleep::Milliseconds(5000); // Disconnect the projector this->debug_.Msg("Disconnecting device..."); this->Disconnect(); this->debug_.Msg("Device disconnected"); this->debug_.Msg("Waiting for 5 seconds..."); dlp::Time::Sleep::Milliseconds(5000); // Reconnect the projector this->debug_.Msg("Connecting to device..."); std::string id; this->GetID(&id); this->Connect(id); if(!this->isConnected()){ // isConnected() contains debug messages this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_NOT_CONNECTED); } this->debug_.Msg("Connected"); this->debug_.Msg("Waiting for 5 seconds..."); dlp::Time::Sleep::Milliseconds(5000); this->firmware_upload_restart_needed = false; // Enter programming mode this->debug_.Msg("Putting device in programming mode..."); if(DLPC350_EnterProgrammingMode() < 0){ this->debug_.Msg("Device did NOT enter programming mode"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_UNABLE_TO_ENTER_PROGRAMMING_MODE); } // Get the connected LCr4500 flashdevice information this->debug_.Msg("Retrieving flash manufacturer and device IDs from connected device..."); if((DLPC350_GetFlashManID(&manID) < 0)){ this->debug_.Msg("Retrieving flash manufacturer ID FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_GET_FLASH_MANUFACTURER_ID_FAILED); } if((DLPC350_GetFlashDevID(&devID) < 0)){ this->debug_.Msg("Retrieving flash device ID FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_GET_FLASH_DEVICE_ID_FAILED); } // Save flash device information to this LCr4500 object devID &= 0xFFFF; this->myFlashDevice.Mfg_ID = manID; this->myFlashDevice.Dev_ID = devID; std::ifstream flash_param_file(flash_parameters_filename); std::string flash_param_file_line; // Read in file line by line this->debug_.Msg("Searching for flash device parameters in " + flash_parameters_filename + "..."); bool flashdevice_found = false; while(std::getline(flash_param_file,flash_param_file_line) && flashdevice_found == false) { this->debug_.Msg("..."); flashdevice_found = this->ProcessFlashParamsLine(flash_param_file_line); } flash_param_file.close(); // If the flash device was NOT found in the file return error if(flashdevice_found == false){ this->debug_.Msg("Flash device parameters NOT found"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FLASHDEVICE_PARAMETERS_NOT_FOUND); } this->debug_.Msg("Flash device parameters found"); this->debug_.Msg("Waiting 1 second..."); dlp::Time::Sleep::Milliseconds(1000); if(skip_bootloader) { BLsize = 128 * 1024; dataLen -= BLsize; } // Get the flash device memory address sectors needed for programming this->debug_.Msg("Determining amount of memory needed for firmware file..."); startSector = GetSectorNum(BLsize); lastSectorToErase = GetSectorNum(dlp::File::GetSize(firmware_filename)); //If perfectly aligned with last sector start addr, no need to erase last sector. if(dlp::File::GetSize(firmware_filename) == this->myFlashDevice.SectorArr[lastSectorToErase]){ lastSectorToErase -= 1; } // Set the flashdevice type on connected LCr4500 DLPC350_SetFlashType(this->myFlashDevice.Type); // Erase the flash sectors on connected LCr4500 this->debug_.Msg("Erasing flash sectors " + Number::ToString(startSector) + " to " + Number::ToString(lastSectorToErase) + "..."); for(int iSector=startSector; iSector <= lastSectorToErase; iSector++) { // Set the flash sector to be erased and erase it DLPC350_SetFlashAddr(this->myFlashDevice.SectorArr[iSector]); if(DLPC350_FlashSectorErase() < 0){ this->debug_.Msg("Flash sector " + Number::ToString(iSector) + " FAILED to erase"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_FLASH_ERASE_FAILED); } // Wait for the erase command to complete DLPC350_WaitForFlashReady(); this->firmware_upload_percent_erased_ = iSector*100/lastSectorToErase; this->debug_.Msg("Flash erase " + Number::ToString(this->GetFirmwareFlashEraseComplete()) + "% complete"); } this->firmware_upload_percent_erased_ = 100; this->debug_.Msg("Erasing flash sectors complete"); // Allocate memory to load the firmware image this->debug_.Msg("Allocating memory for firmware image..."); dataLen = dlp::File::GetSize(firmware_filename); pByteArray = new (std::nothrow) unsigned char [dataLen]; if (pByteArray == nullptr){ this->debug_.Msg("Allocating memory for firmware image FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED); } // Read the firmware iamge into memory this->debug_.Msg("Loading firmware image " + firmware_filename + " into memory..."); std::ifstream firmware(firmware_filename, std::ifstream::binary); firmware.read((char *)pByteArray, dataLen); firmware.close(); // Upload the firmware into the EVM DLPC350_SetFlashAddr(BLsize); dataLen -= BLsize; DLPC350_SetUploadSize(dataLen); dataLen_full = dataLen; this->debug_.Msg("Starting to upload firmware to device..."); while(dataLen > 0) { bytesSent = DLPC350_UploadData(pByteArray+BLsize+dataLen_full-dataLen, dataLen); if(bytesSent < 0) { delete[] pByteArray; this->debug_.Msg("Firmware upload FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_UPLOAD_FAILED); } for(i=0; i<bytesSent; i++) { expectedChecksum += pByteArray[BLsize+dataLen_full-dataLen+i]; } dataLen -= bytesSent; if(this->firmware_upload_percent_complete_ != (((dataLen_full-dataLen)*100)/dataLen_full)) { this->firmware_upload_percent_complete_ = (((dataLen_full-dataLen)*100)/dataLen_full); this->debug_.Msg("Uploading firmware image " + Number::ToString(this->GetFirmwareUploadPercentComplete()) + "% complete"); } } this->debug_.Msg("Verifying checksum..."); if(DLPC350_CalculateFlashChecksum() < 0){ this->debug_.Msg("Checksum verification FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_CHECKSUM_VERIFICATION_FAILED); } this->debug_.Msg("Device calculating checksum..."); DLPC350_WaitForFlashReady(); if(DLPC350_GetFlashChecksum(&checksum) < 0){ this->debug_.Msg("Checksum verification FAILED"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_CHECKSUM_VERIFICATION_FAILED); } else if(checksum != expectedChecksum) { this->debug_.Msg("Checksum mismatch"); this->debug_.Msg("Expected = " + Number::ToString(expectedChecksum)); this->debug_.Msg("Received = " + Number::ToString(checksum)); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_FIRMWARE_CHECKSUM_MISMATCH); } else { this->debug_.Msg("Exiting programming mode..."); DLPC350_ExitProgrammingMode(); //Exit programming mode; Start application. } delete[] pByteArray; this->debug_.Msg("Device rebooting..."); this->debug_.Msg("Waiting 5 seconds..."); this->firmware_upload_restart_needed = true; dlp::Time::Sleep::Milliseconds(5000); // Disconnect the projector this->debug_.Msg("Disconnecting device..."); this->Disconnect(); this->debug_.Msg("Waiting 5 seconds..."); dlp::Time::Sleep::Milliseconds(5000); // Reconnect the projector this->debug_.Msg("Connecting to device..."); this->GetID(&id); this->Connect(id); if(!this->isConnected()){ // isConnected() contains debug messages this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret.AddError(LCR4500_NOT_CONNECTED); } this->debug_.Msg("Connected"); this->debug_.Msg("Firmware upload complete"); this->firmware_upload_in_progress.clear(); this->firmware_upload_restart_needed = false; return ret; } /** @brief Returns true if a firmware upload is in progress */ bool LCr4500::FirmwareUploadInProgress(){ if(!this->firmware_upload_in_progress.test_and_set()){ // Firmware is NOT uploading, clear flag since the above // methods sets it this->firmware_upload_in_progress.clear(); return false; } else{ // Firmware upload is in progress return true; } } /** @brief Returns the firmware upload completion in percent */ long long LCr4500::GetFirmwareUploadPercentComplete(){ return this->firmware_upload_percent_complete_; } /** @brief Returns the firmware flash erase completion in percent */ long long LCr4500::GetFirmwareFlashEraseComplete(){ return this->firmware_upload_percent_erased_; } /** @brief Gets flash memory device parameters from flash parameter file. * Returns false if parameters are NOT found or flash device has too few sectors * @param[in] line input line for read in from file */ bool LCr4500::ProcessFlashParamsLine(const std::string &line) { unsigned int MfgID; unsigned int DevID; std::vector<std::string> separated_parameters; std::string param_line = line; // Check that the line is NOT empty if(param_line.empty()) return false; // Remove leading and trailing whitespace param_line = dlp::String::Trim(line); // Check that the line does NOT begin with / if(param_line.front() == '/') return false; // Separate the CSV values separated_parameters = dlp::String::SeparateDelimited(param_line,','); // Check that there are at least 9 flash device parameters // Mfg MfgID Device DevID Mb Alg Size #sec Sector_Addresses if(separated_parameters.size() <= 9) return false; // Read in the HEX manufacturer ID and device ID MfgID = dlp::String::ToNumber<unsigned int>(separated_parameters.at(1),16); DevID = dlp::String::ToNumber<unsigned int>(separated_parameters.at(3),16); // Check is these values match the device currently connected if((MfgID == this->myFlashDevice.Mfg_ID) && (DevID == this->myFlashDevice.Dev_ID)) { this->myFlashDevice.Mfg = separated_parameters.at(0); this->myFlashDevice.Dev = separated_parameters.at(2); this->myFlashDevice.Size_MBit = dlp::String::ToNumber<unsigned int>(separated_parameters.at(4)); this->myFlashDevice.Type = dlp::String::ToNumber<unsigned char>(separated_parameters.at(5)); this->myFlashDevice.numSectors = dlp::String::ToNumber<unsigned int>(separated_parameters.at(7)); // Check that flash device has number of sectors if(separated_parameters.size() < (8 + this->myFlashDevice.numSectors)) return false; for(unsigned int iSector = 0; iSector < this->myFlashDevice.numSectors; iSector++) { this->myFlashDevice.SectorArr[iSector] = dlp::String::ToNumber<unsigned int>(separated_parameters.at(8 + iSector),16); } return true; } return false; } /** @brief Gets flash sector number for a memory address * @param[in] addr Memory address location for which the sector number is required */ int LCr4500::GetSectorNum(unsigned int Addr) { unsigned int i; for(i=0; i < this->myFlashDevice.numSectors; i++) { if(this->myFlashDevice.SectorArr[i] > Addr) break; } return i-1; } /** @brief Creates a firmware file for LightCrafter 4500 EVM * @param[in] new_firmware_filename file name desired for the created firmware file * @param[in] image_filenames a vector of strings with all images to be included in firmware file * * @retval LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS A firmware upload is in progress, do NOT send any commands until upload is complete! * @retval LCR4500_DLPC350_FIRMWARE_FILE_NOT_FOUND Could NOT find blank DLPRR350 firmware file * @retval LCR4500_FIRMWARE_FILE_NAME_INVALID The desired firmware file name is NOT a valid file name * @retval LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED Could NOT allocate memory for the firmware file * @retval LCR4500_FIRMWARE_FILE_INVALID The firmware created is invalid * @retval LCR4500_IMAGE_FILE_FORMAT_INVALID The file formats of the images in the input vector are invalid */ ReturnCode LCr4500::CreateFirmware(const std::string &new_firmware_filename, const std::vector<std::string> &image_filenames){ ReturnCode ret; int i = 0; int frwm_ret = 0; int count = 0; long long dataLen; unsigned char *pByteArray; unsigned char *newFrmwImage; unsigned int newFrmwSize; unsigned char compression; unsigned int compSize; // If A firmware upload is in progress return error if(this->FirmwareUploadInProgress()){ this->debug_.Msg("Cannot connect because firmware is uploading"); return ret.AddError(LCR4500_FIRMWARE_UPLOAD_IN_PROGRESS); } // Check that original DLPC350 firmware file exists if(!dlp::File::Exists(this->dlpc350_firmware_.Get())) { this->debug_.Msg( "ERROR: Ensure DLPC350 firmware is installed; download link http://www.ti.com/tool/dlpr350"); this->debug_.Msg( "ERROR: Once installed provide firmware binary location through LCR4500_PARAMETERS_DLPC350_FIRMWARE parameter under projector configuration"); return ret.AddError(LCR4500_DLPC350_FIRMWARE_FILE_NOT_FOUND); } // Check that new firmware file name is NOT empty if(new_firmware_filename.empty()) return ret.AddError(LCR4500_FIRMWARE_FILE_NAME_INVALID); // Load the original DLPC350 firmware file into the firmware api dataLen = dlp::File::GetSize(this->dlpc350_firmware_.Get()); pByteArray = new (std::nothrow) unsigned char [dataLen]; if (pByteArray == nullptr) return ret.AddError(LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED); // Read the firmware into memory std::ifstream firmware_orig(this->dlpc350_firmware_.Get(), std::ifstream::binary); firmware_orig.read((char *)pByteArray, dataLen); firmware_orig.close(); // Read the firmware into firmware api frwm_ret = DLPC350_Frmw_CopyAndVerifyImage(pByteArray, dataLen); if (frwm_ret) { switch(frwm_ret) { case ERROR_FRMW_FLASH_TABLE_SIGN_MISMATCH: this->debug_.Msg( "ERROR: Flash Table Signature doesn't match! Bad Firmware Image!"); delete[] pByteArray; return ret.AddError(LCR4500_FIRMWARE_FILE_INVALID); case ERROR_NO_MEM_FOR_MALLOC: this->debug_.Msg( "Fatal Error! System Run out of memory"); delete[] pByteArray; return ret.AddError(LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED); default: break; } } delete[] pByteArray; // Check the firmware version //if ((DLPC350_Frmw_GetVersionNumber() & 0xFFFFFF) < RELEASE_FW_VERSION) // this->debug_.Msg( "WARNING: Old version of Firmware detected. Download the latest release from http://www.ti.com/tool/dlpr350."); firmwarePath = new_firmware_filename; // Initialize the firmware image buffer count = (int)image_filenames.size(); DLPC350_Frmw_SPLASH_InitBuffer(count); // Create a log file to document firmware build process std::fstream log_file_out; log_file_out.open("Frmw-build.log", std::fstream::out); // Start to build firmware log_file_out << "Building Images from specified BMPs\n\n"; for(i = 0; (i < MAX_SPLASH_IMAGES) && (i < count); i++) { // Check that the image file is the correct resolution // Also checks it the image doesn't exist if( !this->ImageResolutionCorrect(image_filenames.at(i)) ){ this->debug_.Msg("Did NOT add image " + dlp::Number::ToString(image_filenames.at(i)) + " to DLPC350 firmware"); continue; } //this->debug_.Msg( "Allocating memory for LightCrafter 4500 firmware image..."); dataLen = dlp::File::GetSize(image_filenames.at(i)); pByteArray = new (std::nothrow) unsigned char [dataLen]; if (pByteArray == nullptr) return ret.AddError(LCR4500_IMAGE_MEMORY_ALLOCATION_FAILED); // Read the image into memory std::ifstream firmware(image_filenames.at(i), std::ifstream::binary); firmware.read((char *)pByteArray, dataLen); firmware.close(); // Log the uncompressed image size log_file_out << image_filenames.at(i) << "\n"; log_file_out << "\t" << "Uncompressed Size = " << dataLen << " Compression type : "; // Determine if the filename specifies the compression type switch (this->dlpc350_image_compression_.Get()) { case dlp::LCr4500::ImageCompression::NONE: compression = SPLASH_UNCOMPRESSED; break; case dlp::LCr4500::ImageCompression::RLE: compression = SPLASH_RLE_COMPRESSION; break; case dlp::LCr4500::ImageCompression::FOUR_LINE: compression = SPLASH_4LINE_COMPRESSION; break; case dlp::LCr4500::ImageCompression::UNSPECIFIED: default: compression = SPLASH_NOCOMP_SPECIFIED; break; } // if (image_filenames.at(i).find("_nocomp.bmp") != std::string::npos){ // compression = SPLASH_UNCOMPRESSED; // } // else if (image_filenames.at(i).find("_rle.bmp") != std::string::npos){ // compression = SPLASH_RLE_COMPRESSION; // } // else if (image_filenames.at(i).find("_4line.bmp") != std::string::npos){ // compression = SPLASH_4LINE_COMPRESSION; // } // else{ // compression = SPLASH_NOCOMP_SPECIFIED; // } // compression = SPLASH_UNCOMPRESSED; // Add the image to the firmware frwm_ret = DLPC350_Frmw_SPLASH_AddSplash(pByteArray, &compression, &compSize); // Check if there was an error if (frwm_ret < 0) { switch(frwm_ret) { case ERROR_NOT_BMP_FILE: case ERROR_NOT_24bit_BMP_FILE: this->debug_.Msg( "Error building firmware - " + image_filenames.at(i) + " NOT in BMP format"); return ret.AddError(LCR4500_IMAGE_FILE_FORMAT_INVALID); case ERROR_NO_MEM_FOR_MALLOC: case ERROR_NO_SPACE_IN_FRMW: this->debug_.Msg( "Could not add " + image_filenames.at(i) + " - Insufficient memory"); return ret.AddError(LCR4500_FIRMWARE_NOT_ENOUGH_MEMORY); default: this->debug_.Msg( "Error building firmware with " + image_filenames.at(i) + " - Insufficient memory"); return ret.AddError(LCR4500_FIRMWARE_MEMORY_ALLOCATION_FAILED); } } this->debug_.Msg("Added image " + dlp::Number::ToString(image_filenames.at(i)) + " to DLPC350 firmware"); // Log the compression applied to image switch(compression) { case SPLASH_UNCOMPRESSED: log_file_out << "Uncompressed"; break; case SPLASH_RLE_COMPRESSION: log_file_out << "RLE Compression"; break; case SPLASH_4LINE_COMPRESSION: log_file_out << "4 Line Compression"; break; default: break; } // Log the compressed size of the image log_file_out << " Compressed Size = " << compSize << "\n\n"; delete[] pByteArray; } // Close the log file log_file_out.close(); // Get the new flash image data DLPC350_Frmw_Get_NewFlashImage(&newFrmwImage, &newFrmwSize); // Save the new flash image data to a file std::ofstream firmware(new_firmware_filename, std::ofstream::binary); firmware.write((char *)newFrmwImage, newFrmwSize); firmware.close(); return ret; } /** @brief Determines the amount of time required to load an image by loading it * a number of times and recording the longest time required * @param[in] index Flash image index to test load times * @param[in] load_count Number of times to load the image, should be greater than 5 * @param[out] max_microseconds Pointer to the maximum amount of time it took to load the image * * @retval LCR4500_NOT_CONNECTED The LightCrafter 4500 EVM is NOT connected * @retval LCR4500_MEASURE_FLASH_LOAD_TIMING_FAILED The image failed to load or the time failed to be measured * @retval LCR4500_GET_STATUS_FAILED Could NOT read the status of the LightCrafter 4500 * @retval LCR4500_READ_FLASH_LOAD_TIMING_FAILED The time for loading the image could NOT be read */ ReturnCode LCr4500::GetImageLoadTime(const unsigned int &index, const unsigned int &load_count, double *max_microseconds){ ReturnCode ret; // Check that LCr4500 is connected if(!this->isConnected()){ // Device NOT connected return ret.AddError(LCR4500_NOT_CONNECTED); } // Reset the return value (*max_microseconds) = 0; // Measure the average image load time for specified image for(unsigned int iLoad = 0; iLoad < load_count; iLoad++){ unsigned int temp_time; unsigned char HWStatus; unsigned char SysStatus; unsigned char MainStatus; // Tell the controller to measure the flash image load time if(DLPC350_MeasureImageLoadTiming( index, 1) < 0) return ret.AddError(LCR4500_MEASURE_FLASH_LOAD_TIMING_FAILED); // Sleep and Read the status bits to allow measurement time dlp::Time::Sleep::Milliseconds(100); if(DLPC350_GetStatus(&HWStatus, &SysStatus, &MainStatus) < 0) return ret.AddError(LCR4500_GET_STATUS_FAILED); // Read the load time if(DLPC350_ReadImageLoadTiming(&temp_time) < 0) return ret.AddError(LCR4500_READ_FLASH_LOAD_TIMING_FAILED); // Convert temp time to microseconds temp_time = 1000 * temp_time / 18667; // Save value if new time is longer if(temp_time > (*max_microseconds)) (*max_microseconds) = temp_time; } return ret; } /** @brief Creates images to be included in LightCrafter 4500 firmware from a sequence of patterns * @param[in] arg_pattern_sequence \ref dlp::Pattern::Sequence type to make firmware images from * @param[in] arg_image_filename_base Base image filename desired, index is appended to final images * @param[out] ret_pattern_sequence Pointer to return new \ref dlp::Pattern::Sequence * @param[out] ret_image_filename_list vector of strings containing file names of the created firmware images * * @retval DLP_PLATFORM_NOT_SETUP The LightCrafter 4500 object has NOT been properly set up * @retval LCR4500_FIRMWARE_IMAGE_BASENAME_EMPTY The desired firmware file name base is invalid * @retval PATTERN_SEQUENCE_EMPTY The sequence to create the images from is empty * @retval PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL The types for the patterns in the sequence do NOT match * @retval PATTERN_DATA_TYPE_INVALID The data type of the pattern in the sequence is NOT valid * @retval FILE_DOES_NOT_EXIST Image file pointed to by pattern does NOT exist */ ReturnCode LCr4500::CreateFirmwareImages(const dlp::Pattern::Sequence &arg_pattern_sequence, const std::string &arg_image_filename_base, dlp::Pattern::Sequence &ret_pattern_sequence, std::vector<std::string> &ret_image_filename_list ){ ReturnCode ret; std::string filename_temp; dlp::Pattern temp_pattern; unsigned int dmd_rows = 0; unsigned int dmd_cols = 0; // Check that DLP_Platform is setup if(!this->isPlatformSetup()) return ret.AddError(DLP_PLATFORM_NOT_SETUP); // Get DMD columns and rows this->GetColumns(&dmd_cols); this->GetRows(&dmd_rows); this->debug_.Msg("DMD resolution " + dlp::Number::ToString(dmd_cols) + " x " + dlp::Number::ToString(dmd_rows)); Image temp_firmware_image(dmd_cols,dmd_rows,Image::Format::MONO_INT); Image new_firmware_image( dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); unsigned char image_bit_position = 0; unsigned int flash_image_index = 0; unsigned char pattern_bpp = 0; unsigned char pattern_number = 0; PixelRGB pattern_pixel_rgb; unsigned char pattern_pixel = 0; unsigned char pixel_bitdepth_mask = 0; int temp_pixel = 0; int fw_pixel = 0; // Check that image filename base is NOT empty this->debug_.Msg("Check that the image filename base is NOT empty..."); if(arg_image_filename_base.empty()) return ret.AddError(LCR4500_FIRMWARE_IMAGE_BASENAME_EMPTY); this->debug_.Msg("Firmware image file basename is " + arg_image_filename_base); // Check that sequence is NOT empty this->debug_.Msg("Sequence contains " + dlp::Number::ToString(arg_pattern_sequence.GetCount()) + " patterns"); if(arg_pattern_sequence.GetCount() <= 0 ) return ret.AddError(PATTERN_SEQUENCE_EMPTY); // Check that sequence patterns all have same type if(!arg_pattern_sequence.EqualDataTypes()) return ret.AddError(PATTERN_SEQUENCE_PATTERN_TYPES_NOT_EQUAL); this->debug_.Msg("Sequence has equal pattern types"); // Get the first pattern arg_pattern_sequence.Get(0,&temp_pattern); // Check that sequence has images or image filenames if((temp_pattern.data_type != dlp::Pattern::DataType::IMAGE_DATA) && (temp_pattern.data_type != dlp::Pattern::DataType::IMAGE_FILE)) return ret.AddError(PATTERN_DATA_TYPE_INVALID); this->debug_.Msg("Pattern Type correct"); // Copy the pattern sequence dlp::Pattern::Sequence check_sequence; check_sequence.Add(arg_pattern_sequence); // Clean the return sequence this->debug_.Msg("Clearing return sequence and image file list"); ret_pattern_sequence.Clear(); ret_image_filename_list.clear(); // Set the image bitplane position to zero and zero the image image_bit_position = 0; temp_firmware_image.FillImage( (int)0); this->debug_.Msg("Set all pixels in temp firmware image to black"); // Create the new sequence and images for(unsigned int iPat = 0; iPat < check_sequence.GetCount(); iPat++){ dlp::Pattern grab_pattern; dlp::Image temp_pattern_image; temp_pattern_image.Clear(); // Get the current pattern from sequence this->debug_.Msg("Retrieving pattern " + dlp::Number::ToString(iPat)); check_sequence.Get(iPat,&grab_pattern); // Import the image data if(grab_pattern.data_type == dlp::Pattern::DataType::IMAGE_FILE){ this->debug_.Msg(1,"Pattern Type is image file"); // Check that file exists if(!dlp::File::Exists(grab_pattern.image_file)) return ret.AddError(FILE_DOES_NOT_EXIST); this->debug_.Msg(1,"Pattern image file exists"); // Load the image if the sequence has NOT been prepared // because the image data is already on the device and only // the sequence settings need to be determined if(!this->sequence_prepared_.Get()){ temp_pattern_image.Load(grab_pattern.image_file); } } else if(grab_pattern.data_type == dlp::Pattern::DataType::IMAGE_DATA){ this->debug_.Msg(1,"Pattern Type is image data"); // Perform shallow copy of the image data temp_pattern_image = grab_pattern.image_data; } // Copy all pattern settings this->debug_.Msg(1,"Copy pattern information"); temp_pattern.id = grab_pattern.id; temp_pattern.bitdepth = grab_pattern.bitdepth; temp_pattern.color = grab_pattern.color; temp_pattern.exposure = grab_pattern.exposure; temp_pattern.period = grab_pattern.period; temp_pattern.data_type = dlp::Pattern::DataType::PARAMETERS; temp_pattern.image_data.Clear(); temp_pattern.parameters.Clear(); // Check the image resolution if(!this->ImageResolutionCorrect(temp_pattern_image)) return ret.AddError(LCR4500_IMAGE_RESOLUTION_INVALID); // If the pattern does not contain a specific trigger source // use the one loaded during Setup() if(!temp_pattern.parameters.Contains(this->trigger_source_)){ temp_pattern.parameters.Set(this->trigger_source_); } // Determine which bitplane to save pattern image to pattern_bpp = (unsigned char)DlpPatternBitdepthToLCr4500Bitdepth(temp_pattern.bitdepth); this->debug_.Msg(1,"Pattern bpp = " + dlp::Number::ToString(pattern_bpp)); while(!this->StartPatternImageStorage(image_bit_position, pattern_bpp, pattern_number)){ // Increment image_bit_position counter to find correct // bitplane to start writing pattern image image_bit_position++; // If image_bit_position is greater than 23 the temp_firmware_image // hsould be converted to a RGB image and saved to a file. if(image_bit_position > 23){ // If image_bit_position is greater than 23 the temp_firmware_image // should be converted to a RGB image and saved to a file. // Save the image to a file if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ // Create the firmware image filename filename_temp = arg_image_filename_base + dlp::Number::ToString(flash_image_index) + ".bmp"; ret = this->SavePatternIntImageAsRGBfile(temp_firmware_image, filename_temp); if(ret.hasErrors()) return ret; // Add image filename to return image list vector ret_image_filename_list.push_back(filename_temp); /// BUG FIX: On Ubuntu, need to zero the matrices before releasing memory. new_firmware_image.FillImage(0); temp_firmware_image.FillImage(0); // Clear the images new_firmware_image.Clear(); temp_firmware_image.Clear(); // Reallocate the images temp_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::MONO_INT); new_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); } // Reset image_bit_position image_bit_position = 0; // Increment the flash image index flash_image_index++; } } this->debug_.Msg(1,"Bitplane position = " + dlp::Number::ToString(image_bit_position)); this->debug_.Msg(1,"Pattern number = " + dlp::Number::ToString(pattern_number)); this->debug_.Msg(1,"Flash image index = " + dlp::Number::ToString(flash_image_index)); // Check all previous patterns for identical image data bool new_image_data = true; for(unsigned int iImageCheck = 0; new_image_data && (iImageCheck < ret_pattern_sequence.GetCount());iImageCheck++){ dlp::Pattern image_check_pattern; ret_pattern_sequence.Get(iImageCheck,&image_check_pattern); new_image_data = !dlp::Image::Equal(temp_pattern_image, image_check_pattern.image_data); if(!new_image_data) temp_pattern.parameters = image_check_pattern.parameters; } // Add new image to composite image and create LUT parameters if(new_image_data){ // Determine if pattern is monochrome or RGB if(temp_pattern.color != dlp::Pattern::Color::RGB){ // Pattern is monochrome // If the stored image is RGB convert it to monochrome temp_pattern_image.ConvertToMonochrome(); temp_pattern.image_data = temp_pattern_image; // Shallow copy // Create mask according to pattern bitdepth pixel_bitdepth_mask = (1 << pattern_bpp) - 1; // Add the pattern image to the temp image if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ for( unsigned int yRow = 0; yRow < dmd_rows; yRow++){ for( unsigned int xCol = 0; xCol < dmd_cols; xCol++){ // Get the monochrome pixel from the pattern image temp_pattern_image.Unsafe_GetPixel(xCol,yRow,&pattern_pixel); // Mask the pixels according to the pattern bitdepth if(pattern_pixel > pixel_bitdepth_mask){ pattern_pixel = pixel_bitdepth_mask; } else{ pattern_pixel = pattern_pixel & pixel_bitdepth_mask; } // Convert the pattern image pixel to the FW image pixel temp_pixel = (int) pattern_pixel; // Shift the data to the correct starting bitplane temp_pixel = temp_pixel << image_bit_position; // Get the current fw pixel temp_firmware_image.Unsafe_GetPixel( xCol, yRow, &fw_pixel); // Update the fw pixel fw_pixel = temp_pixel + fw_pixel; // Set the uint pixel0 temp_firmware_image.Unsafe_SetPixel( xCol, yRow, fw_pixel); } } } this->debug_.Msg(1,"Setting pattern parameters"); // Add the flash image index and pattern number to the pattern parameters temp_pattern.parameters.Set(Parameters::PatternImageIndex(flash_image_index)); temp_pattern.parameters.Set(Parameters::PatternNumber(pattern_number)); // Increment the image bit position so this pattern image is NOT overwritten image_bit_position = image_bit_position + pattern_bpp; } else{ // Pattern is RGB // Check that image is RGB dlp::Image::Format temp_image_format; temp_pattern_image.GetDataFormat(&temp_image_format); if((temp_image_format != dlp::Image::Format::RGB_UCHAR) && (!this->sequence_prepared_.Get())) return ret.AddError(LCR4500_IMAGE_FORMAT_INVALID); // Add the red channel // Create mask according to pattern bitdepth pixel_bitdepth_mask = (1 << pattern_bpp) - 1; // Add the pattern image to the temp image if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ for( unsigned int yRow = 0; yRow < dmd_rows; yRow++){ for( unsigned int xCol = 0; xCol < dmd_cols; xCol++){ // Get the monochrome pixel from the pattern image temp_pattern_image.Unsafe_GetPixel(xCol,yRow,&pattern_pixel_rgb); // Mask the pixels according to the pattern bitdepth if(pattern_pixel_rgb.r > pixel_bitdepth_mask){ pattern_pixel_rgb.r = pixel_bitdepth_mask; } else{ pattern_pixel_rgb.r = pattern_pixel_rgb.r & pixel_bitdepth_mask; } // Convert the pattern image pixel to the FW image pixel temp_pixel = (int) pattern_pixel_rgb.r; // Shift the data to the correct starting bitplane temp_pixel = temp_pixel << image_bit_position; // Get the current fw pixel temp_firmware_image.Unsafe_GetPixel( xCol, yRow, &fw_pixel); // Update the fw pixel fw_pixel = temp_pixel + fw_pixel; // Set the uint pixel temp_firmware_image.Unsafe_SetPixel( xCol, yRow, fw_pixel); } } } this->debug_.Msg(1,"Setting pattern parameters"); // Add the flash image index and pattern number to the pattern parameters temp_pattern.parameters.Set(Parameters::PatternImageIndexRed(flash_image_index)); temp_pattern.parameters.Set(Parameters::PatternNumberRed(pattern_number)); // Increment the image bit position so this pattern image is NOT overwritten image_bit_position = image_bit_position + pattern_bpp; while(!this->StartPatternImageStorage(image_bit_position, pattern_bpp, pattern_number)){ // Increment image_bit_position counter to find correct // bitplane to start writing pattern image image_bit_position++; // If image_bit_position is greater than 23 the temp_firmware_image // hsould be converted to a RGB image and saved to a file. if(image_bit_position > 23){ // If image_bit_position is greater than 23 the temp_firmware_image // should be converted to a RGB image and saved to a file. // Save the image to a file if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ // Create the firmware image filename filename_temp = arg_image_filename_base + dlp::Number::ToString(flash_image_index) + ".bmp"; ret = this->SavePatternIntImageAsRGBfile(temp_firmware_image, filename_temp); if(ret.hasErrors()) return ret; // Add image filename to return image list vector ret_image_filename_list.push_back(filename_temp); // Clear the images new_firmware_image.Clear(); temp_firmware_image.Clear(); // Reallocate the images temp_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::MONO_INT); new_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); } // Reset image_bit_position image_bit_position = 0; // Increment the flash image index flash_image_index++; } } this->debug_.Msg(1,"Bitplane position = " + dlp::Number::ToString(image_bit_position)); this->debug_.Msg(1,"Pattern number = " + dlp::Number::ToString(pattern_number)); this->debug_.Msg(1,"Flash image index = " + dlp::Number::ToString(flash_image_index)); // Add the green channel // Add the pattern image to the temp image if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ for( unsigned int yRow = 0; yRow < dmd_rows; yRow++){ for( unsigned int xCol = 0; xCol < dmd_cols; xCol++){ // Get the monochrome pixel from the pattern image temp_pattern_image.Unsafe_GetPixel(xCol,yRow,&pattern_pixel_rgb); // Mask the pixels according to the pattern bitdepth if(pattern_pixel_rgb.g > pixel_bitdepth_mask){ pattern_pixel_rgb.g = pixel_bitdepth_mask; } else{ pattern_pixel_rgb.g = pattern_pixel_rgb.g & pixel_bitdepth_mask; } // Convert the pattern image pixel to the FW image pixel temp_pixel = (int) pattern_pixel_rgb.g; // Shift the data to the correct starting bitplane temp_pixel = temp_pixel << image_bit_position; // Get the current fw pixel temp_firmware_image.Unsafe_GetPixel( xCol, yRow, &fw_pixel); // Update the fw pixel fw_pixel = temp_pixel + fw_pixel; // Set the uint pixel temp_firmware_image.Unsafe_SetPixel( xCol, yRow, fw_pixel); } } } this->debug_.Msg(1,"Setting pattern parameters"); // Add the flash image index and pattern number to the pattern parameters temp_pattern.parameters.Set(Parameters::PatternImageIndexGreen(flash_image_index)); temp_pattern.parameters.Set(Parameters::PatternNumberGreen(pattern_number)); // Increment the image bit position so this pattern image is NOT overwritten image_bit_position = image_bit_position + pattern_bpp; while(!this->StartPatternImageStorage(image_bit_position, pattern_bpp, pattern_number)){ // Increment image_bit_position counter to find correct // bitplane to start writing pattern image image_bit_position++; // If image_bit_position is greater than 23 the temp_firmware_image // hsould be converted to a RGB image and saved to a file. if(image_bit_position > 23){ // If image_bit_position is greater than 23 the temp_firmware_image // should be converted to a RGB image and saved to a file. // Save the image to a file if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ // Create the firmware image filename filename_temp = arg_image_filename_base + dlp::Number::ToString(flash_image_index) + ".bmp"; ret = this->SavePatternIntImageAsRGBfile(temp_firmware_image, filename_temp); if(ret.hasErrors()) return ret; // Add image filename to return image list vector ret_image_filename_list.push_back(filename_temp); // Clear the images new_firmware_image.Clear(); temp_firmware_image.Clear(); // Reallocate the images temp_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::MONO_INT); new_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); } // Reset image_bit_position image_bit_position = 0; // Increment the flash image index flash_image_index++; } } this->debug_.Msg(1,"Bitplane position = " + dlp::Number::ToString(image_bit_position)); this->debug_.Msg(1,"Pattern number = " + dlp::Number::ToString(pattern_number)); this->debug_.Msg(1,"Flash image index = " + dlp::Number::ToString(flash_image_index)); // Add the blue channel // Add the pattern image to the temp image if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ for( unsigned int yRow = 0; yRow < dmd_rows; yRow++){ for( unsigned int xCol = 0; xCol < dmd_cols; xCol++){ // Get the monochrome pixel from the pattern image temp_pattern_image.Unsafe_GetPixel(xCol,yRow,&pattern_pixel_rgb); // Mask the pixels according to the pattern bitdepth if(pattern_pixel_rgb.b > pixel_bitdepth_mask){ pattern_pixel_rgb.b = pixel_bitdepth_mask; } else{ pattern_pixel_rgb.b = pattern_pixel_rgb.b & pixel_bitdepth_mask; } // Convert the pattern image pixel to the FW image pixel temp_pixel = (int) pattern_pixel_rgb.b; // Shift the data to the correct starting bitplane temp_pixel = temp_pixel << image_bit_position; // Get the current fw pixel temp_firmware_image.Unsafe_GetPixel( xCol, yRow, &fw_pixel); // Update the fw pixel fw_pixel = temp_pixel + fw_pixel; // Set the uint pixel temp_firmware_image.Unsafe_SetPixel( xCol, yRow, fw_pixel); } } } this->debug_.Msg(1,"Setting pattern parameters"); // Add the flash image index and pattern number to the pattern parameters temp_pattern.parameters.Set(Parameters::PatternImageIndexBlue(flash_image_index)); temp_pattern.parameters.Set(Parameters::PatternNumberBlue(pattern_number)); // Increment the image bit position so this pattern image is NOT overwritten image_bit_position = image_bit_position + pattern_bpp; while(!this->StartPatternImageStorage(image_bit_position, pattern_bpp, pattern_number)){ // Increment image_bit_position counter to find correct // bitplane to start writing pattern image image_bit_position++; // If image_bit_position is greater than 23 the temp_firmware_image // hsould be converted to a RGB image and saved to a file. if(image_bit_position > 23){ // If image_bit_position is greater than 23 the temp_firmware_image // should be converted to a RGB image and saved to a file. // Save the image to a file if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ // Create the firmware image filename filename_temp = arg_image_filename_base + dlp::Number::ToString(flash_image_index) + ".bmp"; ret = this->SavePatternIntImageAsRGBfile(temp_firmware_image, filename_temp); if(ret.hasErrors()) return ret; // Add image filename to return image list vector ret_image_filename_list.push_back(filename_temp); // Clear the images new_firmware_image.Clear(); temp_firmware_image.Clear(); // Reallocate the images temp_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::MONO_INT); new_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); } // Reset image_bit_position image_bit_position = 0; // Increment the flash image index flash_image_index++; } } } } this->debug_.Msg("Adding pattern to sequence"); ret_pattern_sequence.Add(temp_pattern); } // Save the image to a file if sequence has NOT been prepared if(!this->sequence_prepared_.Get()){ // Create the firmware image filename filename_temp = arg_image_filename_base + dlp::Number::ToString(flash_image_index) + ".bmp"; ret = this->SavePatternIntImageAsRGBfile(temp_firmware_image, filename_temp); if(ret.hasErrors()) return ret; // Add image filename to return image list vector ret_image_filename_list.push_back(filename_temp); // Clear the images new_firmware_image.Clear(); temp_firmware_image.Clear(); // Reallocate the images temp_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::MONO_INT); new_firmware_image.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); } // Copy over any parameters ret_pattern_sequence.parameters = check_sequence.parameters; return ret; } /** @brief Creates images to be included in LightCrafter 4500 firmware from a sequence of patterns * @param[in] bitplane_position The bit position the pattern will be stored in the image * @param[in] mono_bpp Bits to be stored in the image for each pixel * @param[out] ret_pattern_number Returns the LCr4500 flash image pattern number */ bool LCr4500::StartPatternImageStorage(const unsigned char &bitplane_position, const unsigned char &mono_bpp, unsigned char &ret_pattern_number){ bool ret = false; unsigned char BitplaneStorage[] = {1,2,3,4,6,6,8,8}; unsigned char BitplaneOffset[] = {0,0,0,0,1,0,1,0}; // There can only be 0-23 positions (RGB888 means 24 bitplanes available) if(bitplane_position > 23) return false; if((mono_bpp > 0) && (mono_bpp <= 8)){ ret = ((bitplane_position - BitplaneOffset[mono_bpp-1]) % BitplaneStorage[mono_bpp-1]) == 0; } // Calculate pattern number ret_pattern_number = (bitplane_position - BitplaneOffset[mono_bpp-1])/ BitplaneStorage[mono_bpp-1]; return ret; } /** @brief Creates images to be included in LightCrafter 4500 firmware from an INT image * @param[in] image_int object of \ref dlp::Image type containing pattern image * @param[in] filename file name to save image object * * @retval DLP_PLATFORM_NOT_SETUP The LightCrafter 4500 object has NOT been properly set up */ ReturnCode LCr4500::SavePatternIntImageAsRGBfile(Image &image_int, const std::string &filename){ ReturnCode ret; Image image_rgb; PixelRGB new_pixel; int pixel_int; unsigned int pixel; unsigned int dmd_rows; unsigned int dmd_cols; // Check that DLP_Platform has been setup if(!this->isPlatformSetup()) return ret.AddError(DLP_PLATFORM_NOT_SETUP); // Get DMD size this->GetColumns(&dmd_cols); this->GetRows(&dmd_rows); // Create the RGB image in memory ret = image_rgb.Create(dmd_cols,dmd_rows,Image::Format::RGB_UCHAR); if(ret.hasErrors()) return ret; // Fill the new RGB image with zeros new_pixel.r = 0; new_pixel.g = 0; new_pixel.b = 0; ret = image_rgb.FillImage(new_pixel); if(ret.hasErrors()) return ret; // Create the RGB image pixel by pixel for(unsigned int yRow = 0; yRow < dmd_rows; yRow++){ for(unsigned int xCol = 0; xCol < dmd_cols; xCol++){ // Get the int pixel image_int.Unsafe_GetPixel(xCol,yRow, &pixel_int); // Create the RGB pixel pixel = (unsigned int) pixel_int; new_pixel.r = (pixel >> 8) & 255; // Pattern Image bitplanes 8 - 15 new_pixel.g = (pixel >> 0) & 255; // Pattern Image bitplanes 0 - 7 new_pixel.b = (pixel >> 16) & 255; // Pattern Image bitplanes 16 - 23 // Set the pixel image_rgb.Unsafe_SetPixel(xCol,yRow,new_pixel); } } // Save the image to a file ret = image_rgb.Save(filename); return ret; } namespace String{ template <> dlp::LCr4500::ImageCompression ToNumber(const std::string &text, unsigned int base ){ // Ignore base variable (void)base; // Remove unused variable warning if (text.compare("NONE") == 0) return dlp::LCr4500::ImageCompression::NONE; if (text.compare("RLE") == 0) return dlp::LCr4500::ImageCompression::RLE; if (text.compare("FOUR_LINE") == 0) return dlp::LCr4500::ImageCompression::FOUR_LINE; return dlp::LCr4500::ImageCompression::UNSPECIFIED; } template <> dlp::LCr4500::PowerStandbyMode::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::PowerStandbyMode::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::ImageFlip::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::ImageFlip::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::InputSource::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::InputSource::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::ParallelPortWidth::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::ParallelPortWidth::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::ParallelClockPort::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::ParallelClockPort::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::DataSwap::SubChannels::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::DataSwap::SubChannels::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::DataSwap::Port::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::DataSwap::Port::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Video::TestPattern::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Video::TestPattern::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::OperatingMode::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::OperatingMode::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::InvertData::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::InvertData::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Source::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Source::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::TriggerMode::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::TriggerMode::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::TriggerSource::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::TriggerSource::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Led::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Led::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Bitdepth::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Bitdepth::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_1BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_1BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_2BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_2BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_3BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_3BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_4BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_4BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_5BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_5BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_6BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_6BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_7BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_7BPP::Enum)dlp::String::ToNumber<int>(text); } template <> dlp::LCr4500::Pattern::Number::Mono_8BPP::Enum ToNumber( const std::string &text, unsigned int base ){ (void)base; // Remove unused variable warning return (dlp::LCr4500::Pattern::Number::Mono_8BPP::Enum)dlp::String::ToNumber<int>(text); } } namespace Number{ template <> std::string ToString<dlp::LCr4500::ImageCompression>(dlp::LCr4500::ImageCompression value ){ switch(value){ case dlp::LCr4500::ImageCompression::NONE: return "NONE"; case dlp::LCr4500::ImageCompression::FOUR_LINE: return "FOUR_LINE"; case dlp::LCr4500::ImageCompression::RLE: return "RLE"; case dlp::LCr4500::ImageCompression::UNSPECIFIED: return "UNSPECIFIED"; } return "UNSPECIFIED"; } template <> std::string ToString<dlp::LCr4500::PowerStandbyMode::Enum>( dlp::LCr4500::PowerStandbyMode::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::ImageFlip::Enum>( dlp::LCr4500::ImageFlip::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::InputSource::Enum>( dlp::LCr4500::Video::InputSource::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::ParallelPortWidth::Enum>(LCr4500::Video::ParallelPortWidth::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::ParallelClockPort::Enum>( dlp::LCr4500::Video::ParallelClockPort::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::DataSwap::SubChannels::Enum>( dlp::LCr4500::Video::DataSwap::SubChannels::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::DataSwap::Port::Enum>( dlp::LCr4500::Video::DataSwap::Port::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Video::TestPattern::Enum>( dlp::LCr4500::Video::TestPattern::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::OperatingMode::Enum>( dlp::LCr4500::OperatingMode::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::InvertData::Enum>( dlp::LCr4500::InvertData::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Source::Enum>( dlp::LCr4500::Pattern::Source::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::TriggerMode::Enum>( dlp::LCr4500::Pattern::TriggerMode::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::TriggerSource::Enum>( dlp::LCr4500::Pattern::TriggerSource::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Led::Enum>( dlp::LCr4500::Pattern::Led::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Bitdepth::Enum>( dlp::LCr4500::Pattern::Bitdepth::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_1BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_1BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_2BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_2BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_3BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_3BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_4BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_4BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_5BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_5BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_6BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_6BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_7BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_7BPP::Enum value ){ return dlp::Number::ToString((int) value); } template <> std::string ToString<dlp::LCr4500::Pattern::Number::Mono_8BPP::Enum>( dlp::LCr4500::Pattern::Number::Mono_8BPP::Enum value ){ return dlp::Number::ToString((int) value); } } }
// Copyright John Maddock 2020. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Basic sanity check that header <boost/math/filters/daubechies.hpp> // #includes all the files that it needs to. // #include <boost/math/filters/daubechies.hpp> void compile_and_link_test() { using namespace boost::math::filters; constexpr std::array<float, 2> fa = daubechies_scaling_filter<float, 1>(); static_assert(fa[0] == 0.70710678118654752440084436210484903928483593768847403658833986899536623923f); static_assert(fa[1] == 0.70710678118654752440084436210484903928483593768847403658833986899536623923f); constexpr std::array<double, 4> da = daubechies_scaling_filter<double, 2>(); static_assert(da[0] == 0.48296291314453414337487159986444868381695241950420227520117153815521160699); static_assert(da[1] == 0.83651630373780790557529378091687320345937038834843929349534147265289472661); static_assert(da[2] == 0.22414386804201338102597276224040035546788351818427176138716833084015463224); static_assert(da[3] == -0.12940952255126038117444941881202416417453445065996525690700160365752848737); constexpr std::array<long double, 6> la = daubechies_scaling_filter<long double, 3>(); static_assert(la[0] == 0.33267055295008261599851158913900563001292339924506835970847057855179372371L); static_assert(la[1] == 0.80689150931109257649449360408871349051929739499482361816509206360348683533L); static_assert(la[2] == 0.45987750211849157009515194214761672080811017743149230664338678024864033563L); static_assert(la[3] == -0.135011020010254588696389906699374480562219845223781191975686255357062768L); static_assert(la[4] == -0.085441273882026661692819169181773311536197638988086629763517489805067820106L); static_assert(la[5] == 0.035226291885709536602740664715510029327758387917431610398934060748942171898L); }
// 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 "remoting/host/server_log_entry_host.h" #include <memory> #include "base/strings/stringize_macros.h" #include "build/build_config.h" #include "remoting/signaling/server_log_entry.h" #include "remoting/signaling/server_log_entry_unittest.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/webrtc/libjingle/xmllite/xmlelement.h" using buzz::XmlAttr; using buzz::XmlElement; namespace remoting { TEST(ServerLogEntryHostTest, MakeForSessionStateChange) { std::unique_ptr<ServerLogEntry> entry( MakeLogEntryForSessionStateChange(true)); std::unique_ptr<XmlElement> stanza = entry->ToStanza(); std::string error; std::map<std::string, std::string> key_value_pairs; key_value_pairs["role"] = "host"; key_value_pairs["event-name"] = "session-state"; key_value_pairs["session-state"] = "connected"; std::set<std::string> keys; ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) << error; } TEST(ServerLogEntryHostTest, MakeForHeartbeat) { std::unique_ptr<ServerLogEntry> entry(MakeLogEntryForHeartbeat()); std::unique_ptr<XmlElement> stanza = entry->ToStanza(); std::string error; std::map<std::string, std::string> key_value_pairs; key_value_pairs["role"] = "host"; key_value_pairs["event-name"] = "heartbeat"; std::set<std::string> keys; ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) << error; } TEST(ServerLogEntryHostTest, AddHostFields) { std::unique_ptr<ServerLogEntry> entry( MakeLogEntryForSessionStateChange(true)); AddHostFieldsToLogEntry(entry.get()); std::unique_ptr<XmlElement> stanza = entry->ToStanza(); std::string error; std::map<std::string, std::string> key_value_pairs; key_value_pairs["role"] = "host"; key_value_pairs["event-name"] = "session-state"; key_value_pairs["session-state"] = "connected"; std::set<std::string> keys; keys.insert("cpu"); #if defined(OS_WIN) key_value_pairs["os-name"] = "Windows"; keys.insert("os-version"); #elif defined(OS_MACOSX) key_value_pairs["os-name"] = "Mac"; keys.insert("os-version"); #elif defined(OS_CHROMEOS) key_value_pairs["os-name"] = "ChromeOS"; keys.insert("os-version"); #elif defined(OS_LINUX) key_value_pairs["os-name"] = "Linux"; keys.insert("os-version"); #endif // The check below will compile but fail if VERSION isn't defined (STRINGIZE // silently converts undefined values). #ifndef VERSION #error VERSION must be defined #endif key_value_pairs["host-version"] = STRINGIZE(VERSION); ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) << error; } TEST(ServerLogEntryHostTest, AddModeField1) { std::unique_ptr<ServerLogEntry> entry( MakeLogEntryForSessionStateChange(true)); entry->AddModeField(ServerLogEntry::IT2ME); std::unique_ptr<XmlElement> stanza = entry->ToStanza(); std::string error; std::map<std::string, std::string> key_value_pairs; key_value_pairs["role"] = "host"; key_value_pairs["event-name"] = "session-state"; key_value_pairs["session-state"] = "connected"; key_value_pairs["mode"] = "it2me"; std::set<std::string> keys; ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) << error; } TEST(ServerLogEntryHostTest, AddModeField2) { std::unique_ptr<ServerLogEntry> entry( MakeLogEntryForSessionStateChange(true)); entry->AddModeField(ServerLogEntry::ME2ME); std::unique_ptr<XmlElement> stanza = entry->ToStanza(); std::string error; std::map<std::string, std::string> key_value_pairs; key_value_pairs["role"] = "host"; key_value_pairs["event-name"] = "session-state"; key_value_pairs["session-state"] = "connected"; key_value_pairs["mode"] = "me2me"; std::set<std::string> keys; ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) << error; } } // namespace remoting
void Utils::sleep( const quint16 &t ) { QTime dieTime = QTime::currentTime().addMSecs(t); while( QTime::currentTime() < dieTime ) { QCoreApplication::processEvents( QEventLoop::AllEvents, 100 ); } } // usleep - suspend execution for microsecond intervals // #include <unistd.h> // int usleep(useconds_t usec); while(!mpLocalMapper->isStopped()) { usleep(1000); }
/* * Copyright 2018 The Polycube 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. */ // Modify these methods with your own implementation #include "Stats.h" #include "Ddosmitigator.h" using namespace polycube::service; Stats::Stats(Ddosmitigator &parent, const StatsJsonObject &conf) : parent_(parent) { logger()->info("Creating Stats instance"); } Stats::~Stats() {} void Stats::update(const StatsJsonObject &conf) { // This method updates all the object/parameter in Stats object specified in // the conf JsonObject. // You can modify this implementation. } StatsJsonObject Stats::toJsonObject() { StatsJsonObject conf; conf.setPps(getPps()); conf.setPkts(getPkts()); return conf; } void Stats::create(Ddosmitigator &parent, const StatsJsonObject &conf) { // throw std::runtime_error("[Stats]: Method create not supported"); } std::shared_ptr<Stats> Stats::getEntry(Ddosmitigator &parent) { // This method retrieves the pointer to Stats object specified by its keys. parent.logger()->debug("Stats getEntry"); StatsJsonObject sjo; return std::shared_ptr<Stats>(new Stats(parent, sjo)); } void Stats::removeEntry(Ddosmitigator &parent) { // This method removes the single Stats object specified by its keys. // Remember to call here the remove static method for all-sub-objects of // Stats. throw std::runtime_error( "[Stats]: Method removeEntry not supported. Read Only"); } uint64_t Stats::getPps() { // This method retrieves the pps value. int begin = getPkts(); sleep(1); int end = getPkts(); return end - begin; return 0; // throw std::runtime_error("[Stats]: Method getPps not implemented"); } uint64_t Stats::getPkts() { // This method retrieves the pkts value. uint64_t pkts = 0; auto dropcnt = parent_.get_percpuarray_table<uint64_t>("dropcnt"); auto values = dropcnt.get(0); pkts = std::accumulate(values.begin(), values.end(), pkts); logger()->debug("getting dropped packets..."); logger()->debug("got {0} pkts", pkts); return pkts; } std::shared_ptr<spdlog::logger> Stats::logger() { return parent_.logger(); }
#ifndef OPENCL_IMAGE2D_ARRAY_HPP #define OPENCL_IMAGE2D_ARRAY_HPP #ifdef OPENCL_2 #include <CL/cl2.hpp> #else #ifdef __APPLE__ #include <OpenCL/cl.hpp> #else #include <CL/cl.hpp> #endif #endif namespace nova { template <typename T> class Image2DArray { public: Image2DArray() = default; template <typename... Args> Image2DArray(Args&&... args) : image(std::forward<Args>(args)...) {} Image2DArray(const Image2DArray& other) : image(other.image) {} Image2DArray(Image2DArray& other) : image(other.image) {} Image2DArray& operator=(const Image2DArray& other) { image = other.image; return *this; } Image2DArray& operator=(Image2DArray& other) { image = other.image; return *this; } Image2DArray(Image2DArray&& other) : image(std::move(other.image)) {} Image2DArray& operator=(Image2DArray&& other) { std::swap(image, other.image); return *this; } ~Image2DArray() = default; const cl::Image2DArray& data() const { return image; } cl::Image2DArray& data() { return image; } private: cl::Image2DArray image; }; } #endif // OPENCL_IMAGE2D_ARRAY_HPP
#include "PlatoIncludes.h" #include "Strings.h" #include "ClassTypeInfo.h" #include "Identifier.h" #include "IdentifierRegex.h" #include "PropertyScopes.h" #include "PropertyModes.h" #include "Property.h" #include "ConfigurePhases.h" #include "ResolutionModes.h" #include "Container.h" #include "ThreadLocalVariable.h" #include "Model.h" #include "Pad.h" #include "InputPad.h" #include "OutputPad.h" #include "Region.h" #include "Alias.h" #include "Connector.h" #include "Converter.h" #include "Disposition.h" #include "Distributor.h" #include "Link.h" #include "Flow.h" #include "Phenomenon.h" #include "Restrictor.h" #include "Translator.h" #include "Transducer.h" namespace Plato { const ClassTypeInfo* Region::TypeInfo = NULL; const ClassTypeInfo::HashSet* Region::PropertyTypes = NULL; void Region::Initializer() { TypeInfo = new ClassTypeInfo("Region",307,1,NULL,Container::TypeInfo); PropertyTypes = Container::CreatePropertyTypes( Region::TypeInfo, Alias::TypeInfo, Connector::TypeInfo, Converter::TypeInfo, Disposition::TypeInfo, Distributor::TypeInfo, Flow::TypeInfo, Link::TypeInfo, Phenomenon::TypeInfo, Restrictor::TypeInfo, Translator::TypeInfo, NULL); } void Region::Finalizer() { delete TypeInfo; delete PropertyTypes; } Region::Region(Container* creator, Container* parent, Identifier& elementName, PropertyScopesEnum scope) : Container(*PropertyTypes, creator, parent, elementName, scope) { } Region::Region(Container* parent, Identifier& elementName, PropertyScopesEnum scope) : Container(*PropertyTypes, parent, parent, elementName, scope) { } Region::Region(Container* parent, const char* elementName, PropertyScopesEnum scope) : Container(*PropertyTypes, parent, parent, *new Identifier(elementName), scope) { } Region::~Region() { } void Region::Update() { // Update sub regions. vector<Property*>* properties; properties = GetCategory(*Region::TypeInfo); if(properties!=NULL) { Model::Update(*properties); } // Update DIDs. properties = GetCategory(*Disposition::TypeInfo); if (properties!=NULL) { Model::Update(*properties); } // DEBUG: To do: Update other kinds of elements. } void Region::BirthDeath() { } void Region::Superposition() { } }
//If not included: compiler error "C1010" with MSVC++. #include "../stdafx.h" #include "../global.h" //for type "BYTE" //This class is the base class for classes implementing the Access to //the ModelSpecific Registers //I also could have put every single implementation (e.g. //Windows/MFC, wxWidgets, Linux) into a single controller class. //but then I would have to use conditional compile preprocessor //macros within the class (code is hard to read/maintain then). //This is intended to be a superclass with implemented funkions //that do nothing ("{}") because so there the methods don't need //to be overwrittten as with pure virtual methods. class MSRaccessBase { public: BYTE changePstate(BYTE byPstate, BYTE byCoreNumber) { return 0 ; } };
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * 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 <AK/Time.h> #include <Kernel/Process.h> #include <Kernel/Time/TimeManagement.h> namespace Kernel { KResultOr<int> Process::sys$clock_gettime(clockid_t clock_id, Userspace<timespec*> user_ts) { REQUIRE_PROMISE(stdio); auto ts = TimeManagement::the().current_time(clock_id); if (ts.is_error()) return ts.error(); if (!copy_to_user(user_ts, &ts.value())) return EFAULT; return 0; } KResultOr<int> Process::sys$clock_settime(clockid_t clock_id, Userspace<const timespec*> user_ts) { REQUIRE_PROMISE(settime); if (!is_superuser()) return EPERM; timespec ts; if (!copy_from_user(&ts, user_ts)) return EFAULT; switch (clock_id) { case CLOCK_REALTIME: TimeManagement::the().set_epoch_time(ts); break; default: return EINVAL; } return 0; } KResultOr<int> Process::sys$clock_nanosleep(Userspace<const Syscall::SC_clock_nanosleep_params*> user_params) { REQUIRE_PROMISE(stdio); Syscall::SC_clock_nanosleep_params params; if (!copy_from_user(&params, user_params)) return EFAULT; timespec requested_sleep; if (!copy_from_user(&requested_sleep, params.requested_sleep)) return EFAULT; bool is_absolute; switch (params.flags) { case 0: is_absolute = false; break; case TIMER_ABSTIME: is_absolute = true; break; default: return EINVAL; } if (!TimeManagement::is_valid_clock_id(params.clock_id)) return EINVAL; bool was_interrupted; if (is_absolute) { was_interrupted = Thread::current()->sleep_until(params.clock_id, requested_sleep).was_interrupted(); } else { timespec remaining_sleep; was_interrupted = Thread::current()->sleep(params.clock_id, requested_sleep, &remaining_sleep).was_interrupted(); if (was_interrupted && params.remaining_sleep && !copy_to_user(params.remaining_sleep, &remaining_sleep)) return EFAULT; } if (was_interrupted) return EINTR; return 0; } KResultOr<int> Process::sys$adjtime(Userspace<const timeval*> user_delta, Userspace<timeval*> user_old_delta) { if (user_old_delta) { timespec old_delta_ts = TimeManagement::the().remaining_epoch_time_adjustment(); timeval old_delta; timespec_to_timeval(old_delta_ts, old_delta); if (!copy_to_user(user_old_delta, &old_delta)) return EFAULT; } if (user_delta) { REQUIRE_PROMISE(settime); if (!is_superuser()) return EPERM; timeval delta; if (!copy_from_user(&delta, user_delta)) return EFAULT; if (delta.tv_usec < 0 || delta.tv_usec >= 1'000'000) return EINVAL; timespec delta_ts; timeval_to_timespec(delta, delta_ts); TimeManagement::the().set_remaining_epoch_time_adjustment(delta_ts); } return 0; } KResultOr<int> Process::sys$gettimeofday(Userspace<timeval*> user_tv) { REQUIRE_PROMISE(stdio); auto tv = kgettimeofday(); if (!copy_to_user(user_tv, &tv)) return EFAULT; return 0; } }
#include <iostream> #include "circular_buffer.hpp" using namespace std; int main() { itis::circular_buffer<int> buf = itis::circular_buffer<int>(8); for (int num = 1; num < 16; num++) { buf.EnqueueBack(num); } buf.Resize(10); int num = 99; buf.EnqueueBack(num); num = 11; buf.EnqueueFront(num); cout << buf.getFront().value() << ' ' << buf.getBack().value() << endl; return 0; }
#ifndef __AUDIO_PIPE_HPP__ #define __AUDIO_PIPE_HPP__ #include <string> #include <list> #include <mutex> #include <libwebsockets.h> class AudioPipe { public: enum LwsState_t { LWS_CLIENT_IDLE, LWS_CLIENT_CONNECTING, LWS_CLIENT_CONNECTED, LWS_CLIENT_FAILED, LWS_CLIENT_DISCONNECTING, LWS_CLIENT_DISCONNECTED }; enum NotifyEvent_t { CONNECT_SUCCESS, CONNECT_FAIL, CONNECTION_DROPPED, CONNECTION_CLOSED_GRACEFULLY, MESSAGE }; typedef void (*log_emit_function)(int level, const char *line); typedef void (*notifyHandler_t)(const char *sessionId, NotifyEvent_t event, const char* message); struct lws_per_vhost_data { struct lws_context *context; struct lws_vhost *vhost; const struct lws_protocols *protocol; }; static void initialize(const char* protocolName, unsigned int nThreads, int loglevel, log_emit_function logger); static bool deinitialize(); static bool lws_service_thread(unsigned int nServiceThread); // constructor AudioPipe(const char* uuid, const char* host, unsigned int port, const char* path, int sslFlags, size_t bufLen, size_t minFreespace, const char* username, const char* password, notifyHandler_t callback); ~AudioPipe(); LwsState_t getLwsState(void) { return m_state; } void connect(void); void bufferForSending(const char* text); size_t binarySpaceAvailable(void) { return m_audio_buffer_max_len - m_audio_buffer_write_offset; } size_t binaryMinSpace(void) { return m_audio_buffer_min_freespace; } char * binaryWritePtr(void) { return (char *) m_audio_buffer + m_audio_buffer_write_offset; } void binaryWritePtrAdd(size_t len) { m_audio_buffer_write_offset += len; } void binaryWritePtrResetToZero(void) { m_audio_buffer_write_offset = 0; } void lockAudioBuffer(void) { m_audio_mutex.lock(); } void unlockAudioBuffer(void) ; bool hasBasicAuth(void) { return !m_username.empty() && !m_password.empty(); } void getBasicAuth(std::string& username, std::string& password) { username = m_username; password = m_password; } void do_graceful_shutdown(); bool isGracefulShutdown(void) { return m_gracefulShutdown; } void close() ; // no default constructor or copying AudioPipe() = delete; AudioPipe(const AudioPipe&) = delete; void operator=(const AudioPipe&) = delete; private: static int lws_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); static bool lws_initialized; static bool lws_stopping; static unsigned int nchild; static struct lws_context *contexts[]; static unsigned int numContexts; static std::string protocolName; static std::mutex mutex_connects; static std::mutex mutex_disconnects; static std::mutex mutex_writes; static std::list<AudioPipe*> pendingConnects; static std::list<AudioPipe*> pendingDisconnects; static std::list<AudioPipe*> pendingWrites; static log_emit_function logger; static AudioPipe* findAndRemovePendingConnect(struct lws *wsi); static AudioPipe* findPendingConnect(struct lws *wsi); static void addPendingConnect(AudioPipe* ap); static void addPendingDisconnect(AudioPipe* ap); static void addPendingWrite(AudioPipe* ap); static void processPendingConnects(lws_per_vhost_data *vhd); static void processPendingDisconnects(lws_per_vhost_data *vhd); static void processPendingWrites(void); bool connect_client(struct lws_per_vhost_data *vhd); LwsState_t m_state; std::string m_uuid; std::string m_host; unsigned int m_port; std::string m_path; std::string m_metadata; std::mutex m_text_mutex; std::mutex m_audio_mutex; int m_sslFlags; struct lws *m_wsi; uint8_t *m_audio_buffer; size_t m_audio_buffer_max_len; size_t m_audio_buffer_write_offset; size_t m_audio_buffer_min_freespace; uint8_t* m_recv_buf; uint8_t* m_recv_buf_ptr; size_t m_recv_buf_len; struct lws_per_vhost_data* m_vhd; notifyHandler_t m_callback; log_emit_function m_logger; std::string m_username; std::string m_password; bool m_gracefulShutdown; }; #endif
#include <QCoreApplication> #include <QStandardPaths> #include <QFileInfo> #include <QString> #include <QDir> #include <QDebug> #include "Logger.h" #include "wallet/api/wallet2_api.h" // default log path by OS (should be writable) static const QString defaultLogName = "arqma-wallet-gui.log"; #if defined(Q_OS_IOS) //AppDataLocation = "<APPROOT>/Library/Application Support" static const QString osPath = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0); static const QString appFolder = "arqma-wallet-gui"; #elif defined(Q_OS_WIN) //AppDataLocation = "C:/Users/<USER>/AppData/Roaming/<APPNAME>" static const QString osPath = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0); static const QString appFolder = "arqma-wallet-gui"; #elif defined(Q_OS_ANDROID) //AppDataLocation = "<USER>/<APPNAME>/files" static const QString osPath = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(1); static const QString appFolder = ""; #elif defined(Q_OS_MAC) //HomeLocation = "~" static const QString osPath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).at(0); static const QString appFolder = "Library/Logs"; #else // linux + bsd //HomeLocation = "~" static const QString osPath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).at(0); static const QString appFolder = ".arqma"; #endif // return the absolute path of the logfile const QString getLogPath(const QString logPath) { const QFileInfo fi(logPath); if(!logPath.isEmpty() && !fi.isDir()) return fi.absoluteFilePath(); else { QDir appDir(osPath + "/" + appFolder); if(!appDir.exists()) if(!appDir.mkpath(".")) qWarning() << "Logger: Cannot create log directory " + appDir.path(); return appDir.path() + "/" + defaultLogName; } } // custom messageHandler that foward all messages to easylogging void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) { (void) context; // context isn't used in release builds const std::string cat = "frontend"; // category displayed in the log const std::string msg = message.toStdString(); switch(type) { case QtDebugMsg: Monero::Wallet::debug(cat, msg); break; case QtInfoMsg: Monero::Wallet::info(cat, msg); break; case QtWarningMsg: Monero::Wallet::warning(cat, msg); break; case QtCriticalMsg: Monero::Wallet::error(cat, msg); break; case QtFatalMsg: Monero::Wallet::error(cat, msg); break; } }
//Sample provided by Fabio Galuppo //October 2016 //http://www.simplycpp.com #ifndef SAMPLE2_HPP #define SAMPLE2_HPP int sample2_main(); #endif /* SAMPLE2_HPP */
#include "gear_core_common.h" #include "RenderSurface.h" #include "ARC/src/StringConversion.h" #include "directx12/D3D12Context.h" #include "vulkan/VKContext.h" using namespace gear; using namespace graphics; using namespace miru; using namespace miru::crossplatform; RenderSurface::RenderSurface(CreateInfo* pCreateInfo) { m_CI = *pCreateInfo; Allocator::CreateInfo attachmentAllocatorCI; attachmentAllocatorCI.debugName = "GEAR_CORE_GPU_ALLOCATOR_Attachments"; attachmentAllocatorCI.pContext = m_CI.pContext; attachmentAllocatorCI.blockSize = Allocator::BlockSize::BLOCK_SIZE_64MB; attachmentAllocatorCI.properties = Allocator::PropertiesBit::DEVICE_LOCAL_BIT; m_AttachmentAllocator = Allocator::Create(&attachmentAllocatorCI); m_CurrentWidth = m_CI.width; m_CurrentHeight = m_CI.height; CreateAttachments(); CreateMainRenderPass(); CreateHDRRenderPass(); CreateMainFramebuffers(); CreateHDRFramebuffers(); } RenderSurface::~RenderSurface() { m_CI.pContext->DeviceWaitIdle(); } void RenderSurface::CreateAttachments() { //ColourSRGB { m_ColourSRGBImageCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - ColourSRGBImage"; m_ColourSRGBImageCI.device = m_CI.pContext->GetDevice(); m_ColourSRGBImageCI.type = Image::Type::TYPE_2D; m_ColourSRGBImageCI.format = m_SRGBFormat; m_ColourSRGBImageCI.width = m_CurrentWidth; m_ColourSRGBImageCI.height = m_CurrentHeight; m_ColourSRGBImageCI.depth = 1; m_ColourSRGBImageCI.mipLevels = 1; m_ColourSRGBImageCI.arrayLayers = 1; m_ColourSRGBImageCI.sampleCount = Image::SampleCountBit::SAMPLE_COUNT_1_BIT; m_ColourSRGBImageCI.usage = Image::UsageBit::COLOUR_ATTACHMENT_BIT | Image::UsageBit::SAMPLED_BIT; m_ColourSRGBImageCI.layout = Image::Layout::UNKNOWN; m_ColourSRGBImageCI.size = 0; m_ColourSRGBImageCI.data = nullptr; m_ColourSRGBImageCI.pAllocator = m_AttachmentAllocator; m_ColourSRGBImage = Image::Create(&m_ColourSRGBImageCI); m_ColourSRGBImageViewCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - ColourSRGBImageView"; m_ColourSRGBImageViewCI.device = m_CI.pContext->GetDevice(); m_ColourSRGBImageViewCI.pImage = m_ColourSRGBImage; m_ColourSRGBImageViewCI.viewType = Image::Type::TYPE_2D; m_ColourSRGBImageViewCI.subresourceRange = { Image::AspectBit::COLOUR_BIT, 0, 1, 0, 1 }; m_ColourSRGBImageView = ImageView::Create(&m_ColourSRGBImageViewCI); } //Depth { m_DepthImageCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - DepthImage"; m_DepthImageCI.device = m_CI.pContext->GetDevice(); m_DepthImageCI.type = Image::Type::TYPE_2D; m_DepthImageCI.format = Image::Format::D32_SFLOAT; m_DepthImageCI.width = m_CurrentWidth; m_DepthImageCI.height = m_CurrentHeight; m_DepthImageCI.depth = 1; m_DepthImageCI.mipLevels = 1; m_DepthImageCI.arrayLayers = 1; m_DepthImageCI.sampleCount = m_CI.samples; m_DepthImageCI.usage = Image::UsageBit::DEPTH_STENCIL_ATTACHMENT_BIT; m_DepthImageCI.layout = Image::Layout::UNKNOWN; m_DepthImageCI.size = 0; m_DepthImageCI.data = nullptr; m_DepthImageCI.pAllocator = m_AttachmentAllocator; m_DepthImage = Image::Create(&m_DepthImageCI); m_DepthImageViewCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - DepthImageView"; m_DepthImageViewCI.device = m_CI.pContext->GetDevice(); m_DepthImageViewCI.pImage = m_DepthImage; m_DepthImageViewCI.viewType = Image::Type::TYPE_2D; m_DepthImageViewCI.subresourceRange = { Image::AspectBit::DEPTH_BIT, 0, 1, 0, 1 }; m_DepthImageView = ImageView::Create(&m_DepthImageViewCI); } //MSAAColour if (m_CI.samples > Image::SampleCountBit::SAMPLE_COUNT_1_BIT) { m_MSAAColourImageCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - MSAAColourImage"; m_MSAAColourImageCI.device = m_CI.pContext->GetDevice(); m_MSAAColourImageCI.type = Image::Type::TYPE_2D; m_MSAAColourImageCI.format = m_HDRFormat; m_MSAAColourImageCI.width = m_CurrentWidth; m_MSAAColourImageCI.height = m_CurrentHeight; m_MSAAColourImageCI.depth = 1; m_MSAAColourImageCI.mipLevels = 1; m_MSAAColourImageCI.arrayLayers = 1; m_MSAAColourImageCI.sampleCount = m_CI.samples; m_MSAAColourImageCI.usage = Image::UsageBit::COLOUR_ATTACHMENT_BIT; m_MSAAColourImageCI.layout = Image::Layout::UNKNOWN; m_MSAAColourImageCI.size = 0; m_MSAAColourImageCI.data = nullptr; m_MSAAColourImageCI.pAllocator = m_AttachmentAllocator; m_MSAAColourImage = Image::Create(&m_MSAAColourImageCI); m_MSAAColourImageViewCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - MSAAColourImageView"; m_MSAAColourImageViewCI.device = m_CI.pContext->GetDevice(); m_MSAAColourImageViewCI.pImage = m_MSAAColourImage; m_MSAAColourImageViewCI.viewType = Image::Type::TYPE_2D; m_MSAAColourImageViewCI.subresourceRange = { Image::AspectBit::COLOUR_BIT, 0, 1, 0, 1 }; m_MSAAColourImageView = ImageView::Create(&m_MSAAColourImageViewCI); } //Colour { m_ColourImageCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - ColourImage"; m_ColourImageCI.device = m_CI.pContext->GetDevice(); m_ColourImageCI.type = Image::Type::TYPE_2D; m_ColourImageCI.format = m_HDRFormat; m_ColourImageCI.width = m_CurrentWidth; m_ColourImageCI.height = m_CurrentHeight; m_ColourImageCI.depth = 1; m_ColourImageCI.mipLevels = 1; m_ColourImageCI.arrayLayers = 1; m_ColourImageCI.sampleCount = Image::SampleCountBit::SAMPLE_COUNT_1_BIT; m_ColourImageCI.usage = Image::UsageBit::COLOUR_ATTACHMENT_BIT | Image::UsageBit::STORAGE_BIT | Image::UsageBit::INPUT_ATTACHMENT_BIT; m_ColourImageCI.layout = Image::Layout::UNKNOWN; m_ColourImageCI.size = 0; m_ColourImageCI.data = nullptr; m_ColourImageCI.pAllocator = m_AttachmentAllocator; m_ColourImage = Image::Create(&m_ColourImageCI); m_ColourImageViewCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - ColourImageView"; m_ColourImageViewCI.device = m_CI.pContext->GetDevice(); m_ColourImageViewCI.pImage = m_ColourImage; m_ColourImageViewCI.viewType = Image::Type::TYPE_2D; m_ColourImageViewCI.subresourceRange = { Image::AspectBit::COLOUR_BIT, 0, 1, 0, 1 }; m_ColourImageView = ImageView::Create(&m_ColourImageViewCI); } } void RenderSurface::CreateMainRenderPass() { m_MainRenderPassCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - MainRenderPass"; m_MainRenderPassCI.device = m_CI.pContext->GetDevice(); if (m_CI.samples > Image::SampleCountBit::SAMPLE_COUNT_1_BIT) { m_MainRenderPassCI.attachments = { { //0 - Depth m_DepthImageCI.format, m_CI.samples, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::DONT_CARE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL }, { //1 - MSAAColour m_HDRFormat, m_CI.samples, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::STORE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL }, { //2 - Colour m_HDRFormat, Image::SampleCountBit::SAMPLE_COUNT_1_BIT, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::STORE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL } }; m_MainRenderPassCI.subpassDescriptions = { { PipelineType::GRAPHICS, {}, {{1, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL}}, {{2, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL}}, {{0, Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL}}, {} } }; } else { m_MainRenderPassCI.attachments = { { //0 - Depth m_DepthImageCI.format, m_CI.samples, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::DONT_CARE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL }, { //1 - Colour m_HDRFormat, Image::SampleCountBit::SAMPLE_COUNT_1_BIT, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::STORE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL } }; m_MainRenderPassCI.subpassDescriptions = { { PipelineType::GRAPHICS, {}, {{1, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL}}, {}, {{0, Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL}}, {} } }; } m_MainRenderPassCI.subpassDependencies = { { MIRU_SUBPASS_EXTERNAL, 0, PipelineStageBit::COLOUR_ATTACHMENT_OUTPUT_BIT, PipelineStageBit::COLOUR_ATTACHMENT_OUTPUT_BIT, (Barrier::AccessBit)0, Barrier::AccessBit::COLOUR_ATTACHMENT_READ_BIT | Barrier::AccessBit::COLOUR_ATTACHMENT_WRITE_BIT, DependencyBit::NONE_BIT } }; m_MainRenderPass = RenderPass::Create(&m_MainRenderPassCI); } void RenderSurface::CreateHDRRenderPass() { m_HDRRenderPassCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - HDRRenderPass"; m_HDRRenderPassCI.device = m_CI.pContext->GetDevice(); m_HDRRenderPassCI.attachments = { { //0 - ColourSRGB m_SRGBFormat, Image::SampleCountBit::SAMPLE_COUNT_1_BIT, RenderPass::AttachmentLoadOp::CLEAR, RenderPass::AttachmentStoreOp::STORE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::UNKNOWN, Image::Layout::SHADER_READ_ONLY_OPTIMAL }, { //1 - Colour m_HDRFormat, Image::SampleCountBit::SAMPLE_COUNT_1_BIT, RenderPass::AttachmentLoadOp::LOAD, RenderPass::AttachmentStoreOp::DONT_CARE, RenderPass::AttachmentLoadOp::DONT_CARE, RenderPass::AttachmentStoreOp::DONT_CARE, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL } }; m_HDRRenderPassCI.subpassDescriptions = { { PipelineType::GRAPHICS, {{1, Image::Layout::SHADER_READ_ONLY_OPTIMAL}}, {{0, Image::Layout::COLOUR_ATTACHMENT_OPTIMAL}}, {}, {}, {} } }; m_HDRRenderPassCI.subpassDependencies = { { MIRU_SUBPASS_EXTERNAL, 0, PipelineStageBit::COLOUR_ATTACHMENT_OUTPUT_BIT, PipelineStageBit::COLOUR_ATTACHMENT_OUTPUT_BIT, (Barrier::AccessBit)0, Barrier::AccessBit::COLOUR_ATTACHMENT_READ_BIT | Barrier::AccessBit::COLOUR_ATTACHMENT_WRITE_BIT, DependencyBit::NONE_BIT } }; m_HDRRenderPass = RenderPass::Create(&m_HDRRenderPassCI); } void RenderSurface::CreateMainFramebuffers() { for (size_t i = 0; i < _countof(m_MainFramebuffers); i++) { m_MainFramebufferCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - MainFramebuffer"; m_MainFramebufferCI.device = m_CI.pContext->GetDevice(); m_MainFramebufferCI.renderPass = m_MainRenderPass; if (m_CI.samples > Image::SampleCountBit::SAMPLE_COUNT_1_BIT) m_MainFramebufferCI.attachments = { m_DepthImageView, m_MSAAColourImageView, m_ColourImageView }; else m_MainFramebufferCI.attachments = { m_DepthImageView, m_ColourImageView }; m_MainFramebufferCI.width = m_CurrentWidth; m_MainFramebufferCI.height = m_CurrentHeight; m_MainFramebufferCI.layers = 1; m_MainFramebuffers[i] = Framebuffer::Create(&m_MainFramebufferCI); } } void RenderSurface::CreateHDRFramebuffers() { for (size_t i = 0; i < _countof(m_HDRFramebuffers); i++) { m_HDRFramebufferCI.debugName = "GEAR_CORE_RenderSurface: " + m_CI.debugName + " - HDRFramebuffer"; m_HDRFramebufferCI.device = m_CI.pContext->GetDevice(); m_HDRFramebufferCI.renderPass = m_HDRRenderPass; m_HDRFramebufferCI.attachments = { m_ColourSRGBImageView, m_ColourImageView }; m_HDRFramebufferCI.width = m_CurrentWidth; m_HDRFramebufferCI.height = m_CurrentHeight; m_HDRFramebufferCI.layers = 1; m_HDRFramebuffers[i] = Framebuffer::Create(&m_HDRFramebufferCI); } } void RenderSurface::Resize(uint32_t width, uint32_t height) { m_CurrentWidth = width; m_CurrentHeight = height; CreateAttachments(); CreateMainFramebuffers(); CreateHDRFramebuffers(); }
// Copyright (c) 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 <rpc/blockchain.h> #include <amount.h> #include <chainparams.h> #include <checkpoints.h> #include <coins.h> #include <consensus/validation.h> #include <validation.h> #include <core_io.h> #include <index/txindex.h> #include <policy/feerate.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <rpc/server.h> #include <streams.h> #include <sync.h> #include <txdb.h> #include <txmempool.h> #include <util.h> #include <utilstrencodings.h> #include <hash.h> #include <validationinterface.h> #include <warnings.h> #include <stdint.h> #include <univalue.h> #include <boost/algorithm/string.hpp> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <memory> #include <mutex> #include <condition_variable> struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; /* Calculate the difficulty for a given block index. */ double GetDifficulty(const CBlockIndex* blockindex) { if (blockindex == nullptr) { return 1.0; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { AssertLockHeld(cs_main); UniValue result(UniValue::VOBJ); result.pushKV("hash", blockindex->GetBlockHash().GetHex()); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.pushKV("confirmations", confirmations); result.pushKV("height", blockindex->nHeight); result.pushKV("version", blockindex->nVersion); result.pushKV("versionHex", strprintf("%08x", blockindex->nVersion)); result.pushKV("merkleroot", blockindex->hashMerkleRoot.GetHex()); result.pushKV("time", (int64_t)blockindex->nTime); result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast()); result.pushKV("nonce", (uint64_t)blockindex->nNonce); result.pushKV("bits", strprintf("%08x", blockindex->nBits)); result.pushKV("difficulty", GetDifficulty(blockindex)); result.pushKV("chainwork", blockindex->nChainWork.GetHex()); if (blockindex->pprev) result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex()); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails) { AssertLockHeld(cs_main); UniValue result(UniValue::VOBJ); result.pushKV("hash", blockindex->GetBlockHash().GetHex()); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.pushKV("confirmations", confirmations); result.pushKV("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)); result.pushKV("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)); result.pushKV("weight", (int)::GetBlockWeight(block)); result.pushKV("height", blockindex->nHeight); result.pushKV("version", block.nVersion); result.pushKV("versionHex", strprintf("%08x", block.nVersion)); result.pushKV("merkleroot", block.hashMerkleRoot.GetHex()); UniValue txs(UniValue::VARR); for(const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags()); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.pushKV("tx", txs); result.pushKV("time", block.GetBlockTime()); result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast()); result.pushKV("nonce", (uint64_t)block.nNonce); result.pushKV("bits", strprintf("%08x", block.nBits)); result.pushKV("difficulty", GetDifficulty(blockindex)); result.pushKV("chainwork", blockindex->nChainWork.GetHex()); if (blockindex->pprev) result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex()); return result; } static UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } static UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } static UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000") ); int timeout = 0; if (!request.params[0].isNull()) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.pushKV("hash", block.hash.GetHex()); ret.pushKV("height", block.height); return ret; } static UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.pushKV("hash", block.hash.GetHex()); ret.pushKV("height", block.height); return ret; } static UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000") ); int timeout = 0; int height = request.params[0].get_int(); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.pushKV("hash", block.hash.GetHex()); ret.pushKV("height", block.height); return ret; } static UniValue syncwithvalidationinterfacequeue(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 0) { throw std::runtime_error( "syncwithvalidationinterfacequeue\n" "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n" "\nExamples:\n" + HelpExampleCli("syncwithvalidationinterfacequeue","") + HelpExampleRpc("syncwithvalidationinterfacequeue","") ); } SyncWithValidationInterfaceQueue(); return NullUniValue; } static UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(chainActive.Tip()); } static std::string EntryDescriptionString() { return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + " (DEPRECATED)\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority (DEPRECATED)\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) (DEPRECATED)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) (DEPRECATED)\n" " \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n" " \"fees\" : {\n" " \"base\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modified\" : n, (numeric) transaction fee with fee deltas used for mining priority in " + CURRENCY_UNIT + "\n" " \"ancestor\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) in " + CURRENCY_UNIT + "\n" " \"descendant\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) in " + CURRENCY_UNIT + "\n" " }\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " \"spentby\" : [ (array) unconfirmed transactions spending outputs from this transaction\n" " \"transactionid\", (string) child transaction id\n" " ... ]\n"; } static void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(::mempool.cs) { AssertLockHeld(mempool.cs); UniValue fees(UniValue::VOBJ); fees.pushKV("base", ValueFromAmount(e.GetFee())); fees.pushKV("modified", ValueFromAmount(e.GetModifiedFee())); fees.pushKV("ancestor", ValueFromAmount(e.GetModFeesWithAncestors())); fees.pushKV("descendant", ValueFromAmount(e.GetModFeesWithDescendants())); info.pushKV("fees", fees); info.pushKV("size", (int)e.GetTxSize()); info.pushKV("fee", ValueFromAmount(e.GetFee())); info.pushKV("modifiedfee", ValueFromAmount(e.GetModifiedFee())); info.pushKV("time", e.GetTime()); info.pushKV("height", (int)e.GetHeight()); info.pushKV("descendantcount", e.GetCountWithDescendants()); info.pushKV("descendantsize", e.GetSizeWithDescendants()); info.pushKV("descendantfees", e.GetModFeesWithDescendants()); info.pushKV("ancestorcount", e.GetCountWithAncestors()); info.pushKV("ancestorsize", e.GetSizeWithAncestors()); info.pushKV("ancestorfees", e.GetModFeesWithAncestors()); info.pushKV("wtxid", mempool.vTxHashes[e.vTxHashesIdx].first.ToString()); const CTransaction& tx = e.GetTx(); std::set<std::string> setDepends; for (const CTxIn& txin : tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); for (const std::string& dep : setDepends) { depends.push_back(dep); } info.pushKV("depends", depends); UniValue spent(UniValue::VARR); const CTxMemPool::txiter &it = mempool.mapTx.find(tx.GetHash()); const CTxMemPool::setEntries &setChildren = mempool.GetMemPoolChildren(it); for (const CTxMemPool::txiter &childiter : setChildren) { spent.push_back(childiter->GetTx().GetHash().ToString()); } info.pushKV("spentby", spent); } UniValue mempoolToJSON(bool fVerbose) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); for (const CTxMemPoolEntry& e : mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.pushKV(hash.ToString(), info); } return o; } else { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); for (const uint256& hash : vtxid) a.push_back(hash.ToString()); return a; } } static UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); bool fVerbose = false; if (!request.params[0].isNull()) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } static UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"") ); } bool fVerbose = false; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); for (CTxMemPool::txiter ancestorIt : setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); for (CTxMemPool::txiter ancestorIt : setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.pushKV(_hash.ToString(), info); } return o; } } static UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "getmempooldescendants txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool descendants.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempooldescendants", "\"mytxid\"") + HelpExampleRpc("getmempooldescendants", "\"mytxid\"") ); } bool fVerbose = false; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); for (CTxMemPool::txiter descendantIt : setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); for (CTxMemPool::txiter descendantIt : setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.pushKV(_hash.ToString(), info); } return o; } } static UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw std::runtime_error( "getmempoolentry txid\n" "\nReturns mempool data for given transaction\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "\nResult:\n" "{ (json object)\n" + EntryDescriptionString() + "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolentry", "\"mytxid\"") + HelpExampleRpc("getmempoolentry", "\"mytxid\"") ); } uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } static UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "getblockhash height\n" "\nReturns hash of block in best-block-chain at height provided.\n" "\nArguments:\n" "1. height (numeric, required) The height index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } static UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); const CBlockIndex* pblockindex = LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } static CBlock GetBlockChecked(const CBlockIndex* pblockindex) { CBlock block; if (IsBlockPruned(pblockindex)) { throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)"); } if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) { // Block not found on disk. This could be because we have the block // header in our index but don't have the block (for example if a // non-whitelisted node sends us an unrequested long chain of valid // blocks, we add the headers to our index, but don't accept the // block). throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk"); } return block; } static UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "getblock \"blockhash\" ( verbosity ) \n" "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbosity is 1, returns an Object with information about block <hash>.\n" "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n" "\nArguments:\n" "1. \"blockhash\" (string, required) The block hash\n" "2. verbosity (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n" "\nResult (for verbosity = 0):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nResult (for verbosity = 1):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"strippedsize\" : n, (numeric) The block size excluding witness data\n" " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbosity = 2):\n" "{\n" " ..., Same output as verbosity = 1.\n" " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n" " ,...\n" " ],\n" " ,... Same output as verbosity = 1.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int verbosity = 1; if (!request.params[1].isNull()) { if(request.params[1].isNum()) verbosity = request.params[1].get_int(); else verbosity = request.params[1].get_bool() ? 1 : 0; } const CBlockIndex* pblockindex = LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } const CBlock block = GetBlockChecked(pblockindex); if (verbosity <= 0) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex, verbosity >= 2); } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nBogoSize; uint256 hashSerialized; uint64_t nDiskSize; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {} }; static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs) { assert(!outputs.empty()); ss << hash; ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u); stats.nTransactions++; for (const auto output : outputs) { ss << VARINT(output.first + 1); ss << output.second.out.scriptPubKey; ss << VARINT(output.second.out.nValue, VarIntMode::NONNEGATIVE_SIGNED); stats.nTransactionOutputs++; stats.nTotalAmount += output.second.out.nValue; stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ + 2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */; } ss << VARINT(0u); } //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor()); assert(pcursor); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight; } ss << stats.hashBlock; uint256 prevkey; std::map<uint32_t, Coin> outputs; while (pcursor->Valid()) { boost::this_thread::interruption_point(); COutPoint key; Coin coin; if (pcursor->GetKey(key) && pcursor->GetValue(coin)) { if (!outputs.empty() && key.hash != prevkey) { ApplyStats(stats, ss, prevkey, outputs); outputs.clear(); } prevkey = key.hash; outputs[key.n] = std::move(coin); } else { return error("%s: unable to read value", __func__); } pcursor->Next(); } if (!outputs.empty()) { ApplyStats(stats, ss, prevkey, outputs); } stats.hashSerialized = ss.GetHash(); stats.nDiskSize = view->EstimateSize(); return true; } static UniValue pruneblockchain(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "pruneblockchain\n" "\nArguments:\n" "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n" " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n" "\nResult:\n" "n (numeric) Height of the last block pruned.\n" "\nExamples:\n" + HelpExampleCli("pruneblockchain", "1000") + HelpExampleRpc("pruneblockchain", "1000")); if (!fPruneMode) throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height."); // Height value more than a billion is too high to be a block height, and // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW); if (!pindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp."); } heightParam = pindex->nHeight; } unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) chainActive.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height."); else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n"); height = chainHeight - MIN_BLOCKS_TO_KEEP; } PruneBlockFilesManual(height); return uint64_t(height); } static UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n" " \"transactions\": n, (numeric) The number of transactions with unspent outputs\n" " \"txouts\": n, (numeric) The number of unspent transaction outputs\n" " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n" " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n" " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsdbview.get(), stats)) { ret.pushKV("height", (int64_t)stats.nHeight); ret.pushKV("bestblock", stats.hashBlock.GetHex()); ret.pushKV("transactions", (int64_t)stats.nTransactions); ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs); ret.pushKV("bogosize", (int64_t)stats.nBogoSize); ret.pushKV("hash_serialized_2", stats.hashSerialized.GetHex()); ret.pushKV("disk_size", stats.nDiskSize); ret.pushKV("total_amount", ValueFromAmount(stats.nTotalAmount)); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw std::runtime_error( "gettxout \"txid\" n ( include_mempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"n\" (numeric, required) vout number\n" "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true." " Note that an unspent output that is spent in the mempool won't appear.\n" "\nResult:\n" "{\n" " \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of bitcoin addresses\n" " \"address\" (string) bitcoin address\n" " ,...\n" " ]\n" " },\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); COutPoint out(hash, n); bool fMempool = true; if (!request.params[2].isNull()) fMempool = request.params[2].get_bool(); Coin coin; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip.get(), mempool); if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { return NullUniValue; } } else { if (!pcoinsTip->GetCoin(out, coin)) { return NullUniValue; } } const CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock()); ret.pushKV("bestblock", pindex->GetBlockHash().GetHex()); if (coin.nHeight == MEMPOOL_HEIGHT) { ret.pushKV("confirmations", 0); } else { ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)); } ret.pushKV("value", ValueFromAmount(coin.out.nValue)); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true); ret.pushKV("scriptPubKey", o); ret.pushKV("coinbase", (bool)coin.fCoinBase); return ret; } static UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw std::runtime_error( "verifychain ( checklevel nblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (!request.params[0].isNull()) nCheckLevel = request.params[0].get_int(); if (!request.params[1].isNull()) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height; break; case 3: activated = pindex->nHeight >= consensusParams.BIP66Height; break; case 4: activated = pindex->nHeight >= consensusParams.BIP65Height; break; } rv.pushKV("status", activated); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.pushKV("id", name); rv.pushKV("version", version); rv.pushKV("reject", SoftForkMajorityDesc(version, pindex, consensusParams)); return rv; } static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id); switch (thresholdState) { case ThresholdState::DEFINED: rv.pushKV("status", "defined"); break; case ThresholdState::STARTED: rv.pushKV("status", "started"); break; case ThresholdState::LOCKED_IN: rv.pushKV("status", "locked_in"); break; case ThresholdState::ACTIVE: rv.pushKV("status", "active"); break; case ThresholdState::FAILED: rv.pushKV("status", "failed"); break; } if (ThresholdState::STARTED == thresholdState) { rv.pushKV("bit", consensusParams.vDeployments[id].bit); } rv.pushKV("startTime", consensusParams.vDeployments[id].nStartTime); rv.pushKV("timeout", consensusParams.vDeployments[id].nTimeout); rv.pushKV("since", VersionBitsTipStateSinceHeight(consensusParams, id)); if (ThresholdState::STARTED == thresholdState) { UniValue statsUV(UniValue::VOBJ); BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id); statsUV.pushKV("period", statsStruct.period); statsUV.pushKV("threshold", statsStruct.threshold); statsUV.pushKV("elapsed", statsStruct.elapsed); statsUV.pushKV("count", statsStruct.count); statsUV.pushKV("possible", statsStruct.possible); rv.pushKV("statistics", statsUV); } return rv; } static void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (consensusParams.vDeployments[id].nTimeout > 0) bip9_softforks.pushKV(VersionBitsDeploymentInfo[id].name, BIP9SoftForkDesc(consensusParams, id)); } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding blockchain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n" " \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n" " \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " },\n" " }, ...\n" " ],\n" " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n" " \"xxxx\" : { (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n" " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n" " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n" " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n" " \"since\": xx, (numeric) height of the first block to which the status applies\n" " \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n" " \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n" " \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n" " \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n" " \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n" " \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n" " }\n" " }\n" " }\n" " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.pushKV("chain", Params().NetworkIDString()); obj.pushKV("blocks", (int)chainActive.Height()); obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1); obj.pushKV("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()); obj.pushKV("difficulty", (double)GetDifficulty(chainActive.Tip())); obj.pushKV("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()); obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())); obj.pushKV("initialblockdownload", IsInitialBlockDownload()); obj.pushKV("chainwork", chainActive.Tip()->nChainWork.GetHex()); obj.pushKV("size_on_disk", CalculateCurrentUsage()); obj.pushKV("pruned", fPruneMode); if (fPruneMode) { CBlockIndex* block = chainActive.Tip(); assert(block); while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) { block = block->pprev; } obj.pushKV("pruneheight", block->nHeight); // if 0, execution bypasses the whole if block. bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1); obj.pushKV("automatic_pruning", automatic_pruning); if (automatic_pruning) { obj.pushKV("prune_target_size", nPruneTarget); } } const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VOBJ); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); for (int pos = Consensus::DEPLOYMENT_CSV; pos != Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++pos) { BIP9SoftForkDescPushBack(bip9_softforks, consensusParams, static_cast<Consensus::DeploymentPos>(pos)); } obj.pushKV("softforks", softforks); obj.pushKV("bip9_softforks", bip9_softforks); obj.pushKV("warnings", GetWarnings("statusbar")); return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; static UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; std::set<const CBlockIndex*> setOrphans; std::set<const CBlockIndex*> setPrevs; for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); for (const CBlockIndex* block : setTips) { UniValue obj(UniValue::VOBJ); obj.pushKV("height", block->nHeight); obj.pushKV("hash", block->phashBlock->GetHex()); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.pushKV("branchlen", branchLen); std::string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.pushKV("status", status); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.pushKV("size", (int64_t) mempool.size()); ret.pushKV("bytes", (int64_t) mempool.GetTotalTxSize()); ret.pushKV("usage", (int64_t) mempool.DynamicMemoryUsage()); size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.pushKV("maxmempool", (int64_t) maxmempool); ret.pushKV("mempoolminfee", ValueFromAmount(std::max(mempool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK())); ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())); return ret; } static UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n" " \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } static UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "preciousblock \"blockhash\"\n" "\nTreats a block as if it were received before others with the same work.\n" "\nA later preciousblock call can override the effect of an earlier one.\n" "\nThe effects of preciousblock are not retained across restarts.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("preciousblock", "\"blockhash\"") + HelpExampleRpc("preciousblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); pblockindex = LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state)); } return NullUniValue; } static UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "invalidateblock \"blockhash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); CBlockIndex* pblockindex = LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state)); } return NullUniValue; } static UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "reconsiderblock \"blockhash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); CBlockIndex* pblockindex = LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state)); } return NullUniValue; } static UniValue getchaintxstats(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) throw std::runtime_error( "getchaintxstats ( nblocks blockhash )\n" "\nCompute statistics about the total number and rate of transactions in the chain.\n" "\nArguments:\n" "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n" "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n" "\nResult:\n" "{\n" " \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n" " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n" " \"window_final_block_hash\": \"...\", (string) The hash of the final block in the window.\n" " \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n" " \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n" " \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n" " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getchaintxstats", "") + HelpExampleRpc("getchaintxstats", "2016") ); const CBlockIndex* pindex; int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month if (request.params[1].isNull()) { LOCK(cs_main); pindex = chainActive.Tip(); } else { uint256 hash = uint256S(request.params[1].get_str()); LOCK(cs_main); pindex = LookupBlockIndex(hash); if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } if (!chainActive.Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain"); } } assert(pindex != nullptr); if (request.params[0].isNull()) { blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1)); } else { blockcount = request.params[0].get_int(); if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1"); } } const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount); int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast(); int nTxDiff = pindex->nChainTx - pindexPast->nChainTx; UniValue ret(UniValue::VOBJ); ret.pushKV("time", (int64_t)pindex->nTime); ret.pushKV("txcount", (int64_t)pindex->nChainTx); ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex()); ret.pushKV("window_block_count", blockcount); if (blockcount > 0) { ret.pushKV("window_tx_count", nTxDiff); ret.pushKV("window_interval", nTimeDiff); if (nTimeDiff > 0) { ret.pushKV("txrate", ((double)nTxDiff) / nTimeDiff); } } return ret; } template<typename T> static T CalculateTruncatedMedian(std::vector<T>& scores) { size_t size = scores.size(); if (size == 0) { return 0; } std::sort(scores.begin(), scores.end()); if (size % 2 == 0) { return (scores[size / 2 - 1] + scores[size / 2]) / 2; } else { return scores[size / 2]; } } template<typename T> static inline bool SetHasKeys(const std::set<T>& set) {return false;} template<typename T, typename Tk, typename... Args> static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args) { return (set.count(key) != 0) || SetHasKeys(set, args...); } // outpoint (needed for the utxo index) + nHeight + fCoinBase static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool); static UniValue getblockstats(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) { throw std::runtime_error( "getblockstats hash_or_height ( stats )\n" "\nCompute per block statistics for a given window. All amounts are in satoshis.\n" "It won't work for some heights with pruning.\n" "It won't work without -txindex for utxo_size_inc, *fee or *feerate stats.\n" "\nArguments:\n" "1. \"hash_or_height\" (string or numeric, required) The block hash or height of the target block\n" "2. \"stats\" (array, optional) Values to plot, by default all values (see result below)\n" " [\n" " \"height\", (string, optional) Selected statistic\n" " \"time\", (string, optional) Selected statistic\n" " ,...\n" " ]\n" "\nResult:\n" "{ (json object)\n" " \"avgfee\": xxxxx, (numeric) Average fee in the block\n" " \"avgfeerate\": xxxxx, (numeric) Average feerate (in satoshis per virtual byte)\n" " \"avgtxsize\": xxxxx, (numeric) Average transaction size\n" " \"blockhash\": xxxxx, (string) The block hash (to check for potential reorgs)\n" " \"height\": xxxxx, (numeric) The height of the block\n" " \"ins\": xxxxx, (numeric) The number of inputs (excluding coinbase)\n" " \"maxfee\": xxxxx, (numeric) Maximum fee in the block\n" " \"maxfeerate\": xxxxx, (numeric) Maximum feerate (in satoshis per virtual byte)\n" " \"maxtxsize\": xxxxx, (numeric) Maximum transaction size\n" " \"medianfee\": xxxxx, (numeric) Truncated median fee in the block\n" " \"medianfeerate\": xxxxx, (numeric) Truncated median feerate (in satoshis per virtual byte)\n" " \"mediantime\": xxxxx, (numeric) The block median time past\n" " \"mediantxsize\": xxxxx, (numeric) Truncated median transaction size\n" " \"minfee\": xxxxx, (numeric) Minimum fee in the block\n" " \"minfeerate\": xxxxx, (numeric) Minimum feerate (in satoshis per virtual byte)\n" " \"mintxsize\": xxxxx, (numeric) Minimum transaction size\n" " \"outs\": xxxxx, (numeric) The number of outputs\n" " \"subsidy\": xxxxx, (numeric) The block subsidy\n" " \"swtotal_size\": xxxxx, (numeric) Total size of all segwit transactions\n" " \"swtotal_weight\": xxxxx, (numeric) Total weight of all segwit transactions divided by segwit scale factor (4)\n" " \"swtxs\": xxxxx, (numeric) The number of segwit transactions\n" " \"time\": xxxxx, (numeric) The block time\n" " \"total_out\": xxxxx, (numeric) Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])\n" " \"total_size\": xxxxx, (numeric) Total size of all non-coinbase transactions\n" " \"total_weight\": xxxxx, (numeric) Total weight of all non-coinbase transactions divided by segwit scale factor (4)\n" " \"totalfee\": xxxxx, (numeric) The fee total\n" " \"txs\": xxxxx, (numeric) The number of transactions (excluding coinbase)\n" " \"utxo_increase\": xxxxx, (numeric) The increase/decrease in the number of unspent outputs\n" " \"utxo_size_inc\": xxxxx, (numeric) The increase/decrease in size for the utxo index (not discounting op_return and similar)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'") + HelpExampleRpc("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'") ); } LOCK(cs_main); CBlockIndex* pindex; if (request.params[0].isNum()) { const int height = request.params[0].get_int(); const int current_tip = chainActive.Height(); if (height < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height)); } if (height > current_tip) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip)); } pindex = chainActive[height]; } else { const std::string strHash = request.params[0].get_str(); const uint256 hash(uint256S(strHash)); pindex = LookupBlockIndex(hash); if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } if (!chainActive.Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString())); } } assert(pindex != nullptr); std::set<std::string> stats; if (!request.params[1].isNull()) { const UniValue stats_univalue = request.params[1].get_array(); for (unsigned int i = 0; i < stats_univalue.size(); i++) { const std::string stat = stats_univalue[i].get_str(); stats.insert(stat); } } const CBlock block = GetBlockChecked(pindex); const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default) const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0; const bool do_medianfee = do_all || stats.count("medianfee") != 0; const bool do_medianfeerate = do_all || stats.count("medianfeerate") != 0; const bool loop_inputs = do_all || do_medianfee || do_medianfeerate || SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate"); const bool loop_outputs = do_all || loop_inputs || stats.count("total_out"); const bool do_calculate_size = do_mediantxsize || SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size"); const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "medianfeerate", "minfeerate", "maxfeerate"); const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight"); CAmount maxfee = 0; CAmount maxfeerate = 0; CAmount minfee = MAX_MONEY; CAmount minfeerate = MAX_MONEY; CAmount total_out = 0; CAmount totalfee = 0; int64_t inputs = 0; int64_t maxtxsize = 0; int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE; int64_t outputs = 0; int64_t swtotal_size = 0; int64_t swtotal_weight = 0; int64_t swtxs = 0; int64_t total_size = 0; int64_t total_weight = 0; int64_t utxo_size_inc = 0; std::vector<CAmount> fee_array; std::vector<CAmount> feerate_array; std::vector<int64_t> txsize_array; for (const auto& tx : block.vtx) { outputs += tx->vout.size(); CAmount tx_total_out = 0; if (loop_outputs) { for (const CTxOut& out : tx->vout) { tx_total_out += out.nValue; utxo_size_inc += GetSerializeSize(out, SER_NETWORK, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD; } } if (tx->IsCoinBase()) { continue; } inputs += tx->vin.size(); // Don't count coinbase's fake input total_out += tx_total_out; // Don't count coinbase reward int64_t tx_size = 0; if (do_calculate_size) { tx_size = tx->GetTotalSize(); if (do_mediantxsize) { txsize_array.push_back(tx_size); } maxtxsize = std::max(maxtxsize, tx_size); mintxsize = std::min(mintxsize, tx_size); total_size += tx_size; } int64_t weight = 0; if (do_calculate_weight) { weight = GetTransactionWeight(*tx); total_weight += weight; } if (do_calculate_sw && tx->HasWitness()) { ++swtxs; swtotal_size += tx_size; swtotal_weight += weight; } if (loop_inputs) { if (!g_txindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more of the selected stats requires -txindex enabled"); } CAmount tx_total_in = 0; for (const CTxIn& in : tx->vin) { CTransactionRef tx_in; uint256 hashBlock; if (!GetTransaction(in.prevout.hash, tx_in, Params().GetConsensus(), hashBlock, false)) { throw JSONRPCError(RPC_INTERNAL_ERROR, std::string("Unexpected internal error (tx index seems corrupt)")); } CTxOut prevoutput = tx_in->vout[in.prevout.n]; tx_total_in += prevoutput.nValue; utxo_size_inc -= GetSerializeSize(prevoutput, SER_NETWORK, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD; } CAmount txfee = tx_total_in - tx_total_out; assert(MoneyRange(txfee)); if (do_medianfee) { fee_array.push_back(txfee); } maxfee = std::max(maxfee, txfee); minfee = std::min(minfee, txfee); totalfee += txfee; // New feerate uses satoshis per virtual byte instead of per serialized byte CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0; if (do_medianfeerate) { feerate_array.push_back(feerate); } maxfeerate = std::max(maxfeerate, feerate); minfeerate = std::min(minfeerate, feerate); } } UniValue ret_all(UniValue::VOBJ); ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0); ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0); ret_all.pushKV("blockhash", pindex->GetBlockHash().GetHex()); ret_all.pushKV("height", (int64_t)pindex->nHeight); ret_all.pushKV("ins", inputs); ret_all.pushKV("maxfee", maxfee); ret_all.pushKV("maxfeerate", maxfeerate); ret_all.pushKV("maxtxsize", maxtxsize); ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array)); ret_all.pushKV("medianfeerate", CalculateTruncatedMedian(feerate_array)); ret_all.pushKV("mediantime", pindex->GetMedianTimePast()); ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array)); ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee); ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate); ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize); ret_all.pushKV("outs", outputs); ret_all.pushKV("subsidy", GetBlockSubsidy(pindex->nHeight, Params().GetConsensus())); ret_all.pushKV("swtotal_size", swtotal_size); ret_all.pushKV("swtotal_weight", swtotal_weight); ret_all.pushKV("swtxs", swtxs); ret_all.pushKV("time", pindex->GetBlockTime()); ret_all.pushKV("total_out", total_out); ret_all.pushKV("total_size", total_size); ret_all.pushKV("total_weight", total_weight); ret_all.pushKV("totalfee", totalfee); ret_all.pushKV("txs", (int64_t)block.vtx.size()); ret_all.pushKV("utxo_increase", outputs - inputs); ret_all.pushKV("utxo_size_inc", utxo_size_inc); if (do_all) { return ret_all; } UniValue ret(UniValue::VOBJ); for (const std::string& stat : stats) { const UniValue& value = ret_all[stat]; if (value.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic %s", stat)); } ret.pushKV(stat, value); } return ret; } static UniValue savemempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) { throw std::runtime_error( "savemempool\n" "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n" "\nExamples:\n" + HelpExampleCli("savemempool", "") + HelpExampleRpc("savemempool", "") ); } if (!g_is_mempool_loaded) { throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet"); } if (!DumpMempool()) { throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk"); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "blockchain", "getblockchaininfo", &getblockchaininfo, {} }, { "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} }, { "blockchain", "getblockstats", &getblockstats, {"hash_or_height", "stats"} }, { "blockchain", "getbestblockhash", &getbestblockhash, {} }, { "blockchain", "getblockcount", &getblockcount, {} }, { "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} }, { "blockchain", "getblockhash", &getblockhash, {"height"} }, { "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} }, { "blockchain", "getchaintips", &getchaintips, {} }, { "blockchain", "getdifficulty", &getdifficulty, {} }, { "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} }, { "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} }, { "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} }, { "blockchain", "getmempoolinfo", &getmempoolinfo, {} }, { "blockchain", "getrawmempool", &getrawmempool, {"verbose"} }, { "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} }, { "blockchain", "pruneblockchain", &pruneblockchain, {"height"} }, { "blockchain", "savemempool", &savemempool, {} }, { "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} }, { "blockchain", "preciousblock", &preciousblock, {"blockhash"} }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, {"blockhash"} }, { "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} }, { "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} }, { "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} }, { "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} }, { "hidden", "syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
#include "../include/virtual.h" Virtual::Virtual() {} ///////////// Virtual::~Virtual() {} ///////////// ///////////// ///////////// ///////////// ///////////// ///////////// ///////////// /////////////
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // This file implements the "bridge" between Java and C++ and enables // calling c++ rocksdb::ThreadStatus methods from Java side. #include <jni.h> #include "portal.h" #include "include/org_rocksdb_ThreadStatus.h" #include "rocksdb/thread_status.h" /* * Class: org_rocksdb_ThreadStatus * Method: getThreadTypeName * Signature: (B)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_getThreadTypeName( JNIEnv* env, jclass, jbyte jthread_type_value) { auto name = rocksdb::ThreadStatus::GetThreadTypeName( rocksdb::ThreadTypeJni::toCppThreadType(jthread_type_value)); return rocksdb::JniUtil::toJavaString(env, &name, true); } /* * Class: org_rocksdb_ThreadStatus * Method: getOperationName * Signature: (B)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_getOperationName( JNIEnv* env, jclass, jbyte joperation_type_value) { auto name = rocksdb::ThreadStatus::GetOperationName( rocksdb::OperationTypeJni::toCppOperationType(joperation_type_value)); return rocksdb::JniUtil::toJavaString(env, &name, true); } /* * Class: org_rocksdb_ThreadStatus * Method: microsToStringNative * Signature: (J)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_microsToStringNative( JNIEnv* env, jclass, jlong jmicros) { auto str = rocksdb::ThreadStatus::MicrosToString(static_cast<uint64_t>(jmicros)); return rocksdb::JniUtil::toJavaString(env, &str, true); } /* * Class: org_rocksdb_ThreadStatus * Method: getOperationStageName * Signature: (B)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_getOperationStageName( JNIEnv* env, jclass, jbyte joperation_stage_value) { auto name = rocksdb::ThreadStatus::GetOperationStageName( rocksdb::OperationStageJni::toCppOperationStage(joperation_stage_value)); return rocksdb::JniUtil::toJavaString(env, &name, true); } /* * Class: org_rocksdb_ThreadStatus * Method: getOperationPropertyName * Signature: (BI)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_getOperationPropertyName( JNIEnv* env, jclass, jbyte joperation_type_value, jint jindex) { auto name = rocksdb::ThreadStatus::GetOperationPropertyName( rocksdb::OperationTypeJni::toCppOperationType(joperation_type_value), static_cast<int>(jindex)); return rocksdb::JniUtil::toJavaString(env, &name, true); } /* * Class: org_rocksdb_ThreadStatus * Method: interpretOperationProperties * Signature: (B[J)Ljava/util/Map; */ jobject Java_org_rocksdb_ThreadStatus_interpretOperationProperties( JNIEnv* env, jclass, jbyte joperation_type_value, jlongArray joperation_properties) { //convert joperation_properties const jsize len = env->GetArrayLength(joperation_properties); const std::unique_ptr<uint64_t[]> op_properties(new uint64_t[len]); jlong* jop = env->GetLongArrayElements(joperation_properties, nullptr); if (jop == nullptr) { // exception thrown: OutOfMemoryError return nullptr; } for (jsize i = 0; i < len; i++) { op_properties[i] = static_cast<uint64_t>(jop[i]); } env->ReleaseLongArrayElements(joperation_properties, jop, JNI_ABORT); // call the function auto result = rocksdb::ThreadStatus::InterpretOperationProperties( rocksdb::OperationTypeJni::toCppOperationType(joperation_type_value), op_properties.get()); jobject jresult = rocksdb::HashMapJni::fromCppMap(env, &result); if (env->ExceptionCheck()) { // exception occurred return nullptr; } return jresult; } /* * Class: org_rocksdb_ThreadStatus * Method: getStateName * Signature: (B)Ljava/lang/String; */ jstring Java_org_rocksdb_ThreadStatus_getStateName( JNIEnv* env, jclass, jbyte jstate_type_value) { auto name = rocksdb::ThreadStatus::GetStateName( rocksdb::StateTypeJni::toCppStateType(jstate_type_value)); return rocksdb::JniUtil::toJavaString(env, &name, true); }
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> extern bool fWalletUnlockStakingOnly; AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case UnlockStaking: ui->stakingCheckBox->setChecked(true); ui->stakingCheckBox->show(); // fallthru case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { secureClearPassFields(); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); secureClearPassFields(); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("OLBITX will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your coins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockStaking: case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked(); QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockStaking: case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } void AskPassphraseDialog::secureClearPassFields() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); ui->passEdit1->clear(); ui->passEdit2->clear(); ui->passEdit3->clear(); }
// Copyright 2016-2018 Chris Conway (Koderz). All Rights Reserved. #include "RuntimeMeshComponentPlugin.h" #include "RuntimeMeshRendering.h" #include "RuntimeMeshSectionProxy.h" FRuntimeMeshVertexBuffer::FRuntimeMeshVertexBuffer() : VertexSize(-1), NumVertices(0), UsageFlags(EBufferUsageFlags::BUF_None) { } void FRuntimeMeshVertexBuffer::Reset(int32 InVertexSize, int32 InNumVertices, EUpdateFrequency InUpdateFrequency) { VertexSize = InVertexSize; NumVertices = InNumVertices; UsageFlags = InUpdateFrequency == EUpdateFrequency::Frequent ? BUF_Dynamic : BUF_Static; ReleaseResource(); InitResource(); } void FRuntimeMeshVertexBuffer::InitRHI() { if (VertexSize > 0 && NumVertices > 0) { // Create the vertex buffer FRHIResourceCreateInfo CreateInfo; VertexBufferRHI = RHICreateVertexBuffer(GetBufferSize(), UsageFlags, CreateInfo); } } /* Set the size of the vertex buffer */ void FRuntimeMeshVertexBuffer::SetNum(int32 NewVertexCount) { // Make sure we're not already the right size if (NewVertexCount != NumVertices) { NumVertices = NewVertexCount; // Rebuild resource ReleaseResource(); InitResource(); } } /* Set the data for the vertex buffer */ void FRuntimeMeshVertexBuffer::SetData(const TArray<uint8>& Data) { check(Data.Num() == GetBufferSize()); if (GetBufferSize() > 0) { check(VertexBufferRHI.IsValid()); // Lock the vertex buffer void* Buffer = RHILockVertexBuffer(VertexBufferRHI, 0, Data.Num(), RLM_WriteOnly); // Write the vertices to the vertex buffer FMemory::Memcpy(Buffer, Data.GetData(), Data.Num()); // Unlock the vertex buffer RHIUnlockVertexBuffer(VertexBufferRHI); } } FRuntimeMeshIndexBuffer::FRuntimeMeshIndexBuffer() : IndexSize(-1), NumIndices(0), UsageFlags(EBufferUsageFlags::BUF_None) { } void FRuntimeMeshIndexBuffer::Reset(int32 InIndexSize, int32 InNumIndices, EUpdateFrequency InUpdateFrequency) { IndexSize = InIndexSize; NumIndices = InNumIndices; UsageFlags = InUpdateFrequency == EUpdateFrequency::Frequent ? BUF_Dynamic : BUF_Static; ReleaseResource(); InitResource(); } void FRuntimeMeshIndexBuffer::InitRHI() { if (IndexSize > 0 && NumIndices > 0) { // Create the index buffer FRHIResourceCreateInfo CreateInfo; IndexBufferRHI = RHICreateIndexBuffer(IndexSize, GetBufferSize(), BUF_Dynamic, CreateInfo); } } /* Set the size of the index buffer */ void FRuntimeMeshIndexBuffer::SetNum(int32 NewIndexCount) { // Make sure we're not already the right size if (NewIndexCount != NumIndices) { NumIndices = NewIndexCount; // Rebuild resource ReleaseResource(); InitResource(); } } /* Set the data for the index buffer */ void FRuntimeMeshIndexBuffer::SetData(const TArray<uint8>& Data) { check(Data.Num() == GetBufferSize()); if (GetBufferSize() > 0) { check(IndexBufferRHI.IsValid()); // Lock the index buffer void* Buffer = RHILockIndexBuffer(IndexBufferRHI, 0, Data.Num(), RLM_WriteOnly); // Write the indices to the vertex buffer FMemory::Memcpy(Buffer, Data.GetData(), Data.Num()); // Unlock the index buffer RHIUnlockIndexBuffer(IndexBufferRHI); } } FRuntimeMeshVertexFactory::FRuntimeMeshVertexFactory(FRuntimeMeshSectionProxy* InSectionParent) : SectionParent(InSectionParent) { } /** Init function that can be called on any thread, and will do the right thing (enqueue command if called on main thread) */ void FRuntimeMeshVertexFactory::Init(FLocalVertexFactory::FDataType VertexStructure) { if (IsInRenderingThread()) { SetData(VertexStructure); } else { // Send the command to the render thread ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER( InitRuntimeMeshVertexFactory, FRuntimeMeshVertexFactory*, VertexFactory, this, FLocalVertexFactory::FDataType, VertexStructure, VertexStructure, { VertexFactory->Init(VertexStructure); }); } } /* Gets the section visibility for static sections */ uint64 FRuntimeMeshVertexFactory::GetStaticBatchElementVisibility(const class FSceneView& View, const struct FMeshBatch* Batch) const { return SectionParent->ShouldRender(); }
#include <cassert> #include <chrono> #include "../../../include/meanshift.h" #include "../../../include/container_io.h" #include "../constants_3d.h" int main(int argc, char *argv[]){ const float bandwidth = std::stof(argv[1]); const float radius = std::stof(argv[2]); const float min_distance = std::stof(argv[3]); const float eps_to_real = std::stof(argv[4]); // Hyperparameters constexpr auto niter = constants::niter; constexpr auto eps = constants::case_1000::eps; // I/O constexpr auto num_points = constants::case_1000::num_points; constexpr auto dim = constants::dim; constexpr auto num_centroids = constants::num_centroids; const auto data_path = constants::case_1000::data_path; const auto centroids_path = constants::case_1000::centroids_path; mean_shift::mat<float, num_points, dim> data = mean_shift::io::load_csv<float, num_points, dim>(data_path, ','); const mean_shift::mat<float, num_centroids, dim> real_centroids = mean_shift::io::load_csv<float, num_centroids, dim>(centroids_path, ','); const std::vector<mean_shift::vec<float, dim>> centroids = mean_shift::seq::cluster_points<float, num_points, dim>(data, niter, bandwidth, radius, min_distance, eps); assert(centroids.size() == num_centroids); bool are_close = mean_shift::are_close_to_real<float, num_centroids, dim>(centroids, real_centroids, eps_to_real); assert(are_close); return 0; }
// peter 02:20 20151219 #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdio.h> using namespace cv; static void help() { printf("\n1. This program demonstrates OpenCV drawing and text output functions.\n" "Usage:\n" " ./drawing\n"); } static Scalar randomColor(RNG& rng) { int icolor = (unsigned)rng; return Scalar(icolor&255, (icolor>>8)&255, (icolor>>16)&255); } int main() { help(); char wndname[] = "Drawing Demo"; // const int NUMBER = 100; const int NUMBER = 4; const int DELAY = 5; int lineType = CV_AA; // change it to 8 to see non-antialiased graphics // int i, width = 1000, height = 700; int i, width = 400, height = 400; // int i, width = 1024, height = 720; int x1 = -width/2, x2 = width*3/2, y1 = -height/2, y2 = height*3/2; RNG rng(0xFFFFFFFF); // step 1: create a window with specified width and height (1000,700) and title name Mat image = Mat::zeros(height, width, CV_8UC3); imshow(wndname, image); waitKey(DELAY); #if 1 // Size textsize = getTextSize("OpenCV forever!", FONT_HERSHEY_COMPLEX, 3, 5, 0); Size textsize = getTextSize("forever!", CV_FONT_HERSHEY_COMPLEX, 3, 5, 0); Point org((width - textsize.width)/2, (height - textsize.height)/2); Mat image2; for( i = 0; i < 255; i += 2 ) { // image2 = image - Scalar::all(i); image2 = image ; // putText(image2, "Ya OpenCV forever!", org, FONT_HERSHEY_COMPLEX, 3, Scalar(i, i, 255), 5, lineType); putText(image2, "Ya !", org, FONT_HERSHEY_COMPLEX, 3, Scalar(i, i, 255), 5, lineType); imshow(wndname, image2); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i < NUMBER; i++) { Point pt1, pt2; pt1.x = rng.uniform(x1, x2); pt1.y = rng.uniform(y1, y2); pt2.x = rng.uniform(x1, x2); pt2.y = rng.uniform(y1, y2); // api help on <url:http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html> line( image, pt1, pt2, randomColor(rng), rng.uniform(1,10), lineType ); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i < NUMBER; i++) { Point pt1, pt2; pt1.x = rng.uniform(x1, x2); pt1.y = rng.uniform(y1, y2); pt2.x = rng.uniform(x1, x2); pt2.y = rng.uniform(y1, y2); int thickness = rng.uniform(-3, 10); rectangle( image, pt1, pt2, randomColor(rng), MAX(thickness, -1), lineType ); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i < NUMBER; i++) { Point center; center.x = rng.uniform(x1, x2); center.y = rng.uniform(y1, y2); Size axes; axes.width = rng.uniform(0, 200); axes.height = rng.uniform(0, 200); double angle = rng.uniform(0, 180); ellipse( image, center, axes, angle, angle - 100, angle + 200, randomColor(rng), rng.uniform(-1,9), lineType ); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i< NUMBER; i++) { Point pt[2][3]; pt[0][0].x = rng.uniform(x1, x2); pt[0][0].y = rng.uniform(y1, y2); pt[0][1].x = rng.uniform(x1, x2); pt[0][1].y = rng.uniform(y1, y2); pt[0][2].x = rng.uniform(x1, x2); pt[0][2].y = rng.uniform(y1, y2); pt[1][0].x = rng.uniform(x1, x2); pt[1][0].y = rng.uniform(y1, y2); pt[1][1].x = rng.uniform(x1, x2); pt[1][1].y = rng.uniform(y1, y2); pt[1][2].x = rng.uniform(x1, x2); pt[1][2].y = rng.uniform(y1, y2); const Point* ppt[2] = {pt[0], pt[1]}; int npt[] = {3, 3}; polylines(image, ppt, npt, 2, true, randomColor(rng), rng.uniform(1,10), lineType); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i< NUMBER; i++) { Point pt[2][3]; pt[0][0].x = rng.uniform(x1, x2); pt[0][0].y = rng.uniform(y1, y2); pt[0][1].x = rng.uniform(x1, x2); pt[0][1].y = rng.uniform(y1, y2); pt[0][2].x = rng.uniform(x1, x2); pt[0][2].y = rng.uniform(y1, y2); pt[1][0].x = rng.uniform(x1, x2); pt[1][0].y = rng.uniform(y1, y2); pt[1][1].x = rng.uniform(x1, x2); pt[1][1].y = rng.uniform(y1, y2); pt[1][2].x = rng.uniform(x1, x2); pt[1][2].y = rng.uniform(y1, y2); const Point* ppt[2] = {pt[0], pt[1]}; int npt[] = {3, 3}; fillPoly(image, ppt, npt, 2, randomColor(rng), lineType); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 0; i < NUMBER; i++) { Point center; center.x = rng.uniform(x1, x2); center.y = rng.uniform(y1, y2); circle(image, center, rng.uniform(0, 300), randomColor(rng), rng.uniform(-1, 9), lineType); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif #if 0 for (i = 1; i < NUMBER; i++) { Point org; org.x = rng.uniform(x1, x2); org.y = rng.uniform(y1, y2); putText(image, "Testing text rendering", org, rng.uniform(0,8), rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType); imshow(wndname, image); if(waitKey(DELAY) >= 0) return 0; } #endif waitKey(); return 0; } #ifdef _EiC main(1,"drawing.c"); #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_calloc_53d.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-53d.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_calloc_53 { #ifndef OMITBAD void bad_sink_d(wchar_t * data) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2B_sink_d(wchar_t * data) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } /* goodB2G uses the BadSource with the GoodSink */ void goodB2G_sink_d(wchar_t * data) { /* FIX: Free memory using free() */ free(data); } #endif /* OMITGOOD */ } // close namespace
//------------------------------------------------------------------------------ // File: MType.cpp // // Desc: DirectShow base classes - implements a class that holds and // manages media type information. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // helper class that derived pin objects can use to compare media // types etc. Has same data members as the struct AM_MEDIA_TYPE defined // in the streams IDL file, but also has (non-virtual) functions #include "../BaseClasses.h" #include <mmreg.h> CMediaType::~CMediaType(){ FreeMediaType(*this); } CMediaType::CMediaType() { InitMediaType(); } CMediaType::CMediaType(const GUID * type) { InitMediaType(); majortype = *type; } // copy constructor does a deep copy of the format block CMediaType::CMediaType(const AM_MEDIA_TYPE& rt, __out_opt HRESULT* phr) { HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr) && (NULL != phr)) { *phr = hr; } } CMediaType::CMediaType(const CMediaType& rt, __out_opt HRESULT* phr) { HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr) && (NULL != phr)) { *phr = hr; } } // this class inherits publicly from AM_MEDIA_TYPE so the compiler could generate // the following assignment operator itself, however it could introduce some // memory conflicts and leaks in the process because the structure contains // a dynamically allocated block (pbFormat) which it will not copy correctly CMediaType& CMediaType::operator=(const AM_MEDIA_TYPE& rt) { Set(rt); return *this; } CMediaType& CMediaType::operator=(const CMediaType& rt) { *this = (AM_MEDIA_TYPE &) rt; return *this; } BOOL CMediaType::operator == (const CMediaType& rt) const { // I don't believe we need to check sample size or // temporal compression flags, since I think these must // be represented in the type, subtype and format somehow. They // are pulled out as separate flags so that people who don't understand // the particular format representation can still see them, but // they should duplicate information in the format block. return ((IsEqualGUID(majortype,rt.majortype) == TRUE) && (IsEqualGUID(subtype,rt.subtype) == TRUE) && (IsEqualGUID(formattype,rt.formattype) == TRUE) && (cbFormat == rt.cbFormat) && ( (cbFormat == 0) || pbFormat != NULL && rt.pbFormat != NULL && (memcmp(pbFormat, rt.pbFormat, cbFormat) == 0))); } BOOL CMediaType::operator != (const CMediaType& rt) const { /* Check to see if they are equal */ if (*this == rt) { return FALSE; } return TRUE; } HRESULT CMediaType::Set(const CMediaType& rt) { return Set((AM_MEDIA_TYPE &) rt); } HRESULT CMediaType::Set(const AM_MEDIA_TYPE& rt) { if (&rt != this) { FreeMediaType(*this); HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr)) { return E_OUTOFMEMORY; } } return S_OK; } BOOL CMediaType::IsValid() const { return (!IsEqualGUID(majortype,GUID_NULL)); } void CMediaType::SetType(const GUID* ptype) { majortype = *ptype; } void CMediaType::SetSubtype(const GUID* ptype) { subtype = *ptype; } ULONG CMediaType::GetSampleSize() const { if (IsFixedSize()) { return lSampleSize; } else { return 0; } } void CMediaType::SetSampleSize(ULONG sz) { if (sz == 0) { SetVariableSize(); } else { bFixedSizeSamples = TRUE; lSampleSize = sz; } } void CMediaType::SetVariableSize() { bFixedSizeSamples = FALSE; } void CMediaType::SetTemporalCompression(BOOL bCompressed) { bTemporalCompression = bCompressed; } BOOL CMediaType::SetFormat(__in_bcount(cb) BYTE * pformat, ULONG cb) { if (NULL == AllocFormatBuffer(cb)) return(FALSE); ASSERT(pbFormat); memcpy(pbFormat, pformat, cb); return(TRUE); } // set the type of the media type format block, this type defines what you // will actually find in the format pointer. For example FORMAT_VideoInfo or // FORMAT_WaveFormatEx. In the future this may be an interface pointer to a // property set. Before sending out media types this should be filled in. void CMediaType::SetFormatType(const GUID *pformattype) { formattype = *pformattype; } // reset the format buffer void CMediaType::ResetFormatBuffer() { if (cbFormat) { CoTaskMemFree((PVOID)pbFormat); } cbFormat = 0; pbFormat = NULL; } // allocate length bytes for the format and return a read/write pointer // If we cannot allocate the new block of memory we return NULL leaving // the original block of memory untouched (as does ReallocFormatBuffer) BYTE* CMediaType::AllocFormatBuffer(ULONG length) { ASSERT(length); // do the types have the same buffer size if (cbFormat == length) { return pbFormat; } // allocate the new format buffer BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); if (pNewFormat == NULL) { if (length <= cbFormat) return pbFormat; //reuse the old block anyway. return NULL; } // delete the old format if (cbFormat != 0) { ASSERT(pbFormat); CoTaskMemFree((PVOID)pbFormat); } cbFormat = length; pbFormat = pNewFormat; return pbFormat; } // reallocate length bytes for the format and return a read/write pointer // to it. We keep as much information as we can given the new buffer size // if this fails the original format buffer is left untouched. The caller // is responsible for ensuring the size of memory required is non zero BYTE* CMediaType::ReallocFormatBuffer(ULONG length) { ASSERT(length); // do the types have the same buffer size if (cbFormat == length) { return pbFormat; } // allocate the new format buffer BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); if (pNewFormat == NULL) { if (length <= cbFormat) return pbFormat; //reuse the old block anyway. return NULL; } // copy any previous format (or part of if new is smaller) // delete the old format and replace with the new one if (cbFormat != 0) { ASSERT(pbFormat); memcpy(pNewFormat,pbFormat,min(length,cbFormat)); CoTaskMemFree((PVOID)pbFormat); } cbFormat = length; pbFormat = pNewFormat; return pNewFormat; } // initialise a media type structure void CMediaType::InitMediaType() { ZeroMemory((PVOID)this, sizeof(*this)); lSampleSize = 1; bFixedSizeSamples = TRUE; } // a partially specified media type can be passed to IPin::Connect // as a constraint on the media type used in the connection. // the type, subtype or format type can be null. BOOL CMediaType::IsPartiallySpecified(void) const { if ((majortype == GUID_NULL) || (formattype == GUID_NULL)) { return TRUE; } else { return FALSE; } } BOOL CMediaType::MatchesPartial(const CMediaType* ppartial) const { if ((ppartial->majortype != GUID_NULL) && (majortype != ppartial->majortype)) { return FALSE; } if ((ppartial->subtype != GUID_NULL) && (subtype != ppartial->subtype)) { return FALSE; } if (ppartial->formattype != GUID_NULL) { // if the format block is specified then it must match exactly if (formattype != ppartial->formattype) { return FALSE; } if (cbFormat != ppartial->cbFormat) { return FALSE; } if ((cbFormat != 0) && (memcmp(pbFormat, ppartial->pbFormat, cbFormat) != 0)) { return FALSE; } } return TRUE; } // general purpose function to delete a heap allocated AM_MEDIA_TYPE structure // which is useful when calling IEnumMediaTypes::Next as the interface // implementation allocates the structures which you must later delete // the format block may also be a pointer to an interface to release void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt) { // allow NULL pointers for coding simplicity if (pmt == NULL) { return; } FreeMediaType(*pmt); CoTaskMemFree((PVOID)pmt); } // this also comes in useful when using the IEnumMediaTypes interface so // that you can copy a media type, you can do nearly the same by creating // a CMediaType object but as soon as it goes out of scope the destructor // will delete the memory it allocated (this takes a copy of the memory) AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc) { ASSERT(pSrc); // Allocate a block of memory for the media type AM_MEDIA_TYPE *pMediaType = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)); if (pMediaType == NULL) { return NULL; } // Copy the variable length format block HRESULT hr = CopyMediaType(pMediaType,pSrc); if (FAILED(hr)) { CoTaskMemFree((PVOID)pMediaType); return NULL; } return pMediaType; } // Copy 1 media type to another HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource) { // We'll leak if we copy onto one that already exists - there's one // case we can check like that - copying to itself. ASSERT(pmtSource != pmtTarget); *pmtTarget = *pmtSource; if (pmtSource->cbFormat != 0) { ASSERT(pmtSource->pbFormat != NULL); pmtTarget->pbFormat = (PBYTE)CoTaskMemAlloc(pmtSource->cbFormat); if (pmtTarget->pbFormat == NULL) { pmtTarget->cbFormat = 0; return E_OUTOFMEMORY; } else { CopyMemory((PVOID)pmtTarget->pbFormat, (PVOID)pmtSource->pbFormat, pmtTarget->cbFormat); } } if (pmtTarget->pUnk != NULL) { pmtTarget->pUnk->AddRef(); } return S_OK; } // Free an existing media type (ie free resources it holds) void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE& mt) { if (mt.cbFormat != 0) { CoTaskMemFree((PVOID)mt.pbFormat); // Strictly unnecessary but tidier mt.cbFormat = 0; mt.pbFormat = NULL; } if (mt.pUnk != NULL) { mt.pUnk->Release(); mt.pUnk = NULL; } } // Initialize a media type from a WAVEFORMATEX STDAPI CreateAudioMediaType( const WAVEFORMATEX *pwfx, __out AM_MEDIA_TYPE *pmt, BOOL bSetFormat ) { pmt->majortype = MEDIATYPE_Audio; if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { pmt->subtype = ((PWAVEFORMATEXTENSIBLE)pwfx)->SubFormat; } else { pmt->subtype = FOURCCMap(pwfx->wFormatTag); } pmt->formattype = FORMAT_WaveFormatEx; pmt->bFixedSizeSamples = TRUE; pmt->bTemporalCompression = FALSE; pmt->lSampleSize = pwfx->nBlockAlign; pmt->pUnk = NULL; if (bSetFormat) { if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { pmt->cbFormat = sizeof(WAVEFORMATEX); } else { pmt->cbFormat = sizeof(WAVEFORMATEX) + pwfx->cbSize; } pmt->pbFormat = (PBYTE)CoTaskMemAlloc(pmt->cbFormat); if (pmt->pbFormat == NULL) { return E_OUTOFMEMORY; } if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { CopyMemory(pmt->pbFormat, pwfx, sizeof(PCMWAVEFORMAT)); ((WAVEFORMATEX *)pmt->pbFormat)->cbSize = 0; } else { CopyMemory(pmt->pbFormat, pwfx, pmt->cbFormat); } } return S_OK; } // eliminate very many spurious warnings from MS compiler #pragma warning(disable:4514)
#include <iostream> #include <sstream> #include <cctype> #include <algorithm> using namespace std; int main() { string s; getline(cin, s); bool seen[26]; fill_n(seen, 26, false); stringstream ss; for (string::const_iterator it = s.begin(); it != s.end(); ++it) { switch (*it) { case 'A': case 'E': case 'I': case 'O': case 'U': break; default: if (isupper(*it)) { if (!seen[*it-'A']) { seen[*it-'A'] = true; ss << *it; } } else { ss << *it; } } } ostringstream oss; ss >> s; oss << s; while (ss >> s) { if (isupper(s[0])) { oss << ' '; } oss << s; } cout << oss.str() << endl; return 0; }
// This source file is part of Epoxy licensed under the MIT License. // See LICENSE.md file for details. #include "code_gen.h" #include "version.h" #include <inja.hpp> #include <sstream> namespace epoxy { CodeGen::CodeGen(std::string template_data) : template_data_(std::move(template_data)) {} CodeGen::~CodeGen() = default; static std::string GetEpoxyVersion() { std::stringstream stream; stream << EPOXY_VERSION_MAJOR << "." << EPOXY_VERSION_MINOR << "." << EPOXY_VERSION_PATCH; return stream.str(); } static nlohmann::json CreateJSONTemplateData( const std::vector<Namespace>& namespaces) { nlohmann::json ns_data; ns_data["epoxy_version"] = GetEpoxyVersion(); for (const auto& ns : namespaces) { ns_data["namespaces"].push_back(ns.GetJSONObject()); } return ns_data; } static std::string TypeToDartFFIType(const std::string& type) { if (type == "void") { return "Void"; } if (type == "int8_t") { return "Int8"; } if (type == "int16_t") { return "Int16"; } if (type == "int32_t") { return "Int32"; } if (type == "int64_t") { return "Int64"; } if (type == "uint8_t") { return "Uint8"; } if (type == "uint16_t") { return "Uint16"; } if (type == "uint32_t") { return "Uint32"; } if (type == "uint64_t") { return "Uint64"; } if (type == "double") { return "Double"; } if (type == "float") { return "Float"; } return "unknown"; } static std::string TypeToDartType(const std::string& type) { if (type == "void") { return "void"; } if (type == "int8_t") { return "int"; } if (type == "int16_t") { return "int"; } if (type == "int32_t") { return "int"; } if (type == "int64_t") { return "int"; } if (type == "uint8_t") { return "int"; } if (type == "uint16_t") { return "int"; } if (type == "uint32_t") { return "int"; } if (type == "uint64_t") { return "int"; } if (type == "double") { return "double"; } if (type == "float") { return "double"; } return "unknown"; } CodeGen::RenderResult CodeGen::Render( const std::vector<Namespace>& namespaces) const { inja::Environment env; env.set_trim_blocks(true); env.set_lstrip_blocks(true); env.add_callback("dart_ffi_type", 1u, [](inja::Arguments& args) { return TypeToDartFFIType(args.at(0u)->get<std::string>()); }); env.add_callback("dart_type", 1u, [](inja::Arguments& args) { return TypeToDartType(args.at(0u)->get<std::string>()); }); try { auto render = env.render(template_data_.data(), CreateJSONTemplateData(namespaces)); return {render, std::nullopt}; } catch (std::exception e) { return {std::nullopt, e.what()}; } } std::string CodeGen::GenerateTemplateDataJSON( const std::vector<Namespace>& namespaces) const { return CreateJSONTemplateData(namespaces).dump(); } } // namespace epoxy
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/systemui/statusbar/policy/AccessibilityContentDescriptions.h" #include "../R.h" using Elastos::Droid::SystemUI::R; namespace Elastos { namespace Droid { namespace SystemUI { namespace StatusBar { namespace Policy { const Int32 AccessibilityContentDescriptions::PHONE_SIGNAL_STRENGTH[5] = { R::string::accessibility_no_phone, R::string::accessibility_phone_one_bar, R::string::accessibility_phone_two_bars, R::string::accessibility_phone_three_bars, R::string::accessibility_phone_signal_full }; const Int32 AccessibilityContentDescriptions::DATA_CONNECTION_STRENGTH[5] = { R::string::accessibility_no_data, R::string::accessibility_data_one_bar, R::string::accessibility_data_two_bars, R::string::accessibility_data_three_bars, R::string::accessibility_data_signal_full }; const Int32 AccessibilityContentDescriptions::WIFI_CONNECTION_STRENGTH[5] = { R::string::accessibility_no_wifi, R::string::accessibility_wifi_one_bar, R::string::accessibility_wifi_two_bars, R::string::accessibility_wifi_three_bars, R::string::accessibility_wifi_signal_full }; const Int32 AccessibilityContentDescriptions::WIMAX_CONNECTION_STRENGTH[5] = { R::string::accessibility_no_wimax, R::string::accessibility_wimax_one_bar, R::string::accessibility_wimax_two_bars, R::string::accessibility_wimax_three_bars, R::string::accessibility_wimax_signal_full }; } // namespace Policy } // namespace StatusBar } // namespace SystemUI } // namespace Droid } // namespace Elastos
/* * Copyright (C) 2018 The Android Open Source Project * * 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 <algorithm> #include <map> #include <random> #include <string> #include "perfetto/base/logging.h" #include "perfetto/ext/base/optional.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "protos/perfetto/common/descriptor.pbzero.h" #include "protos/perfetto/trace_processor/trace_processor.pbzero.h" #include "src/base/test/utils.h" #include "test/gtest_and_gmock.h" namespace perfetto { namespace trace_processor { namespace { constexpr size_t kMaxChunkSize = 4 * 1024 * 1024; TEST(TraceProcessorCustomConfigTest, SkipInternalMetricsMatchingMountPath) { auto config = Config(); config.skip_builtin_metric_paths = {"android/"}; auto processor = TraceProcessor::CreateInstance(config); processor->NotifyEndOfFile(); // Check that andorid metrics have not been loaded. auto it = processor->ExecuteQuery( "select count(*) from trace_metrics " "where name = 'android_cpu';"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 0); // Check that other metrics have been loaded. it = processor->ExecuteQuery( "select count(*) from trace_metrics " "where name = 'trace_metadata';"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 1); } TEST(TraceProcessorCustomConfigTest, EmptyStringSkipsAllMetrics) { auto config = Config(); config.skip_builtin_metric_paths = {""}; auto processor = TraceProcessor::CreateInstance(config); processor->NotifyEndOfFile(); // Check that other metrics have been loaded. auto it = processor->ExecuteQuery( "select count(*) from trace_metrics " "where name = 'trace_metadata';"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 0); } TEST(TraceProcessorCustomConfigTest, HandlesMalformedMountPath) { auto config = Config(); config.skip_builtin_metric_paths = {"androi"}; auto processor = TraceProcessor::CreateInstance(config); processor->NotifyEndOfFile(); // Check that andorid metrics have been loaded. auto it = processor->ExecuteQuery( "select count(*) from trace_metrics " "where name = 'android_cpu';"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 1); } class TraceProcessorIntegrationTest : public ::testing::Test { public: TraceProcessorIntegrationTest() : processor_(TraceProcessor::CreateInstance(Config())) {} protected: util::Status LoadTrace(const char* name, size_t min_chunk_size = 512, size_t max_chunk_size = kMaxChunkSize) { EXPECT_LE(min_chunk_size, max_chunk_size); base::ScopedFstream f(fopen( base::GetTestDataPath(std::string("test/data/") + name).c_str(), "rb")); std::minstd_rand0 rnd_engine(0); std::uniform_int_distribution<size_t> dist(min_chunk_size, max_chunk_size); while (!feof(*f)) { size_t chunk_size = dist(rnd_engine); std::unique_ptr<uint8_t[]> buf(new uint8_t[chunk_size]); auto rsize = fread(reinterpret_cast<char*>(buf.get()), 1, chunk_size, *f); auto status = processor_->Parse(std::move(buf), rsize); if (!status.ok()) return status; } processor_->NotifyEndOfFile(); return util::OkStatus(); } Iterator Query(const std::string& query) { return processor_->ExecuteQuery(query.c_str()); } TraceProcessor* Processor() { return processor_.get(); } size_t RestoreInitialTables() { return processor_->RestoreInitialTables(); } private: std::unique_ptr<TraceProcessor> processor_; }; TEST_F(TraceProcessorIntegrationTest, AndroidSchedAndPs) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb").ok()); auto it = Query( "select count(*), max(ts) - min(ts) from sched " "where dur != 0 and utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 139787); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 19684308497); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, TraceBounds) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb").ok()); auto it = Query("select start_ts, end_ts from trace_bounds"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 81473009948313); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 81492700784311); ASSERT_FALSE(it.Next()); } // Tests that the duration of the last slice is accounted in the computation // of the trace boundaries. Linux ftraces tend to hide this problem because // after the last sched_switch there's always a "wake" event which causes the // raw table to fix the bounds. TEST_F(TraceProcessorIntegrationTest, TraceBoundsUserspaceOnly) { ASSERT_TRUE(LoadTrace("sfgate.json").ok()); auto it = Query("select start_ts, end_ts from trace_bounds"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 2213649212614000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 2213689745140000); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, Hash) { auto it = Query("select HASH()"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, static_cast<int64_t>(0xcbf29ce484222325)); it = Query("select HASH('test')"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, static_cast<int64_t>(0xf9e6e6ef197c2b25)); it = Query("select HASH('test', 1)"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, static_cast<int64_t>(0xa9cb070fdc15f7a4)); } #if !PERFETTO_BUILDFLAG(PERFETTO_LLVM_DEMANGLE) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #define MAYBE_Demangle DISABLED_Demangle #else #define MAYBE_Demangle Demangle #endif TEST_F(TraceProcessorIntegrationTest, MAYBE_Demangle) { auto it = Query("select DEMANGLE('_Znwm')"); ASSERT_TRUE(it.Next()); EXPECT_STRCASEEQ(it.Get(0).string_value, "operator new(unsigned long)"); it = Query("select DEMANGLE('_ZN3art6Thread14CreateCallbackEPv')"); ASSERT_TRUE(it.Next()); EXPECT_STRCASEEQ(it.Get(0).string_value, "art::Thread::CreateCallback(void*)"); it = Query("select DEMANGLE('test')"); ASSERT_TRUE(it.Next()); EXPECT_TRUE(it.Get(0).is_null()); } #if !PERFETTO_BUILDFLAG(PERFETTO_LLVM_DEMANGLE) #define MAYBE_DemangleRust DISABLED_DemangleRust #else #define MAYBE_DemangleRust DemangleRust #endif TEST_F(TraceProcessorIntegrationTest, MAYBE_DemangleRust) { auto it = Query( "select DEMANGLE(" "'_RNvNvMs0_NtNtNtCsg1Z12QU66Yk_3std3sys4unix6threadNtB7_" "6Thread3new12thread_start')"); ASSERT_TRUE(it.Next()); EXPECT_STRCASEEQ(it.Get(0).string_value, "<std::sys::unix::thread::Thread>::new::thread_start"); it = Query("select DEMANGLE('_RNvCsdV139EorvfX_14keystore2_main4main')"); ASSERT_TRUE(it.Next()); ASSERT_STRCASEEQ(it.Get(0).string_value, "keystore2_main::main"); it = Query("select DEMANGLE('_R')"); ASSERT_TRUE(it.Next()); ASSERT_TRUE(it.Get(0).is_null()); } #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) TEST_F(TraceProcessorIntegrationTest, Sfgate) { ASSERT_TRUE(LoadTrace("sfgate.json", strlen("{\"traceEvents\":[")).ok()); auto it = Query( "select count(*), max(ts) - min(ts) " "from slice s inner join thread_track t " "on s.track_id = t.id where utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 39828); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 40532506000); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, UnsortedTrace) { ASSERT_TRUE( LoadTrace("unsorted_trace.json", strlen("{\"traceEvents\":[")).ok()); auto it = Query("select ts, depth from slice order by ts"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 50000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 0); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 100000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 1); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, SerializeMetricDescriptors) { std::vector<uint8_t> desc_set_bytes = Processor()->GetMetricDescriptors(); protos::pbzero::DescriptorSet::Decoder desc_set(desc_set_bytes.data(), desc_set_bytes.size()); ASSERT_TRUE(desc_set.has_descriptors()); int trace_metrics_count = 0; for (auto desc = desc_set.descriptors(); desc; ++desc) { protos::pbzero::DescriptorProto::Decoder proto_desc(*desc); if (proto_desc.name().ToStdString() == ".perfetto.protos.TraceMetrics") { ASSERT_TRUE(proto_desc.has_field()); trace_metrics_count++; } } // There should be exactly one definition of TraceMetrics. This can be not // true if we're not deduping descriptors properly. ASSERT_EQ(trace_metrics_count, 1); } TEST_F(TraceProcessorIntegrationTest, ComputeMetricsFormattedExtension) { std::string metric_output; util::Status status = Processor()->ComputeMetricText( std::vector<std::string>{"test_chrome_metric"}, TraceProcessor::MetricResultFormat::kProtoText, &metric_output); ASSERT_TRUE(status.ok()); // Extension fields are output as [fully.qualified.name]. ASSERT_EQ(metric_output, "[perfetto.protos.test_chrome_metric] {\n" " test_value: 1\n" "}"); } TEST_F(TraceProcessorIntegrationTest, ComputeMetricsFormattedNoExtension) { std::string metric_output; util::Status status = Processor()->ComputeMetricText( std::vector<std::string>{"trace_metadata"}, TraceProcessor::MetricResultFormat::kProtoText, &metric_output); ASSERT_TRUE(status.ok()); // Check that metric result starts with trace_metadata field. Since this is // not an extension field, the field name is not fully qualified. ASSERT_TRUE(metric_output.rfind("trace_metadata {") == 0); } // TODO(hjd): Add trace to test_data. TEST_F(TraceProcessorIntegrationTest, DISABLED_AndroidBuildTrace) { ASSERT_TRUE(LoadTrace("android_build_trace.json", strlen("[\n{")).ok()); } TEST_F(TraceProcessorIntegrationTest, DISABLED_Clusterfuzz14357) { ASSERT_FALSE(LoadTrace("clusterfuzz_14357", 4096).ok()); } #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) TEST_F(TraceProcessorIntegrationTest, Clusterfuzz14730) { ASSERT_TRUE(LoadTrace("clusterfuzz_14730", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz14753) { ASSERT_TRUE(LoadTrace("clusterfuzz_14753", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz14762) { ASSERT_TRUE(LoadTrace("clusterfuzz_14762", 4096 * 1024).ok()); auto it = Query("select sum(value) from stats where severity = 'error';"); ASSERT_TRUE(it.Next()); ASSERT_GT(it.Get(0).long_value, 0); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz14767) { ASSERT_TRUE(LoadTrace("clusterfuzz_14767", 4096 * 1024).ok()); auto it = Query("select sum(value) from stats where severity = 'error';"); ASSERT_TRUE(it.Next()); ASSERT_GT(it.Get(0).long_value, 0); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz14799) { ASSERT_TRUE(LoadTrace("clusterfuzz_14799", 4096 * 1024).ok()); auto it = Query("select sum(value) from stats where severity = 'error';"); ASSERT_TRUE(it.Next()); ASSERT_GT(it.Get(0).long_value, 0); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz15252) { ASSERT_TRUE(LoadTrace("clusterfuzz_15252", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, Clusterfuzz17805) { // This trace is garbage but is detected as a systrace. However, it should // still parse successfully as we try to be graceful with encountering random // data in systrace as they can have arbitrary print events from the kernel. ASSERT_TRUE(LoadTrace("clusterfuzz_17805", 4096).ok()); } // Failing on DCHECKs during import because the traces aren't really valid. #if PERFETTO_DCHECK_IS_ON() #define MAYBE_Clusterfuzz20215 DISABLED_Clusterfuzz20215 #define MAYBE_Clusterfuzz20292 DISABLED_Clusterfuzz20292 #define MAYBE_Clusterfuzz21178 DISABLED_Clusterfuzz21178 #define MAYBE_Clusterfuzz21890 DISABLED_Clusterfuzz21890 #define MAYBE_Clusterfuzz23053 DISABLED_Clusterfuzz23053 #define MAYBE_Clusterfuzz28338 DISABLED_Clusterfuzz28338 #define MAYBE_Clusterfuzz28766 DISABLED_Clusterfuzz28766 #else // PERFETTO_DCHECK_IS_ON() #define MAYBE_Clusterfuzz20215 Clusterfuzz20215 #define MAYBE_Clusterfuzz20292 Clusterfuzz20292 #define MAYBE_Clusterfuzz21178 Clusterfuzz21178 #define MAYBE_Clusterfuzz21890 Clusterfuzz21890 #define MAYBE_Clusterfuzz23053 Clusterfuzz23053 #define MAYBE_Clusterfuzz28338 Clusterfuzz28338 #define MAYBE_Clusterfuzz28766 Clusterfuzz28766 #endif // PERFETTO_DCHECK_IS_ON() TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz20215) { ASSERT_TRUE(LoadTrace("clusterfuzz_20215", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz20292) { ASSERT_FALSE(LoadTrace("clusterfuzz_20292", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz21178) { ASSERT_TRUE(LoadTrace("clusterfuzz_21178", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz21890) { ASSERT_FALSE(LoadTrace("clusterfuzz_21890", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz23053) { ASSERT_FALSE(LoadTrace("clusterfuzz_23053", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz28338) { ASSERT_TRUE(LoadTrace("clusterfuzz_28338", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, MAYBE_Clusterfuzz28766) { ASSERT_TRUE(LoadTrace("clusterfuzz_28766", 4096).ok()); } TEST_F(TraceProcessorIntegrationTest, RestoreInitialTables) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb").ok()); for (int repeat = 0; repeat < 3; repeat++) { ASSERT_EQ(RestoreInitialTables(), 0u); auto it = Query("CREATE TABLE user1(unused text);"); it.Next(); ASSERT_TRUE(it.Status().ok()); it = Query("CREATE TEMPORARY TABLE user2(unused text);"); it.Next(); ASSERT_TRUE(it.Status().ok()); it = Query("CREATE VIEW user3 AS SELECT * FROM stats;"); it.Next(); ASSERT_TRUE(it.Status().ok()); ASSERT_EQ(RestoreInitialTables(), 3u); } } // This test checks that a ninja trace is tokenized properly even if read in // small chunks of 1KB each. The values used in the test have been cross-checked // with opening the same trace with ninjatracing + chrome://tracing. TEST_F(TraceProcessorIntegrationTest, NinjaLog) { ASSERT_TRUE(LoadTrace("ninja_log", 1024).ok()); auto it = Query("select count(*) from process where name like 'Build';"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, 2); it = Query( "select count(*) from thread left join process using(upid) where " "thread.name like 'Worker%' and process.pid=1"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, 14); it = Query( "create view slices_1st_build as select slices.* from slices left " "join thread_track on(slices.track_id == thread_track.id) left join " "thread using(utid) left join process using(upid) where pid=2"); it.Next(); ASSERT_TRUE(it.Status().ok()); it = Query("select (max(ts) - min(ts)) / 1000000 from slices_1st_build"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, 12612); it = Query("select name from slices_1st_build order by ts desc limit 1"); ASSERT_TRUE(it.Next()); ASSERT_STREQ(it.Get(0).string_value, "obj/src/trace_processor/unittests.trace_sorter_unittest.o"); it = Query("select sum(dur) / 1000000 from slices_1st_build"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).long_value, 276174); } /* * This trace does not have a uuid. The uuid will be generated from the first * 4096 bytes, which will be read in one chunk. */ TEST_F(TraceProcessorIntegrationTest, TraceWithoutUuidReadInOneChunk) { ASSERT_TRUE(LoadTrace("example_android_trace_30s.pb", kMaxChunkSize).ok()); auto it = Query("select str_value from metadata where name = 'trace_uuid'"); ASSERT_TRUE(it.Next()); EXPECT_STREQ(it.Get(0).string_value, "00000000-0000-0000-8906-ebb53e1d0738"); } /* * This trace does not have a uuid. The uuid will be generated from the first * 4096 bytes, which will be read in multiple chunks. */ TEST_F(TraceProcessorIntegrationTest, TraceWithoutUuidReadInMultipleChuncks) { ASSERT_TRUE(LoadTrace("example_android_trace_30s.pb", 512, 2048).ok()); auto it = Query("select str_value from metadata where name = 'trace_uuid'"); ASSERT_TRUE(it.Next()); EXPECT_STREQ(it.Get(0).string_value, "00000000-0000-0000-8906-ebb53e1d0738"); } /* * This trace has a uuid. It will not be overriden by the hash of the first 4096 * bytes. */ TEST_F(TraceProcessorIntegrationTest, TraceWithUuidReadInParts) { ASSERT_TRUE(LoadTrace("trace_with_uuid.pftrace", 512, 2048).ok()); auto it = Query("select str_value from metadata where name = 'trace_uuid'"); ASSERT_TRUE(it.Next()); EXPECT_STREQ(it.Get(0).string_value, "123e4567-e89b-12d3-a456-426655443322"); } } // namespace } // namespace trace_processor } // namespace perfetto
#pragma once #include <aw/opengl/types.hpp> #include <string_view> namespace aw { class ShaderStage { public: enum class Type { Vertex, Fragment, }; public: ShaderStage(Type type); ~ShaderStage(); bool loadFromPath(std::string_view path); bool loadFromMemory(const char* content); bool loadFromMemory(const char** content, size_t count); GLuint id() const { return mId; } Type type() const { return mType; } private: private: Type mType; GLuint mId; }; } // namespace aw
/*============================================================================= Copyright (c) 1998-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <iostream> #include <boost/detail/lightweight_test.hpp> using namespace std; //#define BOOST_SPIRIT_DEBUG #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_loops.hpp> using namespace BOOST_SPIRIT_CLASSIC_NS; /////////////////////////////////////////////////////////////////////////////// // // Loops tests // /////////////////////////////////////////////////////////////////////////////// void loops_tests() { parse_info<char const*> pi; pi = parse("\"Hello World\"", "\"" >> *(anychar_p - "\"") >> "\""); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 13); BOOST_TEST(*pi.stop == 0); pi = parse("\"Hello World\"", "\"" >> repeat_p(0, more)[anychar_p - "\""] >> "\""); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 13); BOOST_TEST(*pi.stop == 0); pi = parse("xx", +ch_p('x')); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 2); BOOST_TEST(*pi.stop == 0); pi = parse("xx", repeat_p(1, more)[ch_p('x')]); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 2); BOOST_TEST(*pi.stop == 0); pi = parse("", +ch_p('x')); BOOST_TEST(!pi.hit); pi = parse("", repeat_p(1, more)[ch_p('x')]); BOOST_TEST(!pi.hit); pi = parse("", *ch_p('x')); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 0); BOOST_TEST(*pi.stop == 0); pi = parse("", repeat_p(0, more)[ch_p('x')]); BOOST_TEST(pi.hit); BOOST_TEST(pi.full); BOOST_TEST(pi.length == 0); BOOST_TEST(*pi.stop == 0); // repeat exact 8 rule<> rep8 = repeat_p(8)[alpha_p] >> 'X'; BOOST_TEST(!parse("abcdefgX", rep8).hit); BOOST_TEST(parse("abcdefghX", rep8).full); BOOST_TEST(!parse("abcdefghiX", rep8).hit); BOOST_TEST(!parse("abcdefgX", rep8).hit); BOOST_TEST(!parse("aX", rep8).hit); // repeat 2 to 8 rule<> rep28 = repeat_p(2, 8)[alpha_p] >> '*'; BOOST_TEST(parse("abcdefg*", rep28).full); BOOST_TEST(parse("abcdefgh*", rep28).full); BOOST_TEST(!parse("abcdefghi*", rep28).hit); BOOST_TEST(!parse("a*", rep28).hit); // repeat 2 or more rule<> rep2_ = repeat_p(2, more)[alpha_p] >> '+'; BOOST_TEST(parse("abcdefg+", rep2_).full); BOOST_TEST(parse("abcdefgh+", rep2_).full); BOOST_TEST(parse("abcdefghi+", rep2_).full); BOOST_TEST(parse("abcdefg+", rep2_).full); BOOST_TEST(!parse("a+", rep2_).hit); // repeat 0 rule<> rep0 = repeat_p(0)[alpha_p] >> '/'; BOOST_TEST(parse("/", rep0).full); BOOST_TEST(!parse("a/", rep0).hit); // repeat 0 or 1 rule<> rep01 = repeat_p(0, 1)[alpha_p >> digit_p] >> '?'; BOOST_TEST(!parse("abcdefg?", rep01).hit); BOOST_TEST(!parse("a?", rep01).hit); BOOST_TEST(!parse("1?", rep01).hit); BOOST_TEST(!parse("11?", rep01).hit); BOOST_TEST(!parse("aa?", rep01).hit); BOOST_TEST(parse("?", rep01).full); BOOST_TEST(parse("a1?", rep01).full); } /////////////////////////////////////////////////////////////////////////////// // // Main // /////////////////////////////////////////////////////////////////////////////// int main() { loops_tests(); return boost::report_errors(); }
// Copyright (c) 2014-2019, The Monero Project // // 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 its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers /*! * \file simplewallet.cpp * * \brief Source file that defines simple_wallet class. */ #include <locale.h> #include <thread> #include <iostream> #include <sstream> #include <fstream> #include <ctype.h> #include <boost/lexical_cast.hpp> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/regex.hpp> #include <boost/range/adaptor/transformed.hpp> #include "include_base_utils.h" #include "console_handler.h" #include "common/i18n.h" #include "common/command_line.h" #include "common/util.h" #include "common/dns_utils.h" #include "common/base58.h" #include "common/scoped_message_writer.h" #include "cryptonote_protocol/cryptonote_protocol_handler.h" #include "simplewallet.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "storages/http_abstract_invoke.h" #include "rpc/core_rpc_server_commands_defs.h" #include "rpc/rpc_payment_signature.h" #include "crypto/crypto.h" // for crypto::secret_key definition #include "mnemonics/electrum-words.h" #include "rapidjson/document.h" #include "common/json_util.h" #include "ringct/rctSigs.h" #include "multisig/multisig.h" #include "wallet/wallet_args.h" #include "version.h" #include <stdexcept> #include "wallet/message_store.h" #ifdef WIN32 #include <boost/locale.hpp> #include <boost/filesystem.hpp> #endif #ifdef HAVE_READLINE #include "readline_buffer.h" #endif using namespace std; using namespace epee; using namespace cryptonote; using boost::lexical_cast; namespace po = boost::program_options; typedef cryptonote::simple_wallet sw; #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "wallet.simplewallet" #define EXTENDED_LOGS_FILE "wallet_details.log" #define DEFAULT_MIX 10 #define MIN_RING_SIZE 11 // Used to inform user about min ring size -- does not track actual protocol #define OLD_AGE_WARN_THRESHOLD (30 * 86400 / DIFFICULTY_TARGET_V2) // 30 days #define LOCK_IDLE_SCOPE() \ bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \ m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \ /* stop any background refresh and other processes, and take over */ \ m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); \ m_wallet->stop(); \ boost::unique_lock<boost::mutex> lock(m_idle_mutex); \ m_idle_cond.notify_all(); \ epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \ /* m_idle_mutex is still locked here */ \ m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \ m_suspend_rpc_payment_mining.store(false, std::memory_order_relaxed);; \ m_rpc_payment_checker.trigger(); \ m_idle_cond.notify_one(); \ }) #define SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(code) \ LOCK_IDLE_SCOPE(); \ boost::optional<tools::password_container> pwd_container = boost::none; \ if (m_wallet->ask_password() && !(pwd_container = get_and_verify_password())) { code; } \ tools::wallet_keys_unlocker unlocker(*m_wallet, pwd_container); #define SCOPED_WALLET_UNLOCK() SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return true;) #define PRINT_USAGE(usage_help) fail_msg_writer() << boost::format(tr("usage: %s")) % usage_help; #define LONG_PAYMENT_ID_SUPPORT_CHECK() \ do { \ fail_msg_writer() << tr("Error: Long payment IDs are obsolete."); \ fail_msg_writer() << tr("Long payment IDs were not encrypted on the blockchain and would harm your privacy."); \ fail_msg_writer() << tr("If the party you're sending to still requires a long payment ID, please notify them."); \ return true; \ } while(0) #define REFRESH_PERIOD 90 // seconds #define CREDITS_TARGET 50000 #define MAX_PAYMENT_DIFF 10000 #define MIN_PAYMENT_RATE 0.01f // per hash enum TransferType { Transfer, TransferLocked, }; static std::string get_human_readable_timespan(std::chrono::seconds seconds); namespace { const std::array<const char* const, 5> allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}}; const auto arg_wallet_file = wallet_args::arg_wallet_file(); const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key(); const command_line::arg_descriptor<std::string> arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to <arg>"), ""}; const command_line::arg_descriptor<std::string> arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to <arg>"), ""}; const command_line::arg_descriptor<std::string> arg_generate_from_view_key = {"generate-from-view-key", sw::tr("Generate incoming-only wallet from view key"), ""}; const command_line::arg_descriptor<std::string> arg_generate_from_spend_key = {"generate-from-spend-key", sw::tr("Generate deterministic wallet from spend key"), ""}; const command_line::arg_descriptor<std::string> arg_generate_from_keys = {"generate-from-keys", sw::tr("Generate wallet from private keys"), ""}; const command_line::arg_descriptor<std::string> arg_generate_from_multisig_keys = {"generate-from-multisig-keys", sw::tr("Generate a master wallet from multisig wallet keys"), ""}; const auto arg_generate_from_json = wallet_args::arg_generate_from_json(); const command_line::arg_descriptor<std::string> arg_mnemonic_language = {"mnemonic-language", sw::tr("Language for mnemonic"), ""}; const command_line::arg_descriptor<std::string> arg_electrum_seed = {"electrum-seed", sw::tr("Specify Electrum seed for wallet recovery/creation"), ""}; const command_line::arg_descriptor<bool> arg_restore_deterministic_wallet = {"restore-deterministic-wallet", sw::tr("Recover wallet using Electrum-style mnemonic seed"), false}; const command_line::arg_descriptor<bool> arg_restore_from_seed = {"restore-from-seed", sw::tr("alias for --restore-deterministic-wallet"), false}; const command_line::arg_descriptor<bool> arg_restore_multisig_wallet = {"restore-multisig-wallet", sw::tr("Recover multisig wallet using Electrum-style mnemonic seed"), false}; const command_line::arg_descriptor<bool> arg_non_deterministic = {"non-deterministic", sw::tr("Generate non-deterministic view and spend keys"), false}; const command_line::arg_descriptor<bool> arg_allow_mismatched_daemon_version = {"allow-mismatched-daemon-version", sw::tr("Allow communicating with a daemon that uses a different RPC version"), false}; const command_line::arg_descriptor<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0}; const command_line::arg_descriptor<std::string> arg_restore_date = {"restore-date", sw::tr("Restore from estimated blockchain height on specified date"), ""}; const command_line::arg_descriptor<bool> arg_do_not_relay = {"do-not-relay", sw::tr("The newly created transaction will not be relayed to the coinevo network"), false}; const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false}; const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""}; const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false}; const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""}; const char* USAGE_START_MINING("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]"); const char* USAGE_SET_DAEMON("set_daemon <host>[:<port>] [trusted|untrusted]"); const char* USAGE_SHOW_BALANCE("balance [detail]"); const char* USAGE_INCOMING_TRANSFERS("incoming_transfers [available|unavailable] [verbose] [uses] [index=<N1>[,<N2>[,...]]]"); const char* USAGE_PAYMENTS("payments <PID_1> [<PID_2> ... <PID_N>]"); const char* USAGE_PAYMENT_ID("payment_id"); const char* USAGE_TRANSFER("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [<payment_id>]"); const char* USAGE_LOCKED_TRANSFER("locked_transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <addr> <amount>) <lockblocks> [<payment_id (obsolete)>]"); const char* USAGE_LOCKED_SWEEP_ALL("locked_sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <lockblocks> [<payment_id (obsolete)>]"); const char* USAGE_SWEEP_ALL("sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]"); const char* USAGE_SWEEP_BELOW("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id (obsolete)>]"); const char* USAGE_SWEEP_SINGLE("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id (obsolete)>]"); const char* USAGE_DONATE("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id (obsolete)>]"); const char* USAGE_SIGN_TRANSFER("sign_transfer [export_raw]"); const char* USAGE_SET_LOG("set_log <level>|{+,-,}<categories>"); const char* USAGE_ACCOUNT("account\n" " account new <label text with white spaces allowed>\n" " account switch <index> \n" " account label <index> <label text with white spaces allowed>\n" " account tag <tag_name> <account_index_1> [<account_index_2> ...]\n" " account untag <account_index_1> [<account_index_2> ...]\n" " account tag_description <tag_name> <description>"); const char* USAGE_ADDRESS("address [ new <label text with white spaces allowed> | all | <index_min> [<index_max>] | label <index> <label text with white spaces allowed> | device [<index>]]"); const char* USAGE_INTEGRATED_ADDRESS("integrated_address [device] [<payment_id> | <address>]"); const char* USAGE_ADDRESS_BOOK("address_book [(add ((<address> [pid <id>])|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]"); const char* USAGE_SET_VARIABLE("set <option> [<value>]"); const char* USAGE_GET_TX_KEY("get_tx_key <txid>"); const char* USAGE_SET_TX_KEY("set_tx_key <txid> <tx_key>"); const char* USAGE_CHECK_TX_KEY("check_tx_key <txid> <txkey> <address>"); const char* USAGE_GET_TX_PROOF("get_tx_proof <txid> <address> [<message>]"); const char* USAGE_CHECK_TX_PROOF("check_tx_proof <txid> <address> <signature_file> [<message>]"); const char* USAGE_GET_SPEND_PROOF("get_spend_proof <txid> [<message>]"); const char* USAGE_CHECK_SPEND_PROOF("check_spend_proof <txid> <signature_file> [<message>]"); const char* USAGE_GET_RESERVE_PROOF("get_reserve_proof (all|<amount>) [<message>]"); const char* USAGE_CHECK_RESERVE_PROOF("check_reserve_proof <address> <signature_file> [<message>]"); const char* USAGE_SHOW_TRANSFERS("show_transfers [in|out|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]"); const char* USAGE_UNSPENT_OUTPUTS("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]"); const char* USAGE_RESCAN_BC("rescan_bc [hard|soft|keep_ki] [start_height=0]"); const char* USAGE_SET_TX_NOTE("set_tx_note <txid> [free text note]"); const char* USAGE_GET_TX_NOTE("get_tx_note <txid>"); const char* USAGE_GET_DESCRIPTION("get_description"); const char* USAGE_SET_DESCRIPTION("set_description [free text note]"); const char* USAGE_SIGN("sign <filename>"); const char* USAGE_VERIFY("verify <filename> <address> <signature>"); const char* USAGE_EXPORT_KEY_IMAGES("export_key_images [all] <filename>"); const char* USAGE_IMPORT_KEY_IMAGES("import_key_images <filename>"); const char* USAGE_HW_KEY_IMAGES_SYNC("hw_key_images_sync"); const char* USAGE_HW_RECONNECT("hw_reconnect"); const char* USAGE_EXPORT_OUTPUTS("export_outputs [all] <filename>"); const char* USAGE_IMPORT_OUTPUTS("import_outputs <filename>"); const char* USAGE_SHOW_TRANSFER("show_transfer <txid>"); const char* USAGE_MAKE_MULTISIG("make_multisig <threshold> <string1> [<string>...]"); const char* USAGE_FINALIZE_MULTISIG("finalize_multisig <string> [<string>...]"); const char* USAGE_EXCHANGE_MULTISIG_KEYS("exchange_multisig_keys <string> [<string>...]"); const char* USAGE_EXPORT_MULTISIG_INFO("export_multisig_info <filename>"); const char* USAGE_IMPORT_MULTISIG_INFO("import_multisig_info <filename> [<filename>...]"); const char* USAGE_SIGN_MULTISIG("sign_multisig <filename>"); const char* USAGE_SUBMIT_MULTISIG("submit_multisig <filename>"); const char* USAGE_EXPORT_RAW_MULTISIG_TX("export_raw_multisig_tx <filename>"); const char* USAGE_MMS("mms [<subcommand> [<subcommand_parameters>]]"); const char* USAGE_MMS_INIT("mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>"); const char* USAGE_MMS_INFO("mms info"); const char* USAGE_MMS_SIGNER("mms signer [<number> <label> [<transport_address> [<coinevo_address>]]]"); const char* USAGE_MMS_LIST("mms list"); const char* USAGE_MMS_NEXT("mms next [sync]"); const char* USAGE_MMS_SYNC("mms sync"); const char* USAGE_MMS_TRANSFER("mms transfer <transfer_command_arguments>"); const char* USAGE_MMS_DELETE("mms delete (<message_id> | all)"); const char* USAGE_MMS_SEND("mms send [<message_id>]"); const char* USAGE_MMS_RECEIVE("mms receive"); const char* USAGE_MMS_EXPORT("mms export <message_id>"); const char* USAGE_MMS_NOTE("mms note [<label> <text>]"); const char* USAGE_MMS_SHOW("mms show <message_id>"); const char* USAGE_MMS_SET("mms set <option_name> [<option_value>]"); const char* USAGE_MMS_SEND_SIGNER_CONFIG("mms send_signer_config"); const char* USAGE_MMS_START_AUTO_CONFIG("mms start_auto_config [<label> <label> ...]"); const char* USAGE_MMS_STOP_AUTO_CONFIG("mms stop_auto_config"); const char* USAGE_MMS_AUTO_CONFIG("mms auto_config <auto_config_token>"); const char* USAGE_PRINT_RING("print_ring <key_image> | <txid>"); const char* USAGE_SET_RING("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )"); const char* USAGE_UNSET_RING("unset_ring <txid> | ( <key_image> [<key_image>...] )"); const char* USAGE_SAVE_KNOWN_RINGS("save_known_rings"); const char* USAGE_MARK_OUTPUT_SPENT("mark_output_spent <amount>/<offset> | <filename> [add]"); const char* USAGE_MARK_OUTPUT_UNSPENT("mark_output_unspent <amount>/<offset>"); const char* USAGE_IS_OUTPUT_SPENT("is_output_spent <amount>/<offset>"); const char* USAGE_FREEZE("freeze <key_image>"); const char* USAGE_THAW("thaw <key_image>"); const char* USAGE_FROZEN("frozen <key_image>"); const char* USAGE_LOCK("lock"); const char* USAGE_NET_STATS("net_stats"); const char* USAGE_PUBLIC_NODES("public_nodes"); const char* USAGE_WELCOME("welcome"); const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info"); const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc"); const char* USAGE_STOP_MINING_FOR_RPC("stop_mining_for_rpc"); const char* USAGE_VERSION("version"); const char* USAGE_HELP("help [<command>]"); std::string input_line(const std::string& prompt, bool yesno = false) { PAUSE_READLINE(); std::cout << prompt; if (yesno) std::cout << " (Y/Yes/N/No)"; std::cout << ": " << std::flush; std::string buf; #ifdef _WIN32 buf = tools::input_line_win(); #else std::getline(std::cin, buf); #endif return epee::string_tools::trim(buf); } epee::wipeable_string input_secure_line(const char *prompt) { PAUSE_READLINE(); auto pwd_container = tools::password_container::prompt(false, prompt, false); if (!pwd_container) { MERROR("Failed to read secure line"); return ""; } epee::wipeable_string buf = pwd_container->password(); buf.trim(); return buf; } boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify) { PAUSE_READLINE(); auto pwd_container = tools::password_container::prompt(verify, prompt); if (!pwd_container) { tools::fail_msg_writer() << sw::tr("failed to read wallet password"); } return pwd_container; } boost::optional<tools::password_container> default_password_prompter(bool verify) { return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify); } inline std::string interpret_rpc_response(bool ok, const std::string& status) { std::string err; if (ok) { if (status == CORE_RPC_STATUS_BUSY) { err = sw::tr("daemon is busy. Please try again later."); } else if (status != CORE_RPC_STATUS_OK) { err = status; } } else { err = sw::tr("possibly lost connection to daemon"); } return err; } tools::scoped_message_writer success_msg_writer(bool color = false) { return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info); } tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false) { return tools::scoped_message_writer(color, bright); } tools::scoped_message_writer fail_msg_writer() { return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error); } bool parse_bool(const std::string& s, bool& result) { if (s == "1" || command_line::is_yes(s)) { result = true; return true; } if (s == "0" || command_line::is_no(s)) { result = false; return true; } boost::algorithm::is_iequal ignore_case{}; if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case)) { result = true; return true; } if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case)) { result = false; return true; } return false; } template <typename F> bool parse_bool_and_use(const std::string& s, F func) { bool r; if (parse_bool(s, r)) { func(r); return true; } else { fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no"); return false; } } const struct { const char *name; tools::wallet2::RefreshType refresh_type; } refresh_type_names[] = { { "full", tools::wallet2::RefreshFull }, { "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase }, { "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase }, { "no-coinbase", tools::wallet2::RefreshNoCoinbase }, { "default", tools::wallet2::RefreshDefault }, }; bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type) { for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n) { if (s == refresh_type_names[n].name) { refresh_type = refresh_type_names[n].refresh_type; return true; } } fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type"); return false; } std::string get_refresh_type_name(tools::wallet2::RefreshType type) { for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n) { if (type == refresh_type_names[n].refresh_type) return refresh_type_names[n].name; } return "invalid"; } std::string get_version_string(uint32_t version) { return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff); } std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid) { if (addresses.empty()) return {}; // prompt user for confirmation. // inform user of DNSSEC validation status as well. std::string dnssec_str; if (dnssec_valid) { dnssec_str = sw::tr("DNSSEC validation passed"); } else { dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!"); } std::stringstream prompt; prompt << sw::tr("For URL: ") << url << ", " << dnssec_str << std::endl << sw::tr(" Coinevo Address = ") << addresses[0] << std::endl << sw::tr("Is this OK?") ; // prompt the user for confirmation given the dns query and dnssec status std::string confirm_dns_ok = input_line(prompt.str(), true); if (std::cin.eof()) { return {}; } if (!command_line::is_yes(confirm_dns_ok)) { std::cout << sw::tr("you have cancelled the transfer request") << std::endl; return {}; } return addresses[0]; } bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices) { subaddr_indices.clear(); if (arg.substr(0, 6) != "index=") return false; std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6); std::vector<std::string> subaddr_indices_str; boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(",")); for (const auto& subaddr_index_str : subaddr_indices_str) { uint32_t subaddr_index; if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str)) { fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str; subaddr_indices.clear(); return false; } subaddr_indices.insert(subaddr_index); } return true; } boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str) { auto r = tools::parse_subaddress_lookahead(str); if (!r) fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>"); return r; } } void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon) { bool warn_of_possible_attack = !trusted_daemon; try { std::rethrow_exception(e); } catch (const tools::error::payment_required&) { fail_msg_writer() << tr("Payment required, see the 'rpc_payment_info' command"); m_need_payment = true; } catch (const tools::error::no_connection_to_daemon&) { fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running."); } catch (const tools::error::daemon_busy&) { fail_msg_writer() << tr("daemon is busy. Please try again later."); } catch (const tools::error::wallet_rpc_error& e) { LOG_ERROR("RPC error: " << e.to_string()); fail_msg_writer() << sw::tr("RPC error: ") << e.what(); } catch (const tools::error::get_outs_error &e) { fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what(); } catch (const tools::error::not_enough_unlocked_money& e) { LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") % print_money(e.available()) % print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::not_enough_money& e) { LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") % print_money(e.available()) % print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::tx_not_possible& e) { LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") % print_money(e.available()) % print_money(e.tx_amount() + e.fee()) % print_money(e.tx_amount()) % print_money(e.fee())); fail_msg_writer() << sw::tr("Failed to find a way to create transactions. This is usually due to dust which is so small it cannot pay for itself in fees, or trying to send more money than the unlocked balance, or not leaving enough for fees"); warn_of_possible_attack = false; } catch (const tools::error::not_enough_outs_to_mix& e) { auto writer = fail_msg_writer(); writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":"; for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs()) { writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second; } writer << sw::tr("Please use sweep_unmixable."); } catch (const tools::error::tx_not_constructed&) { fail_msg_writer() << sw::tr("transaction was not constructed"); warn_of_possible_attack = false; } catch (const tools::error::tx_rejected& e) { fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx())); std::string reason = e.reason(); if (!reason.empty()) fail_msg_writer() << sw::tr("Reason: ") << reason; } catch (const tools::error::tx_sum_overflow& e) { fail_msg_writer() << e.what(); warn_of_possible_attack = false; } catch (const tools::error::zero_destination&) { fail_msg_writer() << sw::tr("one of destinations is zero"); warn_of_possible_attack = false; } catch (const tools::error::tx_too_big& e) { fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions"); warn_of_possible_attack = false; } catch (const tools::error::transfer_error& e) { LOG_ERROR("unknown transfer error: " << e.to_string()); fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what(); } catch (const tools::error::multisig_export_needed& e) { LOG_ERROR("Multisig error: " << e.to_string()); fail_msg_writer() << sw::tr("Multisig error: ") << e.what(); warn_of_possible_attack = false; } catch (const tools::error::wallet_internal_error& e) { LOG_ERROR("internal error: " << e.to_string()); fail_msg_writer() << sw::tr("internal error: ") << e.what(); } catch (const std::exception& e) { LOG_ERROR("unexpected error: " << e.what()); fail_msg_writer() << sw::tr("unexpected error: ") << e.what(); } if (warn_of_possible_attack) fail_msg_writer() << sw::tr("There was an error, which could mean the node may be trying to get you to retry creating a transaction, and zero in on which outputs you own. Or it could be a bona fide error. It may be prudent to disconnect from this node, and not try to send a transaction immediately. Alternatively, connect to another node so the original node cannot correlate information."); } namespace { bool check_file_overwrite(const std::string &filename) { boost::system::error_code errcode; if (boost::filesystem::exists(filename, errcode)) { if (boost::ends_with(filename, ".keys")) { fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename; return false; } return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it?")) % filename).str(), true)); } return true; } void print_secret_key(const crypto::secret_key &k) { static constexpr const char hex[] = u8"0123456789abcdef"; const uint8_t *ptr = (const uint8_t*)k.data; for (size_t i = 0, sz = sizeof(k); i < sz; ++i) { putchar(hex[*ptr >> 4]); putchar(hex[*ptr & 15]); ++ptr; } } } bool parse_priority(const std::string& arg, uint32_t& priority) { auto priority_pos = std::find( allowed_priority_strings.begin(), allowed_priority_strings.end(), arg); if(priority_pos != allowed_priority_strings.end()) { priority = std::distance(allowed_priority_strings.begin(), priority_pos); return true; } return false; } std::string join_priority_strings(const char *delimiter) { std::string s; for (size_t n = 0; n < allowed_priority_strings.size(); ++n) { if (!s.empty()) s += delimiter; s += allowed_priority_strings[n]; } return s; } std::string simple_wallet::get_commands_str() { std::stringstream ss; ss << tr("Commands: ") << ENDL; std::string usage = m_cmd_binder.get_usage(); boost::replace_all(usage, "\n", "\n "); usage.insert(0, " "); ss << usage << ENDL; return ss.str(); } std::string simple_wallet::get_command_usage(const std::vector<std::string> &args) { std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args); std::stringstream ss; if(documentation.first.empty()) { ss << tr("Unknown command: ") << args.front(); } else { std::string usage = documentation.second.empty() ? args.front() : documentation.first; std::string description = documentation.second.empty() ? documentation.first : documentation.second; usage.insert(0, " "); ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL; boost::replace_all(description, "\n", "\n "); description.insert(0, " "); ss << tr("Command description: ") << ENDL << description << ENDL; } return ss.str(); } bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { // don't log PAUSE_READLINE(); if (m_wallet->key_on_device()) { std::cout << "secret: On device. Not available" << std::endl; } else { SCOPED_WALLET_UNLOCK(); printf("secret: "); print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key); putchar('\n'); } std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl; return true; } bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and has no spend key"); return true; } // don't log PAUSE_READLINE(); if (m_wallet->key_on_device()) { std::cout << "secret: On device. Not available" << std::endl; } else { SCOPED_WALLET_UNLOCK(); printf("secret: "); print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key); putchar('\n'); } std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl; return true; } bool simple_wallet::print_seed(bool encrypted) { bool success = false; epee::wipeable_string seed; bool ready, multisig; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and has no seed"); return true; } multisig = m_wallet->multisig(&ready); if (multisig) { if (!ready) { fail_msg_writer() << tr("wallet is multisig but not yet finalized"); return true; } } SCOPED_WALLET_UNLOCK(); if (!multisig && !m_wallet->is_deterministic()) { fail_msg_writer() << tr("wallet is non-deterministic and has no seed"); return true; } epee::wipeable_string seed_pass; if (encrypted) { auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true); if (std::cin.eof() || !pwd_container) return true; seed_pass = pwd_container->password(); } if (multisig) success = m_wallet->get_multisig_seed(seed, seed_pass); else if (m_wallet->is_deterministic()) success = m_wallet->get_seed(seed, seed_pass); if (success) { print_seed(seed); } else { fail_msg_writer() << tr("Failed to retrieve seed"); } return true; } bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { return print_seed(false); } bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { return print_seed(true); } bool simple_wallet::restore_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { success_msg_writer() << m_wallet->get_refresh_from_block_height(); return true; } bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (m_wallet->multisig()) { fail_msg_writer() << tr("wallet is multisig and has no seed"); return true; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and has no seed"); return true; } epee::wipeable_string password; { SCOPED_WALLET_UNLOCK(); if (!m_wallet->is_deterministic()) { fail_msg_writer() << tr("wallet is non-deterministic and has no seed"); return true; } // we need the password, even if ask-password is unset if (!pwd_container) { pwd_container = get_and_verify_password(); if (pwd_container == boost::none) { fail_msg_writer() << tr("Incorrect password"); return true; } } password = pwd_container->password(); } std::string mnemonic_language = get_mnemonic_language(); if (mnemonic_language.empty()) return true; m_wallet->set_seed_language(std::move(mnemonic_language)); m_wallet->rewrite(m_wallet_file, password); return true; } bool simple_wallet::change_password(const std::vector<std::string> &args) { const auto orig_pwd_container = get_and_verify_password(); if(orig_pwd_container == boost::none) { fail_msg_writer() << tr("Your original password was incorrect."); return true; } // prompts for a new password, pass true to verify the password const auto pwd_container = default_password_prompter(true); if(!pwd_container) return true; try { m_wallet->change_password(m_wallet_file, orig_pwd_container->password(), pwd_container->password()); } catch (const tools::error::wallet_logic_error& e) { fail_msg_writer() << tr("Error with wallet rewrite: ") << e.what(); return true; } return true; } bool simple_wallet::payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { LONG_PAYMENT_ID_SUPPORT_CHECK(); crypto::hash payment_id; if (args.size() > 0) { PRINT_USAGE(USAGE_PAYMENT_ID); return true; } payment_id = crypto::rand<crypto::hash>(); success_msg_writer() << tr("Random payment ID: ") << payment_id; return true; } bool simple_wallet::print_fee_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (!try_connect_to_daemon()) return true; const bool per_byte = m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE); const uint64_t base_fee = m_wallet->get_base_fee(); const char *base = per_byte ? "byte" : "kB"; const uint64_t typical_size = per_byte ? 2500 : 13; const uint64_t size_granularity = per_byte ? 1 : 1024; message_writer() << (boost::format(tr("Current fee is %s %s per %s")) % print_money(base_fee) % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % base).str(); std::vector<uint64_t> fees; for (uint32_t priority = 1; priority <= 4; ++priority) { uint64_t mult = m_wallet->get_fee_multiplier(priority); fees.push_back(base_fee * typical_size * mult); } std::vector<std::pair<uint64_t, uint64_t>> blocks; try { uint64_t base_size = typical_size * size_granularity; blocks = m_wallet->estimate_backlog(base_size, base_size + size_granularity - 1, fees); } catch (const std::exception &e) { fail_msg_writer() << tr("Error: failed to estimate backlog array size: ") << e.what(); return true; } if (blocks.size() != 4) { fail_msg_writer() << tr("Error: bad estimated backlog array size"); return true; } for (uint32_t priority = 1; priority <= 4; ++priority) { uint64_t nblocks_low = blocks[priority - 1].first; uint64_t nblocks_high = blocks[priority - 1].second; if (nblocks_low > 0) { std::string msg; if (priority == m_wallet->get_default_priority() || (m_wallet->get_default_priority() == 0 && priority == 2)) msg = tr(" (current)"); uint64_t minutes_low = nblocks_low * DIFFICULTY_TARGET_V2 / 60, minutes_high = nblocks_high * DIFFICULTY_TARGET_V2 / 60; if (nblocks_high == nblocks_low) message_writer() << (boost::format(tr("%u block (%u minutes) backlog at priority %u%s")) % nblocks_low % minutes_low % priority % msg).str(); else message_writer() << (boost::format(tr("%u to %u block (%u to %u minutes) backlog at priority %u")) % nblocks_low % nblocks_high % minutes_low % minutes_high % priority).str(); } else message_writer() << tr("No backlog at priority ") << priority; } return true; } bool simple_wallet::prepare_multisig(const std::vector<std::string> &args) { prepare_multisig_main(args, false); return true; } bool simple_wallet::prepare_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (m_wallet->multisig()) { fail_msg_writer() << tr("This wallet is already multisig"); return false; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig"); return false; } if(m_wallet->get_num_transfer_details()) { fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet"); return false; } SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); std::string multisig_info = m_wallet->get_multisig_info(); success_msg_writer() << multisig_info; success_msg_writer() << tr("Send this multisig info to all other participants, then use make_multisig <threshold> <info1> [<info2>...] with others' multisig info"); success_msg_writer() << tr("This includes the PRIVATE view key, so needs to be disclosed only to that multisig wallet's participants "); if (called_by_mms) { get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::key_set, multisig_info); } return true; } bool simple_wallet::make_multisig(const std::vector<std::string> &args) { make_multisig_main(args, false); return true; } bool simple_wallet::make_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (m_wallet->multisig()) { fail_msg_writer() << tr("This wallet is already multisig"); return false; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig"); return false; } if(m_wallet->get_num_transfer_details()) { fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet"); return false; } if (args.size() < 2) { PRINT_USAGE(USAGE_MAKE_MULTISIG); return false; } // parse threshold uint32_t threshold; if (!string_tools::get_xtype_from_string(threshold, args[0])) { fail_msg_writer() << tr("Invalid threshold"); return false; } const auto orig_pwd_container = get_and_verify_password(); if(orig_pwd_container == boost::none) { fail_msg_writer() << tr("Your original password was incorrect."); return false; } LOCK_IDLE_SCOPE(); try { auto local_args = args; local_args.erase(local_args.begin()); std::string multisig_extra_info = m_wallet->make_multisig(orig_pwd_container->password(), local_args, threshold); if (!multisig_extra_info.empty()) { success_msg_writer() << tr("Another step is needed"); success_msg_writer() << multisig_extra_info; success_msg_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info"); if (called_by_mms) { get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info); } return true; } } catch (const std::exception &e) { fail_msg_writer() << tr("Error creating multisig: ") << e.what(); return false; } uint32_t total; if (!m_wallet->multisig(NULL, &threshold, &total)) { fail_msg_writer() << tr("Error creating multisig: new wallet is not multisig"); return false; } success_msg_writer() << std::to_string(threshold) << "/" << total << tr(" multisig address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); return true; } bool simple_wallet::finalize_multisig(const std::vector<std::string> &args) { bool ready; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } const auto pwd_container = get_and_verify_password(); if(pwd_container == boost::none) { fail_msg_writer() << tr("Your original password was incorrect."); return true; } if (!m_wallet->multisig(&ready)) { fail_msg_writer() << tr("This wallet is not multisig"); return true; } if (ready) { fail_msg_writer() << tr("This wallet is already finalized"); return true; } LOCK_IDLE_SCOPE(); if (args.size() < 2) { PRINT_USAGE(USAGE_FINALIZE_MULTISIG); return true; } try { if (!m_wallet->finalize_multisig(pwd_container->password(), args)) { fail_msg_writer() << tr("Failed to finalize multisig"); return true; } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to finalize multisig: ") << e.what(); return true; } return true; } bool simple_wallet::exchange_multisig_keys(const std::vector<std::string> &args) { exchange_multisig_keys_main(args, false); return true; } bool simple_wallet::exchange_multisig_keys_main(const std::vector<std::string> &args, bool called_by_mms) { bool ready; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (!m_wallet->multisig(&ready)) { fail_msg_writer() << tr("This wallet is not multisig"); return false; } if (ready) { fail_msg_writer() << tr("This wallet is already finalized"); return false; } const auto orig_pwd_container = get_and_verify_password(); if(orig_pwd_container == boost::none) { fail_msg_writer() << tr("Your original password was incorrect."); return false; } if (args.size() < 2) { PRINT_USAGE(USAGE_EXCHANGE_MULTISIG_KEYS); return false; } try { std::string multisig_extra_info = m_wallet->exchange_multisig_keys(orig_pwd_container->password(), args); if (!multisig_extra_info.empty()) { message_writer() << tr("Another step is needed"); message_writer() << multisig_extra_info; message_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info"); if (called_by_mms) { get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info); } return true; } else { uint32_t threshold, total; m_wallet->multisig(NULL, &threshold, &total); success_msg_writer() << tr("Multisig wallet has been successfully created. Current wallet type: ") << threshold << "/" << total; success_msg_writer() << tr("Multisig address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to perform multisig keys exchange: ") << e.what(); return false; } return true; } bool simple_wallet::export_multisig(const std::vector<std::string> &args) { export_multisig_main(args, false); return true; } bool simple_wallet::export_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { bool ready; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (!m_wallet->multisig(&ready)) { fail_msg_writer() << tr("This wallet is not multisig"); return false; } if (!ready) { fail_msg_writer() << tr("This multisig wallet is not yet finalized"); return false; } if (args.size() != 1) { PRINT_USAGE(USAGE_EXPORT_MULTISIG_INFO); return false; } const std::string filename = args[0]; if (!called_by_mms && m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename)) return true; SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); try { cryptonote::blobdata ciphertext = m_wallet->export_multisig(); if (called_by_mms) { get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::multisig_sync_data, ciphertext); } else { bool r = m_wallet->save_to_file(filename, ciphertext); if (!r) { fail_msg_writer() << tr("failed to save file ") << filename; return false; } } } catch (const std::exception &e) { LOG_ERROR("Error exporting multisig info: " << e.what()); fail_msg_writer() << tr("Error exporting multisig info: ") << e.what(); return false; } success_msg_writer() << tr("Multisig info exported to ") << filename; return true; } bool simple_wallet::import_multisig(const std::vector<std::string> &args) { import_multisig_main(args, false); return true; } bool simple_wallet::import_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { bool ready; uint32_t threshold, total; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (!m_wallet->multisig(&ready, &threshold, &total)) { fail_msg_writer() << tr("This wallet is not multisig"); return false; } if (!ready) { fail_msg_writer() << tr("This multisig wallet is not yet finalized"); return false; } if (args.size() < threshold - 1) { PRINT_USAGE(USAGE_IMPORT_MULTISIG_INFO); return false; } std::vector<cryptonote::blobdata> info; for (size_t n = 0; n < args.size(); ++n) { if (called_by_mms) { info.push_back(args[n]); } else { const std::string &filename = args[n]; std::string data; bool r = m_wallet->load_from_file(filename, data); if (!r) { fail_msg_writer() << tr("failed to read file ") << filename; return false; } info.push_back(std::move(data)); } } SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); // all read and parsed, actually import try { m_in_manual_refresh.store(true, std::memory_order_relaxed); epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);}); size_t n_outputs = m_wallet->import_multisig(info); // Clear line "Height xxx of xxx" std::cout << "\r \r"; success_msg_writer() << tr("Multisig info imported"); } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to import multisig info: ") << e.what(); return false; } if (m_wallet->is_trusted_daemon()) { try { m_wallet->rescan_spent(); } catch (const std::exception &e) { message_writer() << tr("Failed to update spent status after importing multisig info: ") << e.what(); return false; } } else { message_writer() << tr("Untrusted daemon, spent status may be incorrect. Use a trusted daemon and run \"rescan_spent\""); return false; } return true; } bool simple_wallet::accept_loaded_tx(const tools::wallet2::multisig_tx_set &txs) { std::string extra_message; return accept_loaded_tx([&txs](){return txs.m_ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.m_ptx[n].construction_data;}, extra_message); } bool simple_wallet::sign_multisig(const std::vector<std::string> &args) { sign_multisig_main(args, false); return true; } bool simple_wallet::sign_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { bool ready; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if(!m_wallet->multisig(&ready)) { fail_msg_writer() << tr("This is not a multisig wallet"); return false; } if (!ready) { fail_msg_writer() << tr("This multisig wallet is not yet finalized"); return false; } if (args.size() != 1) { PRINT_USAGE(USAGE_SIGN_MULTISIG); return false; } SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); std::string filename = args[0]; std::vector<crypto::hash> txids; uint32_t signers = 0; try { if (called_by_mms) { tools::wallet2::multisig_tx_set exported_txs; std::string ciphertext; bool r = m_wallet->load_multisig_tx(args[0], exported_txs, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); }); if (r) { r = m_wallet->sign_multisig_tx(exported_txs, txids); } if (r) { ciphertext = m_wallet->save_multisig_tx(exported_txs); if (ciphertext.empty()) { r = false; } } if (r) { mms::message_type message_type = mms::message_type::fully_signed_tx; if (txids.empty()) { message_type = mms::message_type::partially_signed_tx; } get_message_store().process_wallet_created_data(get_multisig_wallet_state(), message_type, ciphertext); filename = "MMS"; // for the messages below } else { fail_msg_writer() << tr("Failed to sign multisig transaction"); return false; } } else { bool r = m_wallet->sign_multisig_tx_from_file(filename, txids, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); }); if (!r) { fail_msg_writer() << tr("Failed to sign multisig transaction"); return false; } } } catch (const tools::error::multisig_export_needed& e) { fail_msg_writer() << tr("Multisig error: ") << e.what(); return false; } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to sign multisig transaction: ") << e.what(); return false; } if (txids.empty()) { uint32_t threshold; m_wallet->multisig(NULL, &threshold); uint32_t signers_needed = threshold - signers - 1; success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", " << signers_needed << " more signer(s) needed"; return true; } else { std::string txids_as_text; for (const auto &txid: txids) { if (!txids_as_text.empty()) txids_as_text += (", "); txids_as_text += epee::string_tools::pod_to_hex(txid); } success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", txid " << txids_as_text; success_msg_writer(true) << tr("It may be relayed to the network with submit_multisig"); } return true; } bool simple_wallet::submit_multisig(const std::vector<std::string> &args) { submit_multisig_main(args, false); return true; } bool simple_wallet::submit_multisig_main(const std::vector<std::string> &args, bool called_by_mms) { bool ready; uint32_t threshold; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return false; } if (!m_wallet->multisig(&ready, &threshold)) { fail_msg_writer() << tr("This is not a multisig wallet"); return false; } if (!ready) { fail_msg_writer() << tr("This multisig wallet is not yet finalized"); return false; } if (args.size() != 1) { PRINT_USAGE(USAGE_SUBMIT_MULTISIG); return false; } if (!try_connect_to_daemon()) return false; SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); std::string filename = args[0]; try { tools::wallet2::multisig_tx_set txs; if (called_by_mms) { bool r = m_wallet->load_multisig_tx(args[0], txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); }); if (!r) { fail_msg_writer() << tr("Failed to load multisig transaction from MMS"); return false; } } else { bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); }); if (!r) { fail_msg_writer() << tr("Failed to load multisig transaction from file"); return false; } } if (txs.m_signers.size() < threshold) { fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures")) % txs.m_signers.size() % (threshold - txs.m_signers.size())).str(); return false; } // actually commit the transactions for (auto &ptx: txs.m_ptx) { m_wallet->commit_tx(ptx); success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << get_transaction_hash(ptx.tx) << ENDL << tr("You can check its status by using the `show_transfers` command."); } } catch (const std::exception &e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); return false; } return true; } bool simple_wallet::export_raw_multisig(const std::vector<std::string> &args) { bool ready; uint32_t threshold; if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (!m_wallet->multisig(&ready, &threshold)) { fail_msg_writer() << tr("This is not a multisig wallet"); return true; } if (!ready) { fail_msg_writer() << tr("This multisig wallet is not yet finalized"); return true; } if (args.size() != 1) { PRINT_USAGE(USAGE_EXPORT_RAW_MULTISIG_TX); return true; } std::string filename = args[0]; if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename)) return true; SCOPED_WALLET_UNLOCK(); try { tools::wallet2::multisig_tx_set txs; bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); }); if (!r) { fail_msg_writer() << tr("Failed to load multisig transaction from file"); return true; } if (txs.m_signers.size() < threshold) { fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures")) % txs.m_signers.size() % (threshold - txs.m_signers.size())).str(); return true; } // save the transactions std::string filenames; for (auto &ptx: txs.m_ptx) { const crypto::hash txid = cryptonote::get_transaction_hash(ptx.tx); const std::string filename = std::string("raw_multisig_coinevo_tx_") + epee::string_tools::pod_to_hex(txid); if (!filenames.empty()) filenames += ", "; filenames += filename; if (!m_wallet->save_to_file(filename, cryptonote::tx_to_blob(ptx.tx))) { fail_msg_writer() << tr("Failed to export multisig transaction to file ") << filename; return true; } } success_msg_writer() << tr("Saved exported multisig transaction file(s): ") << filenames; } catch (const std::exception& e) { LOG_ERROR("unexpected error: " << e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { LOG_ERROR("Unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } bool simple_wallet::print_ring(const std::vector<std::string> &args) { crypto::key_image key_image; crypto::hash txid; if (args.size() != 1) { PRINT_USAGE(USAGE_PRINT_RING); return true; } if (!epee::string_tools::hex_to_pod(args[0], key_image)) { fail_msg_writer() << tr("Invalid key image"); return true; } // this one will always work, they're all 32 byte hex if (!epee::string_tools::hex_to_pod(args[0], txid)) { fail_msg_writer() << tr("Invalid txid"); return true; } std::vector<uint64_t> ring; std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings; try { if (m_wallet->get_ring(key_image, ring)) rings.push_back({key_image, ring}); else if (!m_wallet->get_rings(txid, rings)) { fail_msg_writer() << tr("Key image either not spent, or spent with mixin 0"); return true; } for (const auto &ring: rings) { std::stringstream str; for (const auto &x: ring.second) str << x<< " "; // do NOT translate this "absolute" below, the lin can be used as input to set_ring success_msg_writer() << epee::string_tools::pod_to_hex(ring.first) << " absolute " << str.str(); } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to get key image ring: ") << e.what(); } return true; } bool simple_wallet::set_ring(const std::vector<std::string> &args) { crypto::key_image key_image; // try filename first if (args.size() == 1) { if (!epee::file_io_utils::is_file_exist(args[0])) { fail_msg_writer() << tr("File doesn't exist"); return true; } char str[4096]; std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r")); if (f) { while (!feof(f.get())) { if (!fgets(str, sizeof(str), f.get())) break; const size_t len = strlen(str); if (len > 0 && str[len - 1] == '\n') str[len - 1] = 0; if (!str[0]) continue; char key_image_str[65], type_str[9]; int read_after_key_image = 0, read = 0; int fields = sscanf(str, "%64[abcdefABCDEF0123456789] %n%8s %n", key_image_str, &read_after_key_image, type_str, &read); if (fields != 2) { fail_msg_writer() << tr("Invalid ring specification: ") << str; continue; } key_image_str[64] = 0; type_str[8] = 0; crypto::key_image key_image; if (read_after_key_image == 0 || !epee::string_tools::hex_to_pod(key_image_str, key_image)) { fail_msg_writer() << tr("Invalid key image: ") << str; continue; } if (read == read_after_key_image+8 || (strcmp(type_str, "absolute") && strcmp(type_str, "relative"))) { fail_msg_writer() << tr("Invalid ring type, expected relative or abosolute: ") << str; continue; } bool relative = !strcmp(type_str, "relative"); if (read < 0 || (size_t)read > strlen(str)) { fail_msg_writer() << tr("Error reading line: ") << str; continue; } bool valid = true; std::vector<uint64_t> ring; const char *ptr = str + read; while (*ptr) { unsigned long offset; int elements = sscanf(ptr, "%lu %n", &offset, &read); if (elements == 0 || read <= 0 || (size_t)read > strlen(str)) { fail_msg_writer() << tr("Error reading line: ") << str; valid = false; break; } ring.push_back(offset); ptr += read; } if (!valid) continue; if (ring.empty()) { fail_msg_writer() << tr("Invalid ring: ") << str; continue; } if (relative) { for (size_t n = 1; n < ring.size(); ++n) { if (ring[n] <= 0) { fail_msg_writer() << tr("Invalid relative ring: ") << str; valid = false; break; } } } else { for (size_t n = 1; n < ring.size(); ++n) { if (ring[n] <= ring[n-1]) { fail_msg_writer() << tr("Invalid absolute ring: ") << str; valid = false; break; } } } if (!valid) continue; if (!m_wallet->set_ring(key_image, ring, relative)) fail_msg_writer() << tr("Failed to set ring for key image: ") << key_image << ". " << tr("Continuing."); } f.reset(); } return true; } if (args.size() < 3) { PRINT_USAGE(USAGE_SET_RING); return true; } if (!epee::string_tools::hex_to_pod(args[0], key_image)) { fail_msg_writer() << tr("Invalid key image"); return true; } bool relative; if (args[1] == "absolute") { relative = false; } else if (args[1] == "relative") { relative = true; } else { fail_msg_writer() << tr("Missing absolute or relative keyword"); return true; } std::vector<uint64_t> ring; for (size_t n = 2; n < args.size(); ++n) { ring.resize(ring.size() + 1); if (!string_tools::get_xtype_from_string(ring.back(), args[n])) { fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer"); return true; } if (relative) { if (ring.size() > 1 && !ring.back()) { fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer"); return true; } uint64_t sum = 0; for (uint64_t out: ring) { if (out > std::numeric_limits<uint64_t>::max() - sum) { fail_msg_writer() << tr("invalid index: indices wrap"); return true; } sum += out; } } else { if (ring.size() > 1 && ring[ring.size() - 2] >= ring[ring.size() - 1]) { fail_msg_writer() << tr("invalid index: indices should be in strictly ascending order"); return true; } } } if (!m_wallet->set_ring(key_image, ring, relative)) { fail_msg_writer() << tr("failed to set ring"); return true; } return true; } bool simple_wallet::unset_ring(const std::vector<std::string> &args) { crypto::hash txid; std::vector<crypto::key_image> key_images; if (args.size() < 1) { PRINT_USAGE(USAGE_UNSET_RING); return true; } key_images.resize(args.size()); for (size_t i = 0; i < args.size(); ++i) { if (!epee::string_tools::hex_to_pod(args[i], key_images[i])) { fail_msg_writer() << tr("Invalid key image or txid"); return true; } } static_assert(sizeof(crypto::hash) == sizeof(crypto::key_image), "hash and key_image must have the same size"); memcpy(&txid, &key_images[0], sizeof(txid)); if (!m_wallet->unset_ring(key_images) && !m_wallet->unset_ring(txid)) { fail_msg_writer() << tr("failed to unset ring"); return true; } return true; } bool simple_wallet::rpc_payment_info(const std::vector<std::string> &args) { if (!try_connect_to_daemon()) return true; LOCK_IDLE_SCOPE(); try { bool payment_required; uint64_t credits, diff, credits_per_hash_found, height, seed_height; uint32_t cookie; std::string hashing_blob; crypto::hash seed_hash, next_seed_hash; crypto::public_key pkey; crypto::secret_key_to_public_key(m_wallet->get_rpc_client_secret_key(), pkey); message_writer() << tr("RPC client ID: ") << pkey; message_writer() << tr("RPC client secret key: ") << m_wallet->get_rpc_client_secret_key(); if (!m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie)) { fail_msg_writer() << tr("Failed to query daemon"); return true; } if (payment_required) { uint64_t target = m_wallet->credits_target(); if (target == 0) target = CREDITS_TARGET; message_writer() << tr("Using daemon: ") << m_wallet->get_daemon_address(); message_writer() << tr("Payments required for node use, current credits: ") << credits; message_writer() << tr("Credits target: ") << target; uint64_t expected, discrepancy; m_wallet->credit_report(expected, discrepancy); message_writer() << tr("Credits spent this session: ") << expected; if (expected) message_writer() << tr("Credit discrepancy this session: ") << discrepancy << " (" << 100.0f * discrepancy / expected << "%)"; float cph = credits_per_hash_found / (float)diff; message_writer() << tr("Difficulty: ") << diff << ", " << credits_per_hash_found << " " << tr("credits per hash found, ") << cph << " " << tr("credits/hash");; const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); bool mining = (now - m_last_rpc_payment_mining_time).total_microseconds() < 1000000; if (mining) { float hash_rate = m_rpc_payment_hash_rate; if (hash_rate > 0) { message_writer() << (boost::format(tr("Mining for payment at %.1f H/s")) % hash_rate).str(); if (credits < target) { std::chrono::seconds seconds((unsigned)((target - credits) / cph / hash_rate)); std::string target_string = get_human_readable_timespan(seconds); message_writer() << (boost::format(tr("Estimated time till %u credits target mined: %s")) % target % target_string).str(); } } else message_writer() << tr("Mining for payment"); } else message_writer() << tr("Not mining"); } else message_writer() << tr("No payment needed for node use"); } catch (const std::exception& e) { LOG_ERROR("unexpected error: " << e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } return true; } bool simple_wallet::blackball(const std::vector<std::string> &args) { uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets; if (args.size() == 0) { PRINT_USAGE(USAGE_MARK_OUTPUT_SPENT); return true; } try { if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &amount, &offset) == 2) { m_wallet->blackball_output(std::make_pair(amount, offset)); } else if (epee::file_io_utils::is_file_exist(args[0])) { std::vector<std::pair<uint64_t, uint64_t>> outputs; char str[256]; std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r")); if (f) { while (!feof(f.get())) { if (!fgets(str, sizeof(str), f.get())) break; const size_t len = strlen(str); if (len > 0 && str[len - 1] == '\n') str[len - 1] = 0; if (!str[0]) continue; if (sscanf(str, "@%" PRIu64, &amount) == 1) { continue; } if (amount == std::numeric_limits<uint64_t>::max()) { fail_msg_writer() << tr("First line is not an amount"); return true; } if (sscanf(str, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset) { while (num_offsets--) outputs.push_back(std::make_pair(amount, offset++)); } else if (sscanf(str, "%" PRIu64, &offset) == 1) { outputs.push_back(std::make_pair(amount, offset)); } else { fail_msg_writer() << tr("Invalid output: ") << str; return true; } } f.reset(); bool add = false; if (args.size() > 1) { if (args[1] != "add") { fail_msg_writer() << tr("Bad argument: ") + args[1] + ": " + tr("should be \"add\""); return true; } add = true; } m_wallet->set_blackballed_outputs(outputs, add); } else { fail_msg_writer() << tr("Failed to open file"); return true; } } else { fail_msg_writer() << tr("Invalid output key, and file doesn't exist"); return true; } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to mark output spent: ") << e.what(); } return true; } bool simple_wallet::unblackball(const std::vector<std::string> &args) { std::pair<uint64_t, uint64_t> output; if (args.size() != 1) { PRINT_USAGE(USAGE_MARK_OUTPUT_UNSPENT); return true; } if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2) { fail_msg_writer() << tr("Invalid output"); return true; } try { m_wallet->unblackball_output(output); } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to mark output unspent: ") << e.what(); } return true; } bool simple_wallet::blackballed(const std::vector<std::string> &args) { std::pair<uint64_t, uint64_t> output; if (args.size() != 1) { PRINT_USAGE(USAGE_IS_OUTPUT_SPENT); return true; } if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2) { fail_msg_writer() << tr("Invalid output"); return true; } try { if (m_wallet->is_output_blackballed(output)) message_writer() << tr("Spent: ") << output.first << "/" << output.second; else message_writer() << tr("Not spent: ") << output.first << "/" << output.second; } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to check whether output is spent: ") << e.what(); } return true; } bool simple_wallet::save_known_rings(const std::vector<std::string> &args) { try { LOCK_IDLE_SCOPE(); m_wallet->find_and_save_rings(); } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to save known rings: ") << e.what(); } return true; } bool simple_wallet::freeze_thaw(const std::vector<std::string> &args, bool freeze) { if (args.empty()) { fail_msg_writer() << boost::format(tr("usage: %s <key_image>|<pubkey>")) % (freeze ? "freeze" : "thaw"); return true; } crypto::key_image ki; if (!epee::string_tools::hex_to_pod(args[0], ki)) { fail_msg_writer() << tr("failed to parse key image"); return true; } try { if (freeze) m_wallet->freeze(ki); else m_wallet->thaw(ki); } catch (const std::exception &e) { fail_msg_writer() << e.what(); return true; } return true; } bool simple_wallet::freeze(const std::vector<std::string> &args) { return freeze_thaw(args, true); } bool simple_wallet::thaw(const std::vector<std::string> &args) { return freeze_thaw(args, false); } bool simple_wallet::frozen(const std::vector<std::string> &args) { if (args.empty()) { size_t ntd = m_wallet->get_num_transfer_details(); for (size_t i = 0; i < ntd; ++i) { if (!m_wallet->frozen(i)) continue; const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i); message_writer() << tr("Frozen: ") << td.m_key_image << " " << cryptonote::print_money(td.amount()); } } else { crypto::key_image ki; if (!epee::string_tools::hex_to_pod(args[0], ki)) { fail_msg_writer() << tr("failed to parse key image"); return true; } if (m_wallet->frozen(ki)) message_writer() << tr("Frozen: ") << ki; else message_writer() << tr("Not frozen: ") << ki; } return true; } bool simple_wallet::lock(const std::vector<std::string> &args) { m_locked = true; check_for_inactivity_lock(true); return true; } bool simple_wallet::net_stats(const std::vector<std::string> &args) { message_writer() << std::to_string(m_wallet->get_bytes_sent()) + tr(" bytes sent"); message_writer() << std::to_string(m_wallet->get_bytes_received()) + tr(" bytes received"); return true; } bool simple_wallet::public_nodes(const std::vector<std::string> &args) { try { auto nodes = m_wallet->get_public_nodes(false); m_claimed_cph.clear(); if (nodes.empty()) { fail_msg_writer() << tr("No known public nodes"); return true; } std::sort(nodes.begin(), nodes.end(), [](const public_node &node0, const public_node &node1) { if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash == 0) return true; if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash) return node0.rpc_credits_per_hash < node1.rpc_credits_per_hash; return false; }); const uint64_t now = time(NULL); message_writer() << boost::format("%32s %12s %16s") % tr("address") % tr("credits/hash") % tr("last_seen"); for (const auto &node: nodes) { const float cph = node.rpc_credits_per_hash / RPC_CREDITS_PER_HASH_SCALE; char cphs[9]; snprintf(cphs, sizeof(cphs), "%.3f", cph); const std::string last_seen = node.last_seen == 0 ? tr("never") : get_human_readable_timespan(std::chrono::seconds(now - node.last_seen)); std::string host = node.host + ":" + std::to_string(node.rpc_port); message_writer() << boost::format("%32s %12s %16s") % host % cphs % last_seen; m_claimed_cph[host] = node.rpc_credits_per_hash; } } catch (const std::exception &e) { fail_msg_writer() << tr("Error retrieving public node list: ") << e.what(); } return true; } bool simple_wallet::welcome(const std::vector<std::string> &args) { message_writer() << tr("Welcome to Coinevo, the private cryptocurrency."); message_writer() << ""; message_writer() << tr("Coinevo, like Bitcoin, is a cryptocurrency. That is, it is digital money."); message_writer() << tr("Unlike Bitcoin, your Coinevo transactions and balance stay private and are not visible to the world by default."); message_writer() << tr("However, you have the option of making those available to select parties if you choose to."); message_writer() << ""; message_writer() << tr("Coinevo protects your privacy on the blockchain, and while Coinevo strives to improve all the time,"); message_writer() << tr("no privacy technology can be 100% perfect, Coinevo included."); message_writer() << tr("Coinevo cannot protect you from malware, and it may not be as effective as we hope against powerful adversaries."); message_writer() << tr("Flaws in Coinevo may be discovered in the future, and attacks may be developed to peek under some"); message_writer() << tr("of the layers of privacy Coinevo provides. Be safe and practice defense in depth."); message_writer() << ""; message_writer() << tr("Welcome to Coinevo and financial privacy. For more information see https://coinevo.tech"); return true; } bool simple_wallet::version(const std::vector<std::string> &args) { message_writer() << "Coinevo '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")"; return true; } bool simple_wallet::on_unknown_command(const std::vector<std::string> &args) { if (args[0] == "exit" || args[0] == "q") // backward compat return false; fail_msg_writer() << boost::format(tr("Unknown command '%s', try 'help'")) % args.front(); return true; } bool simple_wallet::on_empty_command() { return true; } bool simple_wallet::on_cancelled_command() { check_for_inactivity_lock(false); return true; } bool simple_wallet::cold_sign_tx(const std::vector<tools::wallet2::pending_tx>& ptx_vector, tools::wallet2::signed_tx_set &exported_txs, std::vector<cryptonote::address_parse_info> &dsts_info, std::function<bool(const tools::wallet2::signed_tx_set &)> accept_func) { std::vector<std::string> tx_aux; message_writer(console_color_white, false) << tr("Please confirm the transaction on the device"); m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux); if (accept_func && !accept_func(exported_txs)) { MERROR("Transactions rejected by callback"); return false; } // aux info m_wallet->cold_tx_aux_import(exported_txs.ptx, tx_aux); // import key images return m_wallet->import_key_images(exported_txs, 0, true); } bool simple_wallet::start_mining_for_rpc(const std::vector<std::string> &args) { if (!try_connect_to_daemon()) return true; LOCK_IDLE_SCOPE(); bool payment_required; uint64_t credits, diff, credits_per_hash_found, height, seed_height; uint32_t cookie; std::string hashing_blob; crypto::hash seed_hash, next_seed_hash; if (!m_wallet->get_rpc_payment_info(true, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie)) { fail_msg_writer() << tr("Failed to query daemon"); return true; } if (!payment_required) { fail_msg_writer() << tr("Daemon does not require payment for RPC access"); return true; } m_rpc_payment_mining_requested = true; m_rpc_payment_checker.trigger(); const float cph = credits_per_hash_found / (float)diff; bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE); success_msg_writer() << (boost::format(tr("Starting mining for RPC access: diff %llu, %f credits/hash%s")) % diff % cph % (low ? " - this is low" : "")).str(); success_msg_writer() << tr("Run stop_mining_for_rpc to stop"); return true; } bool simple_wallet::stop_mining_for_rpc(const std::vector<std::string> &args) { if (!try_connect_to_daemon()) return true; LOCK_IDLE_SCOPE(); m_rpc_payment_mining_requested = false; m_last_rpc_payment_mining_time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)); m_rpc_payment_hash_rate = -1.0f; return true; } bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->always_confirm_transfers(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->print_ring_members(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot transfer"); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->store_tx_info(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_default_ring_size(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot transfer"); return true; } try { if (strchr(args[1].c_str(), '-')) { fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE; return true; } uint32_t ring_size = boost::lexical_cast<uint32_t>(args[1]); if (ring_size < MIN_RING_SIZE && ring_size != 0) { fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE; return true; } if (ring_size != 0 && ring_size != DEFAULT_MIX+1) { if (m_wallet->use_fork_rules(8, 0)) { message_writer() << tr("WARNING: from v8, ring size will be fixed and this setting will be ignored."); } else { message_writer() << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended."); } } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->default_mixin(ring_size > 0 ? ring_size - 1 : 0); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } catch(const boost::bad_lexical_cast &) { fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE; return true; } catch(...) { fail_msg_writer() << tr("could not change default ring size"); return true; } } bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { uint32_t priority = 0; try { if (strchr(args[1].c_str(), '-')) { fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", "); return true; } if (args[1] == "0") { priority = 0; } else { bool found = false; for (size_t n = 0; n < allowed_priority_strings.size(); ++n) { if (allowed_priority_strings[n] == args[1]) { found = true; priority = n; } } if (!found) { priority = boost::lexical_cast<int>(args[1]); if (priority < 1 || priority > 4) { fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", "); return true; } } } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->set_default_priority(priority); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } catch(const boost::bad_lexical_cast &) { fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", "); return true; } catch(...) { fail_msg_writer() << tr("could not change default priority"); return true; } } bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool auto_refresh) { m_auto_refresh_enabled.store(false, std::memory_order_relaxed); m_wallet->auto_refresh(auto_refresh); m_idle_mutex.lock(); m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed); m_idle_cond.notify_one(); m_idle_mutex.unlock(); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { tools::wallet2::RefreshType refresh_type; if (!parse_refresh_type(args[1], refresh_type)) { return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->set_refresh_type(refresh_type); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_ask_password(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { tools::wallet2::AskPasswordType ask = tools::wallet2::AskPasswordToDecrypt; if (args[1] == "never" || args[1] == "0") ask = tools::wallet2::AskPasswordNever; else if (args[1] == "action" || args[1] == "1") ask = tools::wallet2::AskPasswordOnAction; else if (args[1] == "encrypt" || args[1] == "decrypt" || args[1] == "2") ask = tools::wallet2::AskPasswordToDecrypt; else { fail_msg_writer() << tr("invalid argument: must be either 0/never, 1/action, or 2/encrypt/decrypt"); return true; } const tools::wallet2::AskPasswordType cur_ask = m_wallet->ask_password(); if (!m_wallet->watch_only()) { if (cur_ask == tools::wallet2::AskPasswordToDecrypt && ask != tools::wallet2::AskPasswordToDecrypt) m_wallet->decrypt_keys(pwd_container->password()); else if (cur_ask != tools::wallet2::AskPasswordToDecrypt && ask == tools::wallet2::AskPasswordToDecrypt) m_wallet->encrypt_keys(pwd_container->password()); } m_wallet->ask_password(ask); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_unit(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const std::string &unit = args[1]; unsigned int decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT; if (unit == "coinevo") decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT; else if (unit == "millinero") decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 3; else if (unit == "micronero") decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 6; else if (unit == "nanonero") decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 9; else if (unit == "piconero") decimal_point = 0; else { fail_msg_writer() << tr("invalid unit"); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { cryptonote::set_default_decimal_point(decimal_point); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_min_output_count(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { uint32_t count; if (!string_tools::get_xtype_from_string(count, args[1])) { fail_msg_writer() << tr("invalid count: must be an unsigned integer"); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->set_min_output_count(count); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_min_output_value(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { uint64_t value; if (!cryptonote::parse_amount(value, args[1])) { fail_msg_writer() << tr("invalid value"); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->set_min_output_value(value); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_merge_destinations(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->merge_destinations(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_confirm_backlog(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->confirm_backlog(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_confirm_backlog_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { uint32_t threshold; if (!string_tools::get_xtype_from_string(threshold, args[1])) { fail_msg_writer() << tr("invalid count: must be an unsigned integer"); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->set_confirm_backlog_threshold(threshold); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_confirm_export_overwrite(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->confirm_export_overwrite(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_refresh_from_block_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint64_t height; if (!epee::string_tools::get_xtype_from_string(height, args[1])) { fail_msg_writer() << tr("Invalid height"); return true; } m_wallet->set_refresh_from_block_height(height); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_auto_low_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->auto_low_priority(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->segregate_pre_fork_outputs(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_persistent_rpc_client_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->persistent_rpc_client_id(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_auto_mine_for_rpc_payment_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { float threshold; if (!epee::string_tools::get_xtype_from_string(threshold, args[1]) || threshold < 0.0f) { fail_msg_writer() << tr("Invalid threshold"); return true; } m_wallet->auto_mine_for_rpc_payment_threshold(threshold); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_credits_target(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint64_t target; if (!epee::string_tools::get_xtype_from_string(target, args[1])) { fail_msg_writer() << tr("Invalid target"); return true; } m_wallet->credits_target(target); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_key_reuse_mitigation2(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->key_reuse_mitigation2(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_subaddress_lookahead(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { auto lookahead = parse_subaddress_lookahead(args[1]); if (lookahead) { m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } } return true; } bool simple_wallet::set_segregation_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint64_t height; if (!epee::string_tools::get_xtype_from_string(height, args[1])) { fail_msg_writer() << tr("Invalid height"); return true; } m_wallet->segregation_height(height); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_ignore_fractional_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->ignore_fractional_outputs(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_ignore_outputs_above(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint64_t amount; if (!cryptonote::parse_amount(amount, args[1])) { fail_msg_writer() << tr("Invalid amount"); return true; } if (amount == 0) amount = MONEY_SUPPLY; m_wallet->ignore_outputs_above(amount); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_ignore_outputs_below(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint64_t amount; if (!cryptonote::parse_amount(amount, args[1])) { fail_msg_writer() << tr("Invalid amount"); return true; } m_wallet->ignore_outputs_below(amount); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::set_track_uses(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { parse_bool_and_use(args[1], [&](bool r) { m_wallet->track_uses(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); }); } return true; } bool simple_wallet::set_inactivity_lock_timeout(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { #ifdef _WIN32 tools::fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows"); return true; #endif const auto pwd_container = get_and_verify_password(); if (pwd_container) { uint32_t r; if (epee::string_tools::get_xtype_from_string(r, args[1])) { m_wallet->inactivity_lock_timeout(r); m_wallet->rewrite(m_wallet_file, pwd_container->password()); } else { tools::fail_msg_writer() << tr("Invalid number of seconds"); } } return true; } bool simple_wallet::set_setup_background_mining(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { tools::wallet2::BackgroundMiningSetupType setup = tools::wallet2::BackgroundMiningMaybe; if (args[1] == "yes" || args[1] == "1") setup = tools::wallet2::BackgroundMiningYes; else if (args[1] == "no" || args[1] == "0") setup = tools::wallet2::BackgroundMiningNo; else { fail_msg_writer() << tr("invalid argument: must be either 1/yes or 0/no"); return true; } m_wallet->setup_background_mining(setup); m_wallet->rewrite(m_wallet_file, pwd_container->password()); if (setup == tools::wallet2::BackgroundMiningYes) start_background_mining(); else stop_background_mining(); } return true; } bool simple_wallet::set_device_name(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { const auto pwd_container = get_and_verify_password(); if (pwd_container) { if (args.size() == 0){ fail_msg_writer() << tr("Device name not specified"); return true; } m_wallet->device_name(args[1]); bool r = false; try { r = m_wallet->reconnect_device(); if (!r){ fail_msg_writer() << tr("Device reconnect failed"); } } catch(const std::exception & e){ MWARNING("Device reconnect failed: " << e.what()); fail_msg_writer() << tr("Device reconnect failed: ") << e.what(); } } return true; } bool simple_wallet::set_export_format(const std::vector<std::string> &args/* = std::vector<std::string()*/) { if (args.size() < 2) { fail_msg_writer() << tr("Export format not specified"); return true; } if (boost::algorithm::iequals(args[1], "ascii")) { m_wallet->set_export_format(tools::wallet2::ExportFormat::Ascii); } else if (boost::algorithm::iequals(args[1], "binary")) { m_wallet->set_export_format(tools::wallet2::ExportFormat::Binary); } else { fail_msg_writer() << tr("Export format not recognized."); return true; } const auto pwd_container = get_and_verify_password(); if (pwd_container) { m_wallet->rewrite(m_wallet_file, pwd_container->password()); } return true; } bool simple_wallet::help(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if(args.empty()) { success_msg_writer() << get_commands_str(); } else if ((args.size() == 2) && (args.front() == "mms")) { // Little hack to be able to do "help mms <subcommand>" std::vector<std::string> mms_args(1, args.front() + " " + args.back()); success_msg_writer() << get_command_usage(mms_args); } else { success_msg_writer() << get_command_usage(args); } return true; } simple_wallet::simple_wallet() : m_allow_mismatched_daemon_version(false) , m_refresh_progress_reporter(*this) , m_idle_run(true) , m_auto_refresh_enabled(false) , m_auto_refresh_refreshing(false) , m_in_manual_refresh(false) , m_current_subaddress_account(0) , m_last_activity_time(time(NULL)) , m_locked(false) , m_in_command(false) , m_need_payment(false) , m_rpc_payment_mining_requested(false) , m_last_rpc_payment_mining_time(boost::gregorian::date(1970, 1, 1)) , m_daemon_rpc_payment_message_displayed(false) , m_rpc_payment_hash_rate(-1.0f) , m_suspend_rpc_payment_mining(false) { m_cmd_binder.set_handler("start_mining", boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining, _1), tr(USAGE_START_MINING), tr("Start mining in the daemon (bg_mining and ignore_battery are optional booleans).")); m_cmd_binder.set_handler("stop_mining", boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining, _1), tr("Stop mining in the daemon.")); m_cmd_binder.set_handler("set_daemon", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_daemon, _1), tr(USAGE_SET_DAEMON), tr("Set another daemon to connect to.")); m_cmd_binder.set_handler("save_bc", boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_bc, _1), tr("Save the current blockchain data.")); m_cmd_binder.set_handler("refresh", boost::bind(&simple_wallet::on_command, this, &simple_wallet::refresh, _1), tr("Synchronize the transactions and balance.")); m_cmd_binder.set_handler("balance", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_balance, _1), tr(USAGE_SHOW_BALANCE), tr("Show the wallet's balance of the currently selected account.")); m_cmd_binder.set_handler("incoming_transfers", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_incoming_transfers,_1), tr(USAGE_INCOMING_TRANSFERS), tr("Show the incoming transfers, all or filtered by availability and address index.\n\n" "Output format:\n" "Amount, Spent(\"T\"|\"F\"), \"frozen\"|\"locked\"|\"unlocked\", RingCT, Global Index, Transaction Hash, Address Index, [Public Key, Key Image] ")); m_cmd_binder.set_handler("payments", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_payments,_1), tr(USAGE_PAYMENTS), tr("Show the payments for the given payment IDs.")); m_cmd_binder.set_handler("bc_height", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_blockchain_height, _1), tr("Show the blockchain height.")); m_cmd_binder.set_handler("transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::transfer, _1), tr(USAGE_TRANSFER), tr("Transfer <amount> to <address>. If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)")); m_cmd_binder.set_handler("locked_transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::locked_transfer,_1), tr(USAGE_LOCKED_TRANSFER), tr("Transfer <amount> to <address> and lock it for <lockblocks> (max. 1000000). If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)")); m_cmd_binder.set_handler("locked_sweep_all", boost::bind(&simple_wallet::on_command, this, &simple_wallet::locked_sweep_all,_1), tr(USAGE_LOCKED_SWEEP_ALL), tr("Send all unlocked balance to an address and lock it for <lockblocks> (max. 1000000). If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. <priority> is the priority of the sweep. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability.")); m_cmd_binder.set_handler("sweep_unmixable", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_unmixable, _1), tr("Send all unmixable outputs to yourself with ring_size 1")); m_cmd_binder.set_handler("sweep_all", boost::bind(&simple_wallet::sweep_all, this, _1), tr(USAGE_SWEEP_ALL), tr("Send all unlocked balance to an address. If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. If the parameter \"outputs=<N>\" is specified and N > 0, wallet splits the transaction into N even outputs.")); m_cmd_binder.set_handler("sweep_below", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_below, _1), tr(USAGE_SWEEP_BELOW), tr("Send all unlocked outputs below the threshold to an address.")); m_cmd_binder.set_handler("sweep_single", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_single, _1), tr(USAGE_SWEEP_SINGLE), tr("Send a single output of the given key image to an address without change.")); m_cmd_binder.set_handler("donate", boost::bind(&simple_wallet::on_command, this, &simple_wallet::donate, _1), tr(USAGE_DONATE), tr("Donate <amount> to the development team (donate.coinevo.tech).")); m_cmd_binder.set_handler("sign_transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_transfer, _1), tr(USAGE_SIGN_TRANSFER), tr("Sign a transaction from a file. If the parameter \"export_raw\" is specified, transaction raw hex data suitable for the daemon RPC /sendrawtransaction is exported.")); m_cmd_binder.set_handler("submit_transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_transfer, _1), tr("Submit a signed transaction from a file.")); m_cmd_binder.set_handler("set_log", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_log, _1), tr(USAGE_SET_LOG), tr("Change the current log detail (level must be <0-4>).")); m_cmd_binder.set_handler("account", boost::bind(&simple_wallet::on_command, this, &simple_wallet::account, _1), tr(USAGE_ACCOUNT), tr("If no arguments are specified, the wallet shows all the existing accounts along with their balances.\n" "If the \"new\" argument is specified, the wallet creates a new account with its label initialized by the provided label text (which can be empty).\n" "If the \"switch\" argument is specified, the wallet switches to the account specified by <index>.\n" "If the \"label\" argument is specified, the wallet sets the label of the account specified by <index> to the provided label text.\n" "If the \"tag\" argument is specified, a tag <tag_name> is assigned to the specified accounts <account_index_1>, <account_index_2>, ....\n" "If the \"untag\" argument is specified, the tags assigned to the specified accounts <account_index_1>, <account_index_2> ..., are removed.\n" "If the \"tag_description\" argument is specified, the tag <tag_name> is assigned an arbitrary text <description>.")); m_cmd_binder.set_handler("address", boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_address, _1), tr(USAGE_ADDRESS), tr("If no arguments are specified or <index> is specified, the wallet shows the default or specified address. If \"all\" is specified, the wallet shows all the existing addresses in the currently selected account. If \"new \" is specified, the wallet creates a new address with the provided label text (which can be empty). If \"label\" is specified, the wallet sets the label of the address specified by <index> to the provided label text.")); m_cmd_binder.set_handler("integrated_address", boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_integrated_address, _1), tr(USAGE_INTEGRATED_ADDRESS), tr("Encode a payment ID into an integrated address for the current wallet public address (no argument uses a random payment ID), or decode an integrated address to standard address and payment ID")); m_cmd_binder.set_handler("address_book", boost::bind(&simple_wallet::on_command, this, &simple_wallet::address_book,_1), tr(USAGE_ADDRESS_BOOK), tr("Print all entries in the address book, optionally adding/deleting an entry to/from it.")); m_cmd_binder.set_handler("save", boost::bind(&simple_wallet::on_command, this, &simple_wallet::save, _1), tr("Save the wallet data.")); m_cmd_binder.set_handler("save_watch_only", boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_watch_only, _1), tr("Save a watch-only keys file.")); m_cmd_binder.set_handler("viewkey", boost::bind(&simple_wallet::on_command, this, &simple_wallet::viewkey, _1), tr("Display the private view key.")); m_cmd_binder.set_handler("spendkey", boost::bind(&simple_wallet::on_command, this, &simple_wallet::spendkey, _1), tr("Display the private spend key.")); m_cmd_binder.set_handler("seed", boost::bind(&simple_wallet::on_command, this, &simple_wallet::seed, _1), tr("Display the Electrum-style mnemonic seed")); m_cmd_binder.set_handler("restore_height", boost::bind(&simple_wallet::restore_height, this, _1), tr("Display the restore height")); m_cmd_binder.set_handler("set", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_variable, _1), tr(USAGE_SET_VARIABLE), tr("Available options:\n " "seed language\n " " Set the wallet's seed language.\n " "always-confirm-transfers <1|0>\n " " Whether to confirm unsplit txes.\n " "print-ring-members <1|0>\n " " Whether to print detailed information about ring members during confirmation.\n " "store-tx-info <1|0>\n " " Whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference.\n " "default-ring-size <n>\n " " Set the default ring size (obsolete).\n " "auto-refresh <1|0>\n " " Whether to automatically synchronize new blocks from the daemon.\n " "refresh-type <full|optimize-coinbase|no-coinbase|default>\n " " Set the wallet's refresh behaviour.\n " "priority [0|1|2|3|4]\n " " Set the fee to default/unimportant/normal/elevated/priority.\n " "confirm-missing-payment-id <1|0> (obsolete)\n " "ask-password <0|1|2 (or never|action|decrypt)>\n " " action: ask the password before many actions such as transfer, etc\n " " decrypt: same as action, but keeps the spend key encrypted in memory when not needed\n " "unit <coinevo|millinero|micronero|nanonero|piconero>\n " " Set the default coinevo (sub-)unit.\n " "min-outputs-count [n]\n " " Try to keep at least that many outputs of value at least min-outputs-value.\n " "min-outputs-value [n]\n " " Try to keep at least min-outputs-count outputs of at least that value.\n " "merge-destinations <1|0>\n " " Whether to merge multiple payments to the same destination address.\n " "confirm-backlog <1|0>\n " " Whether to warn if there is transaction backlog.\n " "confirm-backlog-threshold [n]\n " " Set a threshold for confirm-backlog to only warn if the transaction backlog is greater than n blocks.\n " "confirm-export-overwrite <1|0>\n " " Whether to warn if the file to be exported already exists.\n " "refresh-from-block-height [n]\n " " Set the height before which to ignore blocks.\n " "auto-low-priority <1|0>\n " " Whether to automatically use the low priority fee level when it's safe to do so.\n " "segregate-pre-fork-outputs <1|0>\n " " Set this if you intend to spend outputs on both Coinevo AND a key reusing fork.\n " "key-reuse-mitigation2 <1|0>\n " " Set this if you are not sure whether you will spend on a key reusing Coinevo fork later.\n " "subaddress-lookahead <major>:<minor>\n " " Set the lookahead sizes for the subaddress hash table.\n " "segregation-height <n>\n " " Set to the height of a key reusing fork you want to use, 0 to use default.\n " "ignore-fractional-outputs <1|0>\n " " Whether to ignore fractional outputs that result in net loss when spending due to fee.\n " "ignore-outputs-above <amount>\n " " Ignore outputs of amount above this threshold when spending. Value 0 is translated to the maximum value (18 million) which disables this filter.\n " "ignore-outputs-below <amount>\n " " Ignore outputs of amount below this threshold when spending.\n " "track-uses <1|0>\n " " Whether to keep track of owned outputs uses.\n " "setup-background-mining <1|0>\n " " Whether to enable background mining. Set this to support the network and to get a chance to receive new coinevo.\n " "device-name <device_name[:device_spec]>\n " " Device name for hardware wallet.\n " "export-format <\"binary\"|\"ascii\">\n " " Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n " "persistent-client-id <1|0>\n " " Whether to keep using the same client id for RPC payment over wallet restarts.\n" "auto-mine-for-rpc-payment-threshold <float>\n " " Whether to automatically start mining for RPC payment if the daemon requires it.\n" "credits-target <unsigned int>\n" " The RPC payment credits balance to target (0 for default).")); m_cmd_binder.set_handler("encrypted_seed", boost::bind(&simple_wallet::on_command, this, &simple_wallet::encrypted_seed, _1), tr("Display the encrypted Electrum-style mnemonic seed.")); m_cmd_binder.set_handler("rescan_spent", boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_spent, _1), tr("Rescan the blockchain for spent outputs.")); m_cmd_binder.set_handler("get_tx_key", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_key, _1), tr(USAGE_GET_TX_KEY), tr("Get the transaction key (r) for a given <txid>.")); m_cmd_binder.set_handler("set_tx_key", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_key, _1), tr(USAGE_SET_TX_KEY), tr("Set the transaction key (r) for a given <txid> in case the tx was made by some other device or 3rd party wallet.")); m_cmd_binder.set_handler("check_tx_key", boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_key, _1), tr(USAGE_CHECK_TX_KEY), tr("Check the amount going to <address> in <txid>.")); m_cmd_binder.set_handler("get_tx_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_proof, _1), tr(USAGE_GET_TX_PROOF), tr("Generate a signature proving funds sent to <address> in <txid>, optionally with a challenge string <message>, using either the transaction secret key (when <address> is not your wallet's address) or the view secret key (otherwise), which does not disclose the secret key.")); m_cmd_binder.set_handler("check_tx_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_proof, _1), tr(USAGE_CHECK_TX_PROOF), tr("Check the proof for funds going to <address> in <txid> with the challenge string <message> if any.")); m_cmd_binder.set_handler("get_spend_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_spend_proof, _1), tr(USAGE_GET_SPEND_PROOF), tr("Generate a signature proving that you generated <txid> using the spend secret key, optionally with a challenge string <message>.")); m_cmd_binder.set_handler("check_spend_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_spend_proof, _1), tr(USAGE_CHECK_SPEND_PROOF), tr("Check a signature proving that the signer generated <txid>, optionally with a challenge string <message>.")); m_cmd_binder.set_handler("get_reserve_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_reserve_proof, _1), tr(USAGE_GET_RESERVE_PROOF), tr("Generate a signature proving that you own at least this much, optionally with a challenge string <message>.\n" "If 'all' is specified, you prove the entire sum of all of your existing accounts' balances.\n" "Otherwise, you prove the reserve of the smallest possible amount above <amount> available in your current account.")); m_cmd_binder.set_handler("check_reserve_proof", boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_reserve_proof, _1), tr(USAGE_CHECK_RESERVE_PROOF), tr("Check a signature proving that the owner of <address> holds at least this much, optionally with a challenge string <message>.")); m_cmd_binder.set_handler("show_transfers", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfers, _1), tr(USAGE_SHOW_TRANSFERS), // Seemingly broken formatting to compensate for the backslash before the quotes. tr("Show the incoming/outgoing transfers within an optional height range.\n\n" "Output format:\n" "In or Coinbase: Block Number, \"block\"|\"in\", Time, Amount, Transaction Hash, Payment ID, Subaddress Index, \"-\", Note\n" "Out: Block Number, \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Destinations, Input addresses**, \"-\", Note\n" "Pool: \"pool\", \"in\", Time, Amount, Transaction Hash, Payment Id, Subaddress Index, \"-\", Note, Double Spend Note\n" "Pending or Failed: \"failed\"|\"pending\", \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Input addresses**, \"-\", Note\n\n" "* Excluding change and fee.\n" "** Set of address indices used as inputs in this transfer.")); m_cmd_binder.set_handler("export_transfers", boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_transfers, _1), tr("export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<filepath>]"), tr("Export to CSV the incoming/outgoing transfers within an optional height range.")); m_cmd_binder.set_handler("unspent_outputs", boost::bind(&simple_wallet::on_command, this, &simple_wallet::unspent_outputs, _1), tr(USAGE_UNSPENT_OUTPUTS), tr("Show the unspent outputs of a specified address within an optional amount range.")); m_cmd_binder.set_handler("rescan_bc", boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_blockchain, _1), tr(USAGE_RESCAN_BC), tr("Rescan the blockchain from scratch. If \"hard\" is specified, you will lose any information which can not be recovered from the blockchain itself.")); m_cmd_binder.set_handler("set_tx_note", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_note, _1), tr(USAGE_SET_TX_NOTE), tr("Set an arbitrary string note for a <txid>.")); m_cmd_binder.set_handler("get_tx_note", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_note, _1), tr(USAGE_GET_TX_NOTE), tr("Get a string note for a txid.")); m_cmd_binder.set_handler("set_description", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_description, _1), tr(USAGE_SET_DESCRIPTION), tr("Set an arbitrary description for the wallet.")); m_cmd_binder.set_handler("get_description", boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_description, _1), tr(USAGE_GET_DESCRIPTION), tr("Get the description of the wallet.")); m_cmd_binder.set_handler("status", boost::bind(&simple_wallet::on_command, this, &simple_wallet::status, _1), tr("Show the wallet's status.")); m_cmd_binder.set_handler("wallet_info", boost::bind(&simple_wallet::on_command, this, &simple_wallet::wallet_info, _1), tr("Show the wallet's information.")); m_cmd_binder.set_handler("sign", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign, _1), tr(USAGE_SIGN), tr("Sign the contents of a file.")); m_cmd_binder.set_handler("verify", boost::bind(&simple_wallet::on_command, this, &simple_wallet::verify, _1), tr(USAGE_VERIFY), tr("Verify a signature on the contents of a file.")); m_cmd_binder.set_handler("export_key_images", boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_key_images, _1), tr(USAGE_EXPORT_KEY_IMAGES), tr("Export a signed set of key images to a <filename>.")); m_cmd_binder.set_handler("import_key_images", boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_key_images, _1), tr(USAGE_IMPORT_KEY_IMAGES), tr("Import a signed key images list and verify their spent status.")); m_cmd_binder.set_handler("hw_key_images_sync", boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_key_images_sync, _1), tr(USAGE_HW_KEY_IMAGES_SYNC), tr("Synchronizes key images with the hw wallet.")); m_cmd_binder.set_handler("hw_reconnect", boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_reconnect, _1), tr(USAGE_HW_RECONNECT), tr("Attempts to reconnect HW wallet.")); m_cmd_binder.set_handler("export_outputs", boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_outputs, _1), tr(USAGE_EXPORT_OUTPUTS), tr("Export a set of outputs owned by this wallet.")); m_cmd_binder.set_handler("import_outputs", boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_outputs, _1), tr(USAGE_IMPORT_OUTPUTS), tr("Import a set of outputs owned by this wallet.")); m_cmd_binder.set_handler("show_transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfer, _1), tr(USAGE_SHOW_TRANSFER), tr("Show information about a transfer to/from this address.")); m_cmd_binder.set_handler("password", boost::bind(&simple_wallet::on_command, this, &simple_wallet::change_password, _1), tr("Change the wallet's password.")); m_cmd_binder.set_handler("payment_id", boost::bind(&simple_wallet::on_command, this, &simple_wallet::payment_id, _1), tr(USAGE_PAYMENT_ID), tr("Generate a new random full size payment id (obsolete). These will be unencrypted on the blockchain, see integrated_address for encrypted short payment ids.")); m_cmd_binder.set_handler("fee", boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_fee_info, _1), tr("Print the information about the current fee and transaction backlog.")); m_cmd_binder.set_handler("prepare_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::prepare_multisig, _1), tr("Export data needed to create a multisig wallet")); m_cmd_binder.set_handler("make_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::make_multisig, _1), tr(USAGE_MAKE_MULTISIG), tr("Turn this wallet into a multisig wallet")); m_cmd_binder.set_handler("finalize_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::finalize_multisig, _1), tr(USAGE_FINALIZE_MULTISIG), tr("Turn this wallet into a multisig wallet, extra step for N-1/N wallets")); m_cmd_binder.set_handler("exchange_multisig_keys", boost::bind(&simple_wallet::on_command, this, &simple_wallet::exchange_multisig_keys, _1), tr(USAGE_EXCHANGE_MULTISIG_KEYS), tr("Performs extra multisig keys exchange rounds. Needed for arbitrary M/N multisig wallets")); m_cmd_binder.set_handler("export_multisig_info", boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_multisig, _1), tr(USAGE_EXPORT_MULTISIG_INFO), tr("Export multisig info for other participants")); m_cmd_binder.set_handler("import_multisig_info", boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_multisig, _1), tr(USAGE_IMPORT_MULTISIG_INFO), tr("Import multisig info from other participants")); m_cmd_binder.set_handler("sign_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_multisig, _1), tr(USAGE_SIGN_MULTISIG), tr("Sign a multisig transaction from a file")); m_cmd_binder.set_handler("submit_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_multisig, _1), tr(USAGE_SUBMIT_MULTISIG), tr("Submit a signed multisig transaction from a file")); m_cmd_binder.set_handler("export_raw_multisig_tx", boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_raw_multisig, _1), tr(USAGE_EXPORT_RAW_MULTISIG_TX), tr("Export a signed multisig transaction to a file")); m_cmd_binder.set_handler("mms", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS), tr("Interface with the MMS (Multisig Messaging System)\n" "<subcommand> is one of:\n" " init, info, signer, list, next, sync, transfer, delete, send, receive, export, note, show, set, help\n" " send_signer_config, start_auto_config, stop_auto_config, auto_config\n" "Get help about a subcommand with: help mms <subcommand>, or mms help <subcommand>")); m_cmd_binder.set_handler("mms init", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_INIT), tr("Initialize and configure the MMS for M/N = number of required signers/number of authorized signers multisig")); m_cmd_binder.set_handler("mms info", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_INFO), tr("Display current MMS configuration")); m_cmd_binder.set_handler("mms signer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_SIGNER), tr("Set or modify authorized signer info (single-word label, transport address, Coinevo address), or list all signers")); m_cmd_binder.set_handler("mms list", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_LIST), tr("List all messages")); m_cmd_binder.set_handler("mms next", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_NEXT), tr("Evaluate the next possible multisig-related action(s) according to wallet state, and execute or offer for choice\n" "By using 'sync' processing of waiting messages with multisig sync info can be forced regardless of wallet state")); m_cmd_binder.set_handler("mms sync", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_SYNC), tr("Force generation of multisig sync info regardless of wallet state, to recover from special situations like \"stale data\" errors")); m_cmd_binder.set_handler("mms transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_TRANSFER), tr("Initiate transfer with MMS support; arguments identical to normal 'transfer' command arguments, for info see there")); m_cmd_binder.set_handler("mms delete", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_DELETE), tr("Delete a single message by giving its id, or delete all messages by using 'all'")); m_cmd_binder.set_handler("mms send", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_SEND), tr("Send a single message by giving its id, or send all waiting messages")); m_cmd_binder.set_handler("mms receive", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_RECEIVE), tr("Check right away for new messages to receive")); m_cmd_binder.set_handler("mms export", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_EXPORT), tr("Write the content of a message to a file \"mms_message_content\"")); m_cmd_binder.set_handler("mms note", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_NOTE), tr("Send a one-line message to an authorized signer, identified by its label, or show any waiting unread notes")); m_cmd_binder.set_handler("mms show", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_SHOW), tr("Show detailed info about a single message")); m_cmd_binder.set_handler("mms set", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_SET), tr("Available options:\n " "auto-send <1|0>\n " " Whether to automatically send newly generated messages right away.\n ")); m_cmd_binder.set_handler("mms send_signer_config", boost::bind(&simple_wallet::mms, this, _1), tr(USAGE_MMS_SEND_SIGNER_CONFIG), tr("Send completed signer config to all other authorized signers")); m_cmd_binder.set_handler("mms start_auto_config", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_START_AUTO_CONFIG), tr("Start auto-config at the auto-config manager's wallet by issuing auto-config tokens and optionally set others' labels")); m_cmd_binder.set_handler("mms stop_auto_config", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_STOP_AUTO_CONFIG), tr("Delete any auto-config tokens and abort a auto-config process")); m_cmd_binder.set_handler("mms auto_config", boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1), tr(USAGE_MMS_AUTO_CONFIG), tr("Start auto-config by using the token received from the auto-config manager")); m_cmd_binder.set_handler("print_ring", boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_ring, _1), tr(USAGE_PRINT_RING), tr("Print the ring(s) used to spend a given key image or transaction (if the ring size is > 1)\n\n" "Output format:\n" "Key Image, \"absolute\", list of rings")); m_cmd_binder.set_handler("set_ring", boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_ring, _1), tr(USAGE_SET_RING), tr("Set the ring used for a given key image, so it can be reused in a fork")); m_cmd_binder.set_handler("unset_ring", boost::bind(&simple_wallet::on_command, this, &simple_wallet::unset_ring, _1), tr(USAGE_UNSET_RING), tr("Unsets the ring used for a given key image or transaction")); m_cmd_binder.set_handler("save_known_rings", boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_known_rings, _1), tr(USAGE_SAVE_KNOWN_RINGS), tr("Save known rings to the shared rings database")); m_cmd_binder.set_handler("mark_output_spent", boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackball, _1), tr(USAGE_MARK_OUTPUT_SPENT), tr("Mark output(s) as spent so they never get selected as fake outputs in a ring")); m_cmd_binder.set_handler("mark_output_unspent", boost::bind(&simple_wallet::on_command, this, &simple_wallet::unblackball, _1), tr(USAGE_MARK_OUTPUT_UNSPENT), tr("Marks an output as unspent so it may get selected as a fake output in a ring")); m_cmd_binder.set_handler("is_output_spent", boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackballed, _1), tr(USAGE_IS_OUTPUT_SPENT), tr("Checks whether an output is marked as spent")); m_cmd_binder.set_handler("freeze", boost::bind(&simple_wallet::on_command, this, &simple_wallet::freeze, _1), tr(USAGE_FREEZE), tr("Freeze a single output by key image so it will not be used")); m_cmd_binder.set_handler("thaw", boost::bind(&simple_wallet::on_command, this, &simple_wallet::thaw, _1), tr(USAGE_THAW), tr("Thaw a single output by key image so it may be used again")); m_cmd_binder.set_handler("frozen", boost::bind(&simple_wallet::on_command, this, &simple_wallet::frozen, _1), tr(USAGE_FROZEN), tr("Checks whether a given output is currently frozen by key image")); m_cmd_binder.set_handler("lock", boost::bind(&simple_wallet::on_command, this, &simple_wallet::lock, _1), tr(USAGE_LOCK), tr("Lock the wallet console, requiring the wallet password to continue")); m_cmd_binder.set_handler("net_stats", boost::bind(&simple_wallet::on_command, this, &simple_wallet::net_stats, _1), tr(USAGE_NET_STATS), tr("Prints simple network stats")); m_cmd_binder.set_handler("public_nodes", boost::bind(&simple_wallet::public_nodes, this, _1), tr(USAGE_PUBLIC_NODES), tr("Lists known public nodes")); m_cmd_binder.set_handler("welcome", boost::bind(&simple_wallet::on_command, this, &simple_wallet::welcome, _1), tr(USAGE_WELCOME), tr("Prints basic info about Coinevo for first time users")); m_cmd_binder.set_handler("version", boost::bind(&simple_wallet::on_command, this, &simple_wallet::version, _1), tr(USAGE_VERSION), tr("Returns version information")); m_cmd_binder.set_handler("rpc_payment_info", boost::bind(&simple_wallet::rpc_payment_info, this, _1), tr(USAGE_RPC_PAYMENT_INFO), tr("Get info about RPC payments to current node")); m_cmd_binder.set_handler("start_mining_for_rpc", boost::bind(&simple_wallet::start_mining_for_rpc, this, _1), tr(USAGE_START_MINING_FOR_RPC), tr("Start mining to pay for RPC access")); m_cmd_binder.set_handler("stop_mining_for_rpc", boost::bind(&simple_wallet::stop_mining_for_rpc, this, _1), tr(USAGE_STOP_MINING_FOR_RPC), tr("Stop mining to pay for RPC access")); m_cmd_binder.set_handler("help", boost::bind(&simple_wallet::on_command, this, &simple_wallet::help, _1), tr(USAGE_HELP), tr("Show the help section or the documentation about a <command>.")); m_cmd_binder.set_unknown_command_handler(boost::bind(&simple_wallet::on_command, this, &simple_wallet::on_unknown_command, _1)); m_cmd_binder.set_empty_command_handler(boost::bind(&simple_wallet::on_empty_command, this)); m_cmd_binder.set_cancel_handler(boost::bind(&simple_wallet::on_cancelled_command, this)); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_variable(const std::vector<std::string> &args) { if (args.empty()) { std::string seed_language = m_wallet->get_seed_language(); if (m_use_english_language_names) seed_language = crypto::ElectrumWords::get_english_name_for(seed_language); std::string priority_string = "invalid"; uint32_t priority = m_wallet->get_default_priority(); if (priority < allowed_priority_strings.size()) priority_string = allowed_priority_strings[priority]; std::string ask_password_string = "invalid"; switch (m_wallet->ask_password()) { case tools::wallet2::AskPasswordNever: ask_password_string = "never"; break; case tools::wallet2::AskPasswordOnAction: ask_password_string = "action"; break; case tools::wallet2::AskPasswordToDecrypt: ask_password_string = "decrypt"; break; } std::string setup_background_mining_string = "invalid"; switch (m_wallet->setup_background_mining()) { case tools::wallet2::BackgroundMiningMaybe: setup_background_mining_string = "maybe"; break; case tools::wallet2::BackgroundMiningYes: setup_background_mining_string = "yes"; break; case tools::wallet2::BackgroundMiningNo: setup_background_mining_string = "no"; break; } success_msg_writer() << "seed = " << seed_language; success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers(); success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members(); success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info(); success_msg_writer() << "default-ring-size = " << (m_wallet->default_mixin() ? m_wallet->default_mixin() + 1 : 0); success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh(); success_msg_writer() << "refresh-type = " << get_refresh_type_name(m_wallet->get_refresh_type()); success_msg_writer() << "priority = " << priority<< " (" << priority_string << ")"; success_msg_writer() << "ask-password = " << m_wallet->ask_password() << " (" << ask_password_string << ")"; success_msg_writer() << "unit = " << cryptonote::get_unit(cryptonote::get_default_decimal_point()); success_msg_writer() << "min-outputs-count = " << m_wallet->get_min_output_count(); success_msg_writer() << "min-outputs-value = " << cryptonote::print_money(m_wallet->get_min_output_value()); success_msg_writer() << "merge-destinations = " << m_wallet->merge_destinations(); success_msg_writer() << "confirm-backlog = " << m_wallet->confirm_backlog(); success_msg_writer() << "confirm-backlog-threshold = " << m_wallet->get_confirm_backlog_threshold(); success_msg_writer() << "confirm-export-overwrite = " << m_wallet->confirm_export_overwrite(); success_msg_writer() << "refresh-from-block-height = " << m_wallet->get_refresh_from_block_height(); success_msg_writer() << "auto-low-priority = " << m_wallet->auto_low_priority(); success_msg_writer() << "segregate-pre-fork-outputs = " << m_wallet->segregate_pre_fork_outputs(); success_msg_writer() << "key-reuse-mitigation2 = " << m_wallet->key_reuse_mitigation2(); const std::pair<size_t, size_t> lookahead = m_wallet->get_subaddress_lookahead(); success_msg_writer() << "subaddress-lookahead = " << lookahead.first << ":" << lookahead.second; success_msg_writer() << "segregation-height = " << m_wallet->segregation_height(); success_msg_writer() << "ignore-fractional-outputs = " << m_wallet->ignore_fractional_outputs(); success_msg_writer() << "ignore-outputs-above = " << cryptonote::print_money(m_wallet->ignore_outputs_above()); success_msg_writer() << "ignore-outputs-below = " << cryptonote::print_money(m_wallet->ignore_outputs_below()); success_msg_writer() << "track-uses = " << m_wallet->track_uses(); success_msg_writer() << "setup-background-mining = " << setup_background_mining_string; success_msg_writer() << "device-name = " << m_wallet->device_name(); success_msg_writer() << "export-format = " << (m_wallet->export_format() == tools::wallet2::ExportFormat::Ascii ? "ascii" : "binary"); success_msg_writer() << "inactivity-lock-timeout = " << m_wallet->inactivity_lock_timeout() #ifdef _WIN32 << " (disabled on Windows)" #endif ; success_msg_writer() << "persistent-rpc-client-id = " << m_wallet->persistent_rpc_client_id(); success_msg_writer() << "auto-mine-for-rpc-payment-threshold = " << m_wallet->auto_mine_for_rpc_payment_threshold(); success_msg_writer() << "credits-target = " << m_wallet->credits_target(); return true; } else { #define CHECK_SIMPLE_VARIABLE(name, f, help) do \ if (args[0] == name) { \ if (args.size() <= 1) \ { \ fail_msg_writer() << "set " << #name << ": " << tr("needs an argument") << " (" << help << ")"; \ return true; \ } \ else \ { \ f(args); \ return true; \ } \ } while(0) if (args[0] == "seed") { if (args.size() == 1) { fail_msg_writer() << tr("set seed: needs an argument. available options: language"); return true; } else if (args[1] == "language") { seed_set_language(args); return true; } } CHECK_SIMPLE_VARIABLE("always-confirm-transfers", set_always_confirm_transfers, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("print-ring-members", set_print_ring_members, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("store-tx-info", set_store_tx_info, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("default-ring-size", set_default_ring_size, tr("integer >= ") << MIN_RING_SIZE); CHECK_SIMPLE_VARIABLE("auto-refresh", set_auto_refresh, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("refresh-type", set_refresh_type, tr("full (slowest, no assumptions); optimize-coinbase (fast, assumes the whole coinbase is paid to a single address); no-coinbase (fastest, assumes we receive no coinbase transaction), default (same as optimize-coinbase)")); CHECK_SIMPLE_VARIABLE("priority", set_default_priority, tr("0, 1, 2, 3, or 4, or one of ") << join_priority_strings(", ")); CHECK_SIMPLE_VARIABLE("ask-password", set_ask_password, tr("0|1|2 (or never|action|decrypt)")); CHECK_SIMPLE_VARIABLE("unit", set_unit, tr("coinevo, millinero, micronero, nanonero, piconero")); CHECK_SIMPLE_VARIABLE("min-outputs-count", set_min_output_count, tr("unsigned integer")); CHECK_SIMPLE_VARIABLE("min-outputs-value", set_min_output_value, tr("amount")); CHECK_SIMPLE_VARIABLE("merge-destinations", set_merge_destinations, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("confirm-backlog", set_confirm_backlog, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("confirm-backlog-threshold", set_confirm_backlog_threshold, tr("unsigned integer")); CHECK_SIMPLE_VARIABLE("confirm-export-overwrite", set_confirm_export_overwrite, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("refresh-from-block-height", set_refresh_from_block_height, tr("block height")); CHECK_SIMPLE_VARIABLE("auto-low-priority", set_auto_low_priority, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("segregate-pre-fork-outputs", set_segregate_pre_fork_outputs, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("key-reuse-mitigation2", set_key_reuse_mitigation2, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("subaddress-lookahead", set_subaddress_lookahead, tr("<major>:<minor>")); CHECK_SIMPLE_VARIABLE("segregation-height", set_segregation_height, tr("unsigned integer")); CHECK_SIMPLE_VARIABLE("ignore-fractional-outputs", set_ignore_fractional_outputs, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("ignore-outputs-above", set_ignore_outputs_above, tr("amount")); CHECK_SIMPLE_VARIABLE("ignore-outputs-below", set_ignore_outputs_below, tr("amount")); CHECK_SIMPLE_VARIABLE("track-uses", set_track_uses, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("inactivity-lock-timeout", set_inactivity_lock_timeout, tr("unsigned integer (seconds, 0 to disable)")); CHECK_SIMPLE_VARIABLE("setup-background-mining", set_setup_background_mining, tr("1/yes or 0/no")); CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("<device_name[:device_spec]>")); CHECK_SIMPLE_VARIABLE("export-format", set_export_format, tr("\"binary\" or \"ascii\"")); CHECK_SIMPLE_VARIABLE("persistent-rpc-client-id", set_persistent_rpc_client_id, tr("0 or 1")); CHECK_SIMPLE_VARIABLE("auto-mine-for-rpc-payment-threshold", set_auto_mine_for_rpc_payment_threshold, tr("floating point >= 0")); CHECK_SIMPLE_VARIABLE("credits-target", set_credits_target, tr("unsigned integer")); } fail_msg_writer() << tr("set: unrecognized argument(s)"); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_log(const std::vector<std::string> &args) { if(args.size() > 1) { PRINT_USAGE(USAGE_SET_LOG); return true; } if(!args.empty()) { uint16_t level = 0; if(epee::string_tools::get_xtype_from_string(level, args[0])) { if(4 < level) { fail_msg_writer() << boost::format(tr("wrong number range, use: %s")) % USAGE_SET_LOG; return true; } mlog_set_log_level(level); } else { mlog_set_log(args[0].c_str()); } } success_msg_writer() << "New log categories: " << mlog_get_categories(); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::ask_wallet_create_if_needed() { LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started"); std::string wallet_path; std::string confirm_creation; bool wallet_name_valid = false; bool keys_file_exists; bool wallet_file_exists; do{ LOG_PRINT_L3("User asked to specify wallet file name."); wallet_path = input_line( tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n" "Wallet file name (or Ctrl-C to quit)" : "Specify wallet file name (e.g., MyWallet). If the wallet doesn't exist, it will be created.\n" "Wallet file name (or Ctrl-C to quit)") ); if(std::cin.eof()) { LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } if(!tools::wallet2::wallet_valid_path_format(wallet_path)) { fail_msg_writer() << tr("Wallet name not valid. Please try again or use Ctrl-C to quit."); wallet_name_valid = false; } else { tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists); LOG_PRINT_L3("wallet_path: " << wallet_path << ""); LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring)) { fail_msg_writer() << tr("Attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting."); return false; } if(wallet_file_exists && keys_file_exists) //Yes wallet, yes keys { success_msg_writer() << tr("Wallet and key files found, loading..."); m_wallet_file = wallet_path; return true; } else if(!wallet_file_exists && keys_file_exists) //No wallet, yes keys { success_msg_writer() << tr("Key file found but not wallet file. Regenerating..."); m_wallet_file = wallet_path; return true; } else if(wallet_file_exists && !keys_file_exists) //Yes wallet, no keys { fail_msg_writer() << tr("Key file not found. Failed to open wallet: ") << "\"" << wallet_path << "\". Exiting."; return false; } else if(!wallet_file_exists && !keys_file_exists) //No wallet, no keys { bool ok = true; if (!m_restoring) { message_writer() << tr("No wallet found with that name. Confirm creation of new wallet named: ") << wallet_path; confirm_creation = input_line("", true); if(std::cin.eof()) { LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } ok = command_line::is_yes(confirm_creation); } if (ok) { success_msg_writer() << tr("Generating new wallet..."); m_generate_new = wallet_path; return true; } } } } while(!wallet_name_valid); LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()"); return false; } /*! * \brief Prints the seed with a nice message * \param seed seed to print */ void simple_wallet::print_seed(const epee::wipeable_string &seed) { success_msg_writer(true) << "\n" << boost::format(tr("NOTE: the following %s can be used to recover access to your wallet. " "Write them down and store them somewhere safe and secure. Please do not store them in " "your email or on file storage services outside of your immediate control.\n")) % (m_wallet->multisig() ? tr("string") : tr("25 words")); // don't log int space_index = 0; size_t len = seed.size(); for (const char *ptr = seed.data(); len--; ++ptr) { if (*ptr == ' ') { if (space_index == 15 || space_index == 7) putchar('\n'); else putchar(*ptr); ++space_index; } else putchar(*ptr); } putchar('\n'); fflush(stdout); } //---------------------------------------------------------------------------------------------------- static bool might_be_partial_seed(const epee::wipeable_string &words) { std::vector<epee::wipeable_string> seed; words.split(seed); return seed.size() < 24; } //---------------------------------------------------------------------------------------------------- static bool datestr_to_int(const std::string &heightstr, uint16_t &year, uint8_t &month, uint8_t &day) { if (heightstr.size() != 10 || heightstr[4] != '-' || heightstr[7] != '-') { fail_msg_writer() << tr("date format must be YYYY-MM-DD"); return false; } try { year = boost::lexical_cast<uint16_t>(heightstr.substr(0,4)); // lexical_cast<uint8_t> won't work because uint8_t is treated as character type month = boost::lexical_cast<uint16_t>(heightstr.substr(5,2)); day = boost::lexical_cast<uint16_t>(heightstr.substr(8,2)); } catch (const boost::bad_lexical_cast &) { fail_msg_writer() << tr("bad height parameter: ") << heightstr; return false; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::init(const boost::program_options::variables_map& vm) { epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ m_electrum_seed.wipe(); }); const bool testnet = tools::wallet2::has_testnet_option(vm); const bool stagenet = tools::wallet2::has_stagenet_option(vm); if (testnet && stagenet) { fail_msg_writer() << tr("Can't specify more than one of --testnet and --stagenet"); return false; } const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET; epee::wipeable_string multisig_keys; epee::wipeable_string password; if (!handle_command_line(vm)) return false; bool welcome = false; if((!m_generate_new.empty()) + (!m_wallet_file.empty()) + (!m_generate_from_device.empty()) + (!m_generate_from_view_key.empty()) + (!m_generate_from_spend_key.empty()) + (!m_generate_from_keys.empty()) + (!m_generate_from_multisig_keys.empty()) + (!m_generate_from_json.empty()) > 1) { fail_msg_writer() << tr("can't specify more than one of --generate-new-wallet=\"wallet_name\", --wallet-file=\"wallet_name\", --generate-from-view-key=\"wallet_name\", --generate-from-spend-key=\"wallet_name\", --generate-from-keys=\"wallet_name\", --generate-from-multisig-keys=\"wallet_name\", --generate-from-json=\"jsonfilename\" and --generate-from-device=\"wallet_name\""); return false; } else if (m_generate_new.empty() && m_wallet_file.empty() && m_generate_from_device.empty() && m_generate_from_view_key.empty() && m_generate_from_spend_key.empty() && m_generate_from_keys.empty() && m_generate_from_multisig_keys.empty() && m_generate_from_json.empty()) { if(!ask_wallet_create_if_needed()) return false; } if (!m_generate_new.empty() || m_restoring) { if (!m_subaddress_lookahead.empty() && !parse_subaddress_lookahead(m_subaddress_lookahead)) return false; std::string old_language; // check for recover flag. if present, require electrum word list (only recovery option for now). if (m_restore_deterministic_wallet || m_restore_multisig_wallet) { if (m_non_deterministic) { fail_msg_writer() << tr("can't specify both --restore-deterministic-wallet or --restore-multisig-wallet and --non-deterministic"); return false; } if (!m_wallet_file.empty()) { if (m_restore_multisig_wallet) fail_msg_writer() << tr("--restore-multisig-wallet uses --generate-new-wallet, not --wallet-file"); else fail_msg_writer() << tr("--restore-deterministic-wallet uses --generate-new-wallet, not --wallet-file"); return false; } if (m_electrum_seed.empty()) { if (m_restore_multisig_wallet) { const char *prompt = "Specify multisig seed"; m_electrum_seed = input_secure_line(prompt); if (std::cin.eof()) return false; if (m_electrum_seed.empty()) { fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"multisig seed here\""); return false; } } else { m_electrum_seed = ""; do { const char *prompt = m_electrum_seed.empty() ? "Specify Electrum seed" : "Electrum seed continued"; epee::wipeable_string electrum_seed = input_secure_line(prompt); if (std::cin.eof()) return false; if (electrum_seed.empty()) { fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"words list here\""); return false; } m_electrum_seed += electrum_seed; m_electrum_seed += ' '; } while (might_be_partial_seed(m_electrum_seed)); } } if (m_restore_multisig_wallet) { const boost::optional<epee::wipeable_string> parsed = m_electrum_seed.parse_hexstr(); if (!parsed) { fail_msg_writer() << tr("Multisig seed failed verification"); return false; } multisig_keys = *parsed; } else { if (!crypto::ElectrumWords::words_to_bytes(m_electrum_seed, m_recovery_key, old_language)) { fail_msg_writer() << tr("Electrum-style word list failed verification"); return false; } } auto pwd_container = password_prompter(tr("Enter seed offset passphrase, empty if none"), false); if (std::cin.eof() || !pwd_container) return false; epee::wipeable_string seed_pass = pwd_container->password(); if (!seed_pass.empty()) { if (m_restore_multisig_wallet) { crypto::secret_key key; crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key); sc_reduce32((unsigned char*)key.data); multisig_keys = m_wallet->decrypt<epee::wipeable_string>(std::string(multisig_keys.data(), multisig_keys.size()), key, true); } else m_recovery_key = cryptonote::decrypt_key(m_recovery_key, seed_pass); } } if (!m_generate_from_view_key.empty()) { m_wallet_file = m_generate_from_view_key; // parse address std::string address_string = input_line("Standard address"); if (std::cin.eof()) return false; if (address_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } cryptonote::address_parse_info info; if(!get_account_address_from_str(info, nettype, address_string)) { fail_msg_writer() << tr("failed to parse address"); return false; } if (info.is_subaddress) { fail_msg_writer() << tr("This address is a subaddress which cannot be used here."); return false; } // parse view secret key epee::wipeable_string viewkey_string = input_secure_line("Secret view key"); if (std::cin.eof()) return false; if (viewkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } crypto::secret_key viewkey; if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey)))) { fail_msg_writer() << tr("failed to parse view key secret key"); return false; } m_wallet_file=m_generate_from_view_key; // check the view key matches the given address crypto::public_key pkey; if (!crypto::secret_key_to_public_key(viewkey, pkey)) { fail_msg_writer() << tr("failed to verify view key secret key"); return false; } if (info.address.m_view_public_key != pkey) { fail_msg_writer() << tr("view key does not match standard address"); return false; } auto r = new_wallet(vm, info.address, boost::none, viewkey); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; } else if (!m_generate_from_spend_key.empty()) { m_wallet_file = m_generate_from_spend_key; // parse spend secret key epee::wipeable_string spendkey_string = input_secure_line("Secret spend key"); if (std::cin.eof()) return false; if (spendkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } if (!spendkey_string.hex_to_pod(unwrap(unwrap(m_recovery_key)))) { fail_msg_writer() << tr("failed to parse spend key secret key"); return false; } auto r = new_wallet(vm, m_recovery_key, true, false, ""); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; } else if (!m_generate_from_keys.empty()) { m_wallet_file = m_generate_from_keys; // parse address std::string address_string = input_line("Standard address"); if (std::cin.eof()) return false; if (address_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } cryptonote::address_parse_info info; if(!get_account_address_from_str(info, nettype, address_string)) { fail_msg_writer() << tr("failed to parse address"); return false; } if (info.is_subaddress) { fail_msg_writer() << tr("This address is a subaddress which cannot be used here."); return false; } // parse spend secret key epee::wipeable_string spendkey_string = input_secure_line("Secret spend key"); if (std::cin.eof()) return false; if (spendkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } crypto::secret_key spendkey; if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey)))) { fail_msg_writer() << tr("failed to parse spend key secret key"); return false; } // parse view secret key epee::wipeable_string viewkey_string = input_secure_line("Secret view key"); if (std::cin.eof()) return false; if (viewkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } crypto::secret_key viewkey; if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey)))) { fail_msg_writer() << tr("failed to parse view key secret key"); return false; } m_wallet_file=m_generate_from_keys; // check the spend and view keys match the given address crypto::public_key pkey; if (!crypto::secret_key_to_public_key(spendkey, pkey)) { fail_msg_writer() << tr("failed to verify spend key secret key"); return false; } if (info.address.m_spend_public_key != pkey) { fail_msg_writer() << tr("spend key does not match standard address"); return false; } if (!crypto::secret_key_to_public_key(viewkey, pkey)) { fail_msg_writer() << tr("failed to verify view key secret key"); return false; } if (info.address.m_view_public_key != pkey) { fail_msg_writer() << tr("view key does not match standard address"); return false; } auto r = new_wallet(vm, info.address, spendkey, viewkey); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; } // Asks user for all the data required to merge secret keys from multisig wallets into one master wallet, which then gets full control of the multisig wallet. The resulting wallet will be the same as any other regular wallet. else if (!m_generate_from_multisig_keys.empty()) { m_wallet_file = m_generate_from_multisig_keys; unsigned int multisig_m; unsigned int multisig_n; // parse multisig type std::string multisig_type_string = input_line("Multisig type (input as M/N with M <= N and M > 1)"); if (std::cin.eof()) return false; if (multisig_type_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } if (sscanf(multisig_type_string.c_str(), "%u/%u", &multisig_m, &multisig_n) != 2) { fail_msg_writer() << tr("Error: expected M/N, but got: ") << multisig_type_string; return false; } if (multisig_m <= 1 || multisig_m > multisig_n) { fail_msg_writer() << tr("Error: expected N > 1 and N <= M, but got: ") << multisig_type_string; return false; } if (multisig_m != multisig_n) { fail_msg_writer() << tr("Error: M/N is currently unsupported. "); return false; } message_writer() << boost::format(tr("Generating master wallet from %u of %u multisig wallet keys")) % multisig_m % multisig_n; // parse multisig address std::string address_string = input_line("Multisig wallet address"); if (std::cin.eof()) return false; if (address_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } cryptonote::address_parse_info info; if(!get_account_address_from_str(info, nettype, address_string)) { fail_msg_writer() << tr("failed to parse address"); return false; } // parse secret view key epee::wipeable_string viewkey_string = input_secure_line("Secret view key"); if (std::cin.eof()) return false; if (viewkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } crypto::secret_key viewkey; if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey)))) { fail_msg_writer() << tr("failed to parse secret view key"); return false; } // check that the view key matches the given address crypto::public_key pkey; if (!crypto::secret_key_to_public_key(viewkey, pkey)) { fail_msg_writer() << tr("failed to verify secret view key"); return false; } if (info.address.m_view_public_key != pkey) { fail_msg_writer() << tr("view key does not match standard address"); return false; } // parse multisig spend keys crypto::secret_key spendkey; // parsing N/N if(multisig_m == multisig_n) { std::vector<crypto::secret_key> multisig_secret_spendkeys(multisig_n); epee::wipeable_string spendkey_string; cryptonote::blobdata spendkey_data; // get N secret spend keys from user for(unsigned int i=0; i<multisig_n; ++i) { spendkey_string = input_secure_line(tr((boost::format(tr("Secret spend key (%u of %u)")) % (i+1) % multisig_m).str().c_str())); if (std::cin.eof()) return false; if (spendkey_string.empty()) { fail_msg_writer() << tr("No data supplied, cancelled"); return false; } if(!spendkey_string.hex_to_pod(unwrap(unwrap(multisig_secret_spendkeys[i])))) { fail_msg_writer() << tr("failed to parse spend key secret key"); return false; } } // sum the spend keys together to get the master spend key spendkey = multisig_secret_spendkeys[0]; for(unsigned int i=1; i<multisig_n; ++i) sc_add(reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&multisig_secret_spendkeys[i])); } // parsing M/N else { fail_msg_writer() << tr("Error: M/N is currently unsupported"); return false; } // check that the spend key matches the given address if (!crypto::secret_key_to_public_key(spendkey, pkey)) { fail_msg_writer() << tr("failed to verify spend key secret key"); return false; } if (info.address.m_spend_public_key != pkey) { fail_msg_writer() << tr("spend key does not match standard address"); return false; } // create wallet auto r = new_wallet(vm, info.address, spendkey, viewkey); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; } else if (!m_generate_from_json.empty()) { try { auto rc = tools::wallet2::make_from_json(vm, false, m_generate_from_json, password_prompter); m_wallet = std::move(rc.first); password = rc.second.password(); m_wallet_file = m_wallet->path(); } catch (const std::exception &e) { fail_msg_writer() << e.what(); return false; } if (!m_wallet) return false; } else if (!m_generate_from_device.empty()) { m_wallet_file = m_generate_from_device; // create wallet auto r = new_wallet(vm); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; // if no block_height is specified, assume its a new account and start it "now" if(m_wallet->get_refresh_from_block_height() == 0) { { tools::scoped_message_writer wrt = tools::msg_writer(); wrt << tr("No restore height is specified.") << " "; wrt << tr("Assumed you are creating a new account, restore will be done from current estimated blockchain height.") << " "; wrt << tr("Use --restore-height or --restore-date if you want to restore an already setup account from a specific height."); } std::string confirm = input_line(tr("Is this okay?"), true); if (std::cin.eof() || !command_line::is_yes(confirm)) CHECK_AND_ASSERT_MES(false, false, tr("account creation aborted")); m_wallet->set_refresh_from_block_height(m_wallet->estimate_blockchain_height()); m_wallet->explicit_refresh_from_block_height(true); m_restore_height = m_wallet->get_refresh_from_block_height(); } } else { if (m_generate_new.empty()) { fail_msg_writer() << tr("specify a wallet path with --generate-new-wallet (not --wallet-file)"); return false; } m_wallet_file = m_generate_new; boost::optional<epee::wipeable_string> r; if (m_restore_multisig_wallet) r = new_wallet(vm, multisig_keys, old_language); else r = new_wallet(vm, m_recovery_key, m_restore_deterministic_wallet, m_non_deterministic, old_language); CHECK_AND_ASSERT_MES(r, false, tr("account creation failed")); password = *r; welcome = true; } if (m_restoring && m_generate_from_json.empty() && m_generate_from_device.empty()) { m_wallet->explicit_refresh_from_block_height(!(command_line::is_arg_defaulted(vm, arg_restore_height) && command_line::is_arg_defaulted(vm, arg_restore_date))); if (command_line::is_arg_defaulted(vm, arg_restore_height) && !command_line::is_arg_defaulted(vm, arg_restore_date)) { uint16_t year; uint8_t month; uint8_t day; if (!datestr_to_int(m_restore_date, year, month, day)) return false; try { m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day); success_msg_writer() << tr("Restore height is: ") << m_restore_height; } catch (const std::runtime_error& e) { fail_msg_writer() << e.what(); return false; } } } if (!m_wallet->explicit_refresh_from_block_height() && m_restoring) { uint32_t version; bool connected = try_connect_to_daemon(false, &version); while (true) { std::string heightstr; if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6)) heightstr = input_line("Restore from specific blockchain height (optional, default 0)"); else heightstr = input_line("Restore from specific blockchain height (optional, default 0),\nor alternatively from specific date (YYYY-MM-DD)"); if (std::cin.eof()) return false; if (heightstr.empty()) { m_restore_height = 0; break; } try { m_restore_height = boost::lexical_cast<uint64_t>(heightstr); break; } catch (const boost::bad_lexical_cast &) { if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6)) { fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr; continue; } uint16_t year; uint8_t month; // 1, 2, ..., 12 uint8_t day; // 1, 2, ..., 31 try { if (!datestr_to_int(heightstr, year, month, day)) return false; m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day); success_msg_writer() << tr("Restore height is: ") << m_restore_height; std::string confirm = input_line(tr("Is this okay?"), true); if (std::cin.eof()) return false; if(command_line::is_yes(confirm)) break; } catch (const boost::bad_lexical_cast &) { fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr; } catch (const std::runtime_error& e) { fail_msg_writer() << e.what(); } } } } if (m_restoring) { uint64_t estimate_height = m_wallet->estimate_blockchain_height(); if (m_restore_height >= estimate_height) { success_msg_writer() << tr("Restore height ") << m_restore_height << (" is not yet reached. The current estimated height is ") << estimate_height; std::string confirm = input_line(tr("Still apply restore height?"), true); if (std::cin.eof() || command_line::is_no(confirm)) m_restore_height = 0; } m_wallet->set_refresh_from_block_height(m_restore_height); } m_wallet->rewrite(m_wallet_file, password); } else { assert(!m_wallet_file.empty()); if (!m_subaddress_lookahead.empty()) { fail_msg_writer() << tr("can't specify --subaddress-lookahead and --wallet-file at the same time"); return false; } auto r = open_wallet(vm); CHECK_AND_ASSERT_MES(r, false, tr("failed to open account")); password = *r; } if (!m_wallet) { fail_msg_writer() << tr("wallet is null"); return false; } if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key)) { crypto::secret_key rpc_client_secret_key; if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), rpc_client_secret_key)) { fail_msg_writer() << tr("RPC client secret key should be 32 byte in hex format"); return false; } m_wallet->set_rpc_client_secret_key(rpc_client_secret_key); } if (!m_wallet->is_trusted_daemon()) { message_writer(console_color_red, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str(); message_writer(console_color_red, true) << boost::format(tr("Using a third party daemon can be detrimental to your security and privacy")); bool ssl = false; if (m_wallet->check_connection(NULL, &ssl) && !ssl) message_writer(console_color_red, true) << boost::format(tr("Using your own without SSL exposes your RPC traffic to monitoring")); message_writer(console_color_red, true) << boost::format(tr("You are strongly encouraged to connect to the Coinevo network using your own daemon")); message_writer(console_color_red, true) << boost::format(tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon")); COMMAND_RPC_GET_INFO::request req; COMMAND_RPC_GET_INFO::response res; bool r = m_wallet->invoke_http_json("/get_info", req, res); std::string err = interpret_rpc_response(r, res.status); if (r && err.empty() && (res.was_bootstrap_ever_used || !res.bootstrap_daemon_address.empty())) message_writer(console_color_red, true) << boost::format(tr("Moreover, a daemon is also less secure when running in bootstrap mode")); } if (m_wallet->get_ring_database().empty()) fail_msg_writer() << tr("Failed to initialize ring database: privacy enhancing features will be inactive"); m_wallet->callback(this); bool skip_check_backround_mining = !command_line::get_arg(vm, arg_command).empty(); if (!skip_check_backround_mining) check_background_mining(password); if (welcome) message_writer(console_color_yellow, true) << tr("If you are new to Coinevo, type \"welcome\" for a brief overview."); m_last_activity_time = time(NULL); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::deinit() { if (!m_wallet.get()) return true; return close_wallet(); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::handle_command_line(const boost::program_options::variables_map& vm) { m_wallet_file = command_line::get_arg(vm, arg_wallet_file); m_generate_new = command_line::get_arg(vm, arg_generate_new_wallet); m_generate_from_device = command_line::get_arg(vm, arg_generate_from_device); m_generate_from_view_key = command_line::get_arg(vm, arg_generate_from_view_key); m_generate_from_spend_key = command_line::get_arg(vm, arg_generate_from_spend_key); m_generate_from_keys = command_line::get_arg(vm, arg_generate_from_keys); m_generate_from_multisig_keys = command_line::get_arg(vm, arg_generate_from_multisig_keys); m_generate_from_json = command_line::get_arg(vm, arg_generate_from_json); m_mnemonic_language = command_line::get_arg(vm, arg_mnemonic_language); m_electrum_seed = command_line::get_arg(vm, arg_electrum_seed); m_restore_deterministic_wallet = command_line::get_arg(vm, arg_restore_deterministic_wallet) || command_line::get_arg(vm, arg_restore_from_seed); m_restore_multisig_wallet = command_line::get_arg(vm, arg_restore_multisig_wallet); m_non_deterministic = command_line::get_arg(vm, arg_non_deterministic); m_allow_mismatched_daemon_version = command_line::get_arg(vm, arg_allow_mismatched_daemon_version); m_restore_height = command_line::get_arg(vm, arg_restore_height); m_restore_date = command_line::get_arg(vm, arg_restore_date); m_do_not_relay = command_line::get_arg(vm, arg_do_not_relay); m_subaddress_lookahead = command_line::get_arg(vm, arg_subaddress_lookahead); m_use_english_language_names = command_line::get_arg(vm, arg_use_english_language_names); m_restoring = !m_generate_from_view_key.empty() || !m_generate_from_spend_key.empty() || !m_generate_from_keys.empty() || !m_generate_from_multisig_keys.empty() || !m_generate_from_json.empty() || !m_generate_from_device.empty() || m_restore_deterministic_wallet || m_restore_multisig_wallet; if (!command_line::is_arg_defaulted(vm, arg_restore_date)) { uint16_t year; uint8_t month, day; if (!datestr_to_int(m_restore_date, year, month, day)) return false; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version) { uint32_t version_ = 0; if (!version) version = &version_; if (!m_wallet->check_connection(version)) { if (!silent) fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " << tr("Daemon either is not started or wrong port was passed. " "Please make sure daemon is running or change the daemon address using the 'set_daemon' command."); return false; } if (!m_allow_mismatched_daemon_version && ((*version >> 16) != CORE_RPC_VERSION_MAJOR)) { if (!silent) fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (*version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address(); return false; } return true; } /*! * \brief Gets the word seed language from the user. * * User is asked to choose from a list of supported languages. * * \return The chosen language. */ std::string simple_wallet::get_mnemonic_language() { std::vector<std::string> language_list_self, language_list_english; const std::vector<std::string> &language_list = m_use_english_language_names ? language_list_english : language_list_self; std::string language_choice; int language_number = -1; crypto::ElectrumWords::get_language_list(language_list_self, false); crypto::ElectrumWords::get_language_list(language_list_english, true); std::cout << tr("List of available languages for your wallet's seed:") << std::endl; std::cout << tr("If your display freezes, exit blind with ^C, then run again with --use-english-language-names") << std::endl; int ii; std::vector<std::string>::const_iterator it; for (it = language_list.begin(), ii = 0; it != language_list.end(); it++, ii++) { std::cout << ii << " : " << *it << std::endl; } while (language_number < 0) { language_choice = input_line(tr("Enter the number corresponding to the language of your choice")); if (std::cin.eof()) return std::string(); try { language_number = std::stoi(language_choice); if (!((language_number >= 0) && (static_cast<unsigned int>(language_number) < language_list.size()))) { language_number = -1; fail_msg_writer() << tr("invalid language choice entered. Please try again.\n"); } } catch (const std::exception &e) { fail_msg_writer() << tr("invalid language choice entered. Please try again.\n"); } } return language_list_self[language_number]; } //---------------------------------------------------------------------------------------------------- boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const { auto pwd_container = default_password_prompter(m_wallet_file.empty()); if (!pwd_container) return boost::none; if (!m_wallet->verify_password(pwd_container->password())) { fail_msg_writer() << tr("invalid password"); return boost::none; } return pwd_container; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm, const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language) { std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc; try { rc = tools::wallet2::make_new(vm, false, password_prompter); } catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; } m_wallet = std::move(rc.first); if (!m_wallet) { return {}; } epee::wipeable_string password = rc.second.password(); if (!m_subaddress_lookahead.empty()) { auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead); assert(lookahead); m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second); } bool was_deprecated_wallet = m_restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) || crypto::ElectrumWords::get_is_old_style_seed(m_electrum_seed)); std::string mnemonic_language = old_language; std::vector<std::string> language_list; crypto::ElectrumWords::get_language_list(language_list); if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end()) { mnemonic_language = m_mnemonic_language; } // Ask for seed language if: // it's a deterministic wallet AND // a seed language is not already specified AND // (it is not a wallet restore OR if it was a deprecated wallet // that was earlier used before this restore) if ((!two_random) && (mnemonic_language.empty() || mnemonic_language == crypto::ElectrumWords::old_language_name) && (!m_restore_deterministic_wallet || was_deprecated_wallet)) { if (was_deprecated_wallet) { // The user had used an older version of the wallet with old style mnemonics. message_writer(console_color_green, false) << "\n" << tr("You had been using " "a deprecated version of the wallet. Please use the new seed that we provide.\n"); } mnemonic_language = get_mnemonic_language(); if (mnemonic_language.empty()) return {}; } m_wallet->set_seed_language(mnemonic_language); bool create_address_file = command_line::get_arg(vm, arg_create_address_file); crypto::secret_key recovery_val; try { recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file); message_writer(console_color_white, true) << tr("Generated new wallet: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); PAUSE_READLINE(); std::cout << tr("View key: "); print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key); putchar('\n'); } catch (const std::exception& e) { fail_msg_writer() << tr("failed to generate new wallet: ") << e.what(); return {}; } // convert rng value to electrum-style word list epee::wipeable_string electrum_words; crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language); success_msg_writer() << "**********************************************************************\n" << tr("Your wallet has been generated!\n" "To start synchronizing with the daemon, use the \"refresh\" command.\n" "Use the \"help\" command to see the list of available commands.\n" "Use \"help <command>\" to see a command's documentation.\n" "Always use the \"exit\" command when closing coinevo-wallet-cli to save \n" "your current session's state. Otherwise, you might need to synchronize \n" "your wallet again (your wallet keys are NOT at risk in any case).\n") ; if (!two_random) { print_seed(electrum_words); } success_msg_writer() << "**********************************************************************"; return password; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm, const cryptonote::account_public_address& address, const boost::optional<crypto::secret_key>& spendkey, const crypto::secret_key& viewkey) { std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc; try { rc = tools::wallet2::make_new(vm, false, password_prompter); } catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; } m_wallet = std::move(rc.first); if (!m_wallet) { return {}; } epee::wipeable_string password = rc.second.password(); if (!m_subaddress_lookahead.empty()) { auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead); assert(lookahead); m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second); } if (m_restore_height) m_wallet->set_refresh_from_block_height(m_restore_height); bool create_address_file = command_line::get_arg(vm, arg_create_address_file); try { if (spendkey) { m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, *spendkey, viewkey, create_address_file); } else { m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file); } message_writer(console_color_white, true) << tr("Generated new wallet: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } catch (const std::exception& e) { fail_msg_writer() << tr("failed to generate new wallet: ") << e.what(); return {}; } return password; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm) { std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc; try { rc = tools::wallet2::make_new(vm, false, password_prompter); } catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; } m_wallet = std::move(rc.first); m_wallet->callback(this); if (!m_wallet) { return {}; } epee::wipeable_string password = rc.second.password(); if (!m_subaddress_lookahead.empty()) { auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead); assert(lookahead); m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second); } if (m_restore_height) m_wallet->set_refresh_from_block_height(m_restore_height); auto device_desc = tools::wallet2::device_name_option(vm); auto device_derivation_path = tools::wallet2::device_derivation_path_option(vm); try { bool create_address_file = command_line::get_arg(vm, arg_create_address_file); m_wallet->device_derivation_path(device_derivation_path); m_wallet->restore(m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file); message_writer(console_color_white, true) << tr("Generated new wallet on hw device: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } catch (const std::exception& e) { fail_msg_writer() << tr("failed to generate new wallet: ") << e.what(); return {}; } return password; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm, const epee::wipeable_string &multisig_keys, const std::string &old_language) { std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc; try { rc = tools::wallet2::make_new(vm, false, password_prompter); } catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; } m_wallet = std::move(rc.first); if (!m_wallet) { return {}; } epee::wipeable_string password = rc.second.password(); if (!m_subaddress_lookahead.empty()) { auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead); assert(lookahead); m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second); } std::string mnemonic_language = old_language; std::vector<std::string> language_list; crypto::ElectrumWords::get_language_list(language_list); if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end()) { mnemonic_language = m_mnemonic_language; } m_wallet->set_seed_language(mnemonic_language); bool create_address_file = command_line::get_arg(vm, arg_create_address_file); try { m_wallet->generate(m_wallet_file, std::move(rc.second).password(), multisig_keys, create_address_file); bool ready; uint32_t threshold, total; if (!m_wallet->multisig(&ready, &threshold, &total) || !ready) { fail_msg_writer() << tr("failed to generate new mutlisig wallet"); return {}; } message_writer(console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } catch (const std::exception& e) { fail_msg_writer() << tr("failed to generate new wallet: ") << e.what(); return {}; } return password; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::open_wallet(const boost::program_options::variables_map& vm) { if (!tools::wallet2::wallet_valid_path_format(m_wallet_file)) { fail_msg_writer() << tr("wallet file path not valid: ") << m_wallet_file; return {}; } bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(m_wallet_file, keys_file_exists, wallet_file_exists); if(!keys_file_exists) { fail_msg_writer() << tr("Key file not found. Failed to open wallet"); return {}; } epee::wipeable_string password; try { auto rc = tools::wallet2::make_from_file(vm, false, "", password_prompter); m_wallet = std::move(rc.first); password = std::move(std::move(rc.second).password()); if (!m_wallet) { return {}; } m_wallet->callback(this); m_wallet->load(m_wallet_file, password); std::string prefix; bool ready; uint32_t threshold, total; if (m_wallet->watch_only()) prefix = tr("Opened watch-only wallet"); else if (m_wallet->multisig(&ready, &threshold, &total)) prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str(); else prefix = tr("Opened wallet"); message_writer(console_color_white, true) << prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); if (m_wallet->get_account().get_device()) { message_writer(console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name(); } // If the wallet file is deprecated, we should ask for mnemonic language again and store // everything in the new format. // NOTE: this is_deprecated() refers to the wallet file format before becoming JSON. It does not refer to the "old english" seed words form of "deprecated" used elsewhere. if (m_wallet->is_deprecated()) { bool is_deterministic; { SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return {};); is_deterministic = m_wallet->is_deterministic(); } if (is_deterministic) { message_writer(console_color_green, false) << "\n" << tr("You had been using " "a deprecated version of the wallet. Please proceed to upgrade your wallet.\n"); std::string mnemonic_language = get_mnemonic_language(); if (mnemonic_language.empty()) return {}; m_wallet->set_seed_language(mnemonic_language); m_wallet->rewrite(m_wallet_file, password); // Display the seed epee::wipeable_string seed; m_wallet->get_seed(seed); print_seed(seed); } else { message_writer(console_color_green, false) << "\n" << tr("You had been using " "a deprecated version of the wallet. Your wallet file format is being upgraded now.\n"); m_wallet->rewrite(m_wallet_file, password); } } } catch (const std::exception& e) { fail_msg_writer() << tr("failed to load wallet: ") << e.what(); if (m_wallet) { // only suggest removing cache if the password was actually correct bool password_is_correct = false; try { password_is_correct = m_wallet->verify_password(password); } catch (...) { } // guard against I/O errors if (password_is_correct) fail_msg_writer() << boost::format(tr("You may want to remove the file \"%s\" and try again")) % m_wallet_file; } return {}; } success_msg_writer() << "**********************************************************************\n" << tr("Use the \"help\" command to see the list of available commands.\n") << tr("Use \"help <command>\" to see a command's documentation.\n") << "**********************************************************************"; return password; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::close_wallet() { if (m_idle_run.load(std::memory_order_relaxed)) { m_idle_run.store(false, std::memory_order_relaxed); m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); m_wallet->stop(); { boost::unique_lock<boost::mutex> lock(m_idle_mutex); m_idle_cond.notify_one(); } m_idle_thread.join(); } bool r = m_wallet->deinit(); if (!r) { fail_msg_writer() << tr("failed to deinitialize wallet"); return false; } try { m_wallet->store(); } catch (const std::exception& e) { fail_msg_writer() << e.what(); return false; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::save(const std::vector<std::string> &args) { try { LOCK_IDLE_SCOPE(); m_wallet->store(); success_msg_writer() << tr("Wallet data saved"); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->multisig()) { fail_msg_writer() << tr("wallet is multisig and cannot save a watch-only version"); return true; } const auto pwd_container = password_prompter(tr("Password for new watch-only wallet"), true); if (!pwd_container) { fail_msg_writer() << tr("failed to read wallet password"); return true; } try { std::string new_keys_filename; m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password(), new_keys_filename); success_msg_writer() << tr("Watch only wallet saved as: ") << new_keys_filename; } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to save watch only wallet: ") << e.what(); return true; } return true; } //---------------------------------------------------------------------------------------------------- void simple_wallet::start_background_mining() { COMMAND_RPC_MINING_STATUS::request reqq; COMMAND_RPC_MINING_STATUS::response resq; bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq); std::string err = interpret_rpc_response(r, resq.status); if (!r) return; if (!err.empty()) { fail_msg_writer() << tr("Failed to query mining status: ") << err; return; } if (!resq.is_background_mining_enabled) { COMMAND_RPC_START_MINING::request req; COMMAND_RPC_START_MINING::response res; req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype()); req.threads_count = 1; req.do_background_mining = true; req.ignore_battery = false; bool r = m_wallet->invoke_http_json("/start_mining", req, res); std::string err = interpret_rpc_response(r, res.status); if (!err.empty()) { fail_msg_writer() << tr("Failed to setup background mining: ") << err; return; } } success_msg_writer() << tr("Background mining enabled. Thank you for supporting the Coinevo network."); } //---------------------------------------------------------------------------------------------------- void simple_wallet::stop_background_mining() { COMMAND_RPC_MINING_STATUS::request reqq; COMMAND_RPC_MINING_STATUS::response resq; bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq); if (!r) return; std::string err = interpret_rpc_response(r, resq.status); if (!err.empty()) { fail_msg_writer() << tr("Failed to query mining status: ") << err; return; } if (resq.is_background_mining_enabled) { COMMAND_RPC_STOP_MINING::request req; COMMAND_RPC_STOP_MINING::response res; bool r = m_wallet->invoke_http_json("/stop_mining", req, res); std::string err = interpret_rpc_response(r, res.status); if (!err.empty()) { fail_msg_writer() << tr("Failed to setup background mining: ") << err; return; } } message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change."); } //---------------------------------------------------------------------------------------------------- void simple_wallet::check_background_mining(const epee::wipeable_string &password) { tools::wallet2::BackgroundMiningSetupType setup = m_wallet->setup_background_mining(); if (setup == tools::wallet2::BackgroundMiningNo) { message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change."); return; } if (!m_wallet->is_trusted_daemon()) { message_writer() << tr("Using an untrusted daemon, skipping background mining check"); return; } COMMAND_RPC_MINING_STATUS::request req; COMMAND_RPC_MINING_STATUS::response res; bool r = m_wallet->invoke_http_json("/mining_status", req, res); std::string err = interpret_rpc_response(r, res.status); bool is_background_mining_enabled = false; if (err.empty()) is_background_mining_enabled = res.is_background_mining_enabled; if (is_background_mining_enabled) { // already active, nice m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes); m_wallet->rewrite(m_wallet_file, password); start_background_mining(); return; } if (res.active) return; if (setup == tools::wallet2::BackgroundMiningMaybe) { message_writer() << tr("The daemon is not set up to background mine."); message_writer() << tr("With background mining enabled, the daemon will mine when idle and not on battery."); message_writer() << tr("Enabling this supports the network you are using, and makes you eligible for receiving new coinevo"); std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): ")); if (std::cin.eof() || !command_line::is_yes(accepted)) { m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningNo); m_wallet->rewrite(m_wallet_file, password); message_writer(console_color_red, false) << tr("Background mining not enabled. Set setup-background-mining to 1 to change."); return; } m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes); m_wallet->rewrite(m_wallet_file, password); start_background_mining(); } } //---------------------------------------------------------------------------------------------------- bool simple_wallet::start_mining(const std::vector<std::string>& args) { if (!m_wallet->is_trusted_daemon()) { fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon"); return true; } if (!try_connect_to_daemon()) return true; if (!m_wallet) { fail_msg_writer() << tr("wallet is null"); return true; } COMMAND_RPC_START_MINING::request req = AUTO_VAL_INIT(req); req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype()); bool ok = true; size_t arg_size = args.size(); if(arg_size >= 3) { if (!parse_bool_and_use(args[2], [&](bool r) { req.ignore_battery = r; })) return true; } if(arg_size >= 2) { if (!parse_bool_and_use(args[1], [&](bool r) { req.do_background_mining = r; })) return true; } if(arg_size >= 1) { uint16_t num = 1; ok = string_tools::get_xtype_from_string(num, args[0]); ok = ok && 1 <= num; req.threads_count = num; } else { req.threads_count = 1; } if (!ok) { PRINT_USAGE(USAGE_START_MINING); return true; } COMMAND_RPC_START_MINING::response res; bool r = m_wallet->invoke_http_json("/start_mining", req, res); std::string err = interpret_rpc_response(r, res.status); if (err.empty()) success_msg_writer() << tr("Mining started in daemon"); else fail_msg_writer() << tr("mining has NOT been started: ") << err; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::stop_mining(const std::vector<std::string>& args) { if (!try_connect_to_daemon()) return true; if (!m_wallet) { fail_msg_writer() << tr("wallet is null"); return true; } COMMAND_RPC_STOP_MINING::request req; COMMAND_RPC_STOP_MINING::response res; bool r = m_wallet->invoke_http_json("/stop_mining", req, res); std::string err = interpret_rpc_response(r, res.status); if (err.empty()) success_msg_writer() << tr("Mining stopped in daemon"); else fail_msg_writer() << tr("mining has NOT been stopped: ") << err; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph) { try { auto i = m_claimed_cph.find(daemon_url); if (i == m_claimed_cph.end()) return false; claimed_cph = m_claimed_cph[daemon_url]; bool payment_required; uint64_t credits, diff, credits_per_hash_found, height, seed_height; uint32_t cookie; cryptonote::blobdata hashing_blob; crypto::hash seed_hash, next_seed_hash; if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie) && payment_required) { actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff); return true; } else { fail_msg_writer() << tr("Error checking daemon RPC access prices"); } } catch (const std::exception &e) { // can't check fail_msg_writer() << tr("Error checking daemon RPC access prices: ") << e.what(); return false; } // no record found for this daemon return false; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_daemon(const std::vector<std::string>& args) { std::string daemon_url; if (args.size() < 1) { PRINT_USAGE(USAGE_SET_DAEMON); return true; } boost::regex rgx("^(.*://)?([A-Za-z0-9\\-\\.]+)(:[0-9]+)?"); boost::cmatch match; // If user input matches URL regex if (boost::regex_match(args[0].c_str(), match, rgx)) { if (match.length() < 4) { fail_msg_writer() << tr("Unexpected array length - Exited simple_wallet::set_daemon()"); return true; } // If no port has been provided, use the default from config if (!match[3].length()) { uint16_t daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT; daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port); } else { daemon_url = args[0]; } LOCK_IDLE_SCOPE(); m_wallet->init(daemon_url); if (args.size() == 2) { if (args[1] == "trusted") m_wallet->set_trusted_daemon(true); else if (args[1] == "untrusted") m_wallet->set_trusted_daemon(false); else { fail_msg_writer() << tr("Expected trusted or untrusted, got ") << args[1] << ": assuming untrusted"; m_wallet->set_trusted_daemon(false); } } else { m_wallet->set_trusted_daemon(false); try { if (tools::is_local_address(m_wallet->get_daemon_address())) { MINFO(tr("Daemon is local, assuming trusted")); m_wallet->set_trusted_daemon(true); } } catch (const std::exception &e) { } } if (!try_connect_to_daemon()) { fail_msg_writer() << tr("Failed to connect to daemon"); return true; } success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted")); // check whether the daemon's prices match the claim, and disconnect if not, to disincentivize daemons lying uint32_t actual_cph, claimed_cph; if (check_daemon_rpc_prices(daemon_url, actual_cph, claimed_cph)) { if (actual_cph < claimed_cph) { fail_msg_writer() << tr("Daemon RPC credits/hash is less than was claimed. Either this daemon is cheating, or it changed its setup recently."); fail_msg_writer() << tr("Claimed: ") << claimed_cph / (float)RPC_CREDITS_PER_HASH_SCALE; fail_msg_writer() << tr("Actual: ") << actual_cph / (float)RPC_CREDITS_PER_HASH_SCALE; } } m_daemon_rpc_payment_message_displayed = false; } else { fail_msg_writer() << tr("This does not seem to be a valid daemon URL."); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::save_bc(const std::vector<std::string>& args) { if (!try_connect_to_daemon()) return true; if (!m_wallet) { fail_msg_writer() << tr("wallet is null"); return true; } COMMAND_RPC_SAVE_BC::request req; COMMAND_RPC_SAVE_BC::response res; bool r = m_wallet->invoke_http_json("/save_bc", req, res); std::string err = interpret_rpc_response(r, res.status); if (err.empty()) success_msg_writer() << tr("Blockchain saved"); else fail_msg_writer() << tr("blockchain can't be saved: ") << err; return true; } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_new_block(uint64_t height, const cryptonote::block& block) { if (m_locked) return; if (!m_auto_refresh_refreshing) m_refresh_progress_reporter.update(height, false); } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index, uint64_t unlock_time) { if (m_locked) return; message_writer(console_color_green, false) << "\r" << tr("Height ") << height << ", " << tr("txid ") << txid << ", " << print_money(amount) << ", " << tr("idx ") << subaddr_index; const uint64_t warn_height = m_wallet->nettype() == TESTNET ? 1000000 : m_wallet->nettype() == STAGENET ? 50000 : 1650000; if (height >= warn_height) { std::vector<tx_extra_field> tx_extra_fields; parse_tx_extra(tx.extra, tx_extra_fields); // failure ok tx_extra_nonce extra_nonce; if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { crypto::hash payment_id = crypto::null_hash; crypto::hash8 payment_id8 = crypto::null_hash8; if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { if (payment_id8 != crypto::null_hash8) message_writer() << tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead"); } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) message_writer(console_color_red, false) << tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead."); } } if (unlock_time && !cryptonote::is_coinbase(tx)) message_writer() << tr("NOTE: This transaction is locked, see details with: show_transfer ") + epee::string_tools::pod_to_hex(txid); if (m_auto_refresh_refreshing) m_cmd_binder.print_prompt(); else m_refresh_progress_reporter.update(height, true); } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index) { if (m_locked) return; // Not implemented in CLI wallet } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx, uint64_t amount, const cryptonote::transaction& spend_tx, const cryptonote::subaddress_index& subaddr_index) { if (m_locked) return; message_writer(console_color_magenta, false) << "\r" << tr("Height ") << height << ", " << tr("txid ") << txid << ", " << tr("spent ") << print_money(amount) << ", " << tr("idx ") << subaddr_index; if (m_auto_refresh_refreshing) m_cmd_binder.print_prompt(); else m_refresh_progress_reporter.update(height, true); } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx) { if (m_locked) return; } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::on_get_password(const char *reason) { if (m_locked) return boost::none; // can't ask for password from a background thread if (!m_in_manual_refresh.load(std::memory_order_relaxed)) { message_writer(console_color_red, false) << boost::format(tr("Password needed (%s) - use the refresh command")) % reason; m_cmd_binder.print_prompt(); return boost::none; } PAUSE_READLINE(); std::string msg = tr("Enter password"); if (reason && *reason) msg += std::string(" (") + reason + ")"; auto pwd_container = tools::password_container::prompt(false, msg.c_str()); if (!pwd_container) { MERROR("Failed to read password"); return boost::none; } return pwd_container->password(); } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_device_button_request(uint64_t code) { message_writer(console_color_white, false) << tr("Device requires attention"); } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::on_device_pin_request() { PAUSE_READLINE(); std::string msg = tr("Enter device PIN"); auto pwd_container = tools::password_container::prompt(false, msg.c_str()); THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device PIN")); return pwd_container->password(); } //---------------------------------------------------------------------------------------------------- boost::optional<epee::wipeable_string> simple_wallet::on_device_passphrase_request(bool on_device) { if (on_device){ message_writer(console_color_white, true) << tr("Please enter the device passphrase on the device"); return boost::none; } PAUSE_READLINE(); std::string msg = tr("Enter device passphrase"); auto pwd_container = tools::password_container::prompt(false, msg.c_str()); THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device passphrase")); return pwd_container->password(); } //---------------------------------------------------------------------------------------------------- void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_blocks, bool is_init, bool received_money) { // Key image sync after the first refresh if (!m_wallet->get_account().get_device().has_tx_cold_sign() || m_wallet->get_account().get_device().has_ki_live_refresh()) { return; } if (!received_money || m_wallet->get_device_last_key_image_sync() != 0) { return; } // Finished first refresh for HW device and money received -> KI sync message_writer() << "\n" << tr("The first refresh has finished for the HW-based wallet with received money. hw_key_images_sync is needed. "); std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): ")); if (std::cin.eof() || !command_line::is_yes(accepted)) { message_writer(console_color_red, false) << tr("hw_key_images_sync skipped. Run command manually before a transfer."); return; } key_images_sync_intern(); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bool is_init) { if (!try_connect_to_daemon(is_init)) return true; LOCK_IDLE_SCOPE(); crypto::hash transfer_hash_pre{}; uint64_t height_pre = 0, height_post; if (reset != ResetNone) { if (reset == ResetSoftKeepKI) height_pre = m_wallet->hash_m_transfers(-1, transfer_hash_pre); m_wallet->rescan_blockchain(reset == ResetHard, false, reset == ResetSoftKeepKI); } PAUSE_READLINE(); message_writer() << tr("Starting refresh..."); uint64_t fetched_blocks = 0; bool received_money = false; bool ok = false; std::ostringstream ss; try { m_in_manual_refresh.store(true, std::memory_order_relaxed); epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);}); m_wallet->refresh(m_wallet->is_trusted_daemon(), start_height, fetched_blocks, received_money); if (reset == ResetSoftKeepKI) { m_wallet->finish_rescan_bc_keep_key_images(height_pre, transfer_hash_pre); height_post = m_wallet->get_num_transfer_details(); if (height_pre != height_post) { message_writer() << tr("New transfer received since rescan was started. Key images are incomplete."); } } ok = true; // Clear line "Height xxx of xxx" std::cout << "\r \r"; success_msg_writer(true) << tr("Refresh done, blocks received: ") << fetched_blocks; if (is_init) print_accounts(); show_balance_unlocked(); on_refresh_finished(start_height, fetched_blocks, is_init, received_money); } catch (const tools::error::daemon_busy&) { ss << tr("daemon is busy. Please try again later."); } catch (const tools::error::no_connection_to_daemon&) { ss << tr("no connection to daemon. Please make sure daemon is running."); } catch (const tools::error::payment_required&) { ss << tr("payment required."); m_need_payment = true; } catch (const tools::error::wallet_rpc_error& e) { LOG_ERROR("RPC error: " << e.to_string()); ss << tr("RPC error: ") << e.what(); } catch (const tools::error::refresh_error& e) { LOG_ERROR("refresh error: " << e.to_string()); ss << tr("refresh error: ") << e.what(); } catch (const tools::error::wallet_internal_error& e) { LOG_ERROR("internal error: " << e.to_string()); ss << tr("internal error: ") << e.what(); } catch (const std::exception& e) { LOG_ERROR("unexpected error: " << e.what()); ss << tr("unexpected error: ") << e.what(); } catch (...) { LOG_ERROR("unknown error"); ss << tr("unknown error"); } if (!ok) { fail_msg_writer() << tr("refresh failed: ") << ss.str() << ". " << tr("Blocks received: ") << fetched_blocks; } // prevent it from triggering the idle screen due to waiting for a foreground refresh m_last_activity_time = time(NULL); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::refresh(const std::vector<std::string>& args) { uint64_t start_height = 0; if(!args.empty()){ try { start_height = boost::lexical_cast<uint64_t>( args[0] ); } catch(const boost::bad_lexical_cast &) { start_height = 0; } } return refresh_main(start_height, ResetNone); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_balance_unlocked(bool detailed) { std::string extra; if (m_wallet->has_multisig_partial_key_images()) extra = tr(" (Some owned outputs have partial key images - import_multisig_info needed)"); else if (m_wallet->has_unknown_key_images()) extra += tr(" (Some owned outputs have missing key images - import_key_images needed)"); success_msg_writer() << tr("Currently selected account: [") << m_current_subaddress_account << tr("] ") << m_wallet->get_subaddress_label({m_current_subaddress_account, 0}); const std::string tag = m_wallet->get_account_tags().second[m_current_subaddress_account]; success_msg_writer() << tr("Tag: ") << (tag.empty() ? std::string{tr("(No tag assigned)")} : tag); uint64_t blocks_to_unlock; uint64_t unlocked_balance = m_wallet->unlocked_balance(m_current_subaddress_account, false, &blocks_to_unlock); std::string unlock_time_message; if (blocks_to_unlock > 0) unlock_time_message = (boost::format(" (%lu block(s) to unlock)") % blocks_to_unlock).str(); success_msg_writer() << tr("Balance: ") << print_money(m_wallet->balance(m_current_subaddress_account, false)) << ", " << tr("unlocked balance: ") << print_money(unlocked_balance) << unlock_time_message << extra; std::map<uint32_t, uint64_t> balance_per_subaddress = m_wallet->balance_per_subaddress(m_current_subaddress_account, false); std::map<uint32_t, std::pair<uint64_t, uint64_t>> unlocked_balance_per_subaddress = m_wallet->unlocked_balance_per_subaddress(m_current_subaddress_account, false); if (!detailed || balance_per_subaddress.empty()) return true; success_msg_writer() << tr("Balance per address:"); success_msg_writer() << boost::format("%15s %21s %21s %7s %21s") % tr("Address") % tr("Balance") % tr("Unlocked balance") % tr("Outputs") % tr("Label"); std::vector<tools::wallet2::transfer_details> transfers; m_wallet->get_transfers(transfers); for (const auto& i : balance_per_subaddress) { cryptonote::subaddress_index subaddr_index = {m_current_subaddress_account, i.first}; std::string address_str = m_wallet->get_subaddress_as_str(subaddr_index).substr(0, 6); uint64_t num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&subaddr_index](const tools::wallet2::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == subaddr_index; }); success_msg_writer() << boost::format(tr("%8u %6s %21s %21s %7u %21s")) % i.first % address_str % print_money(i.second) % print_money(unlocked_balance_per_subaddress[i.first].first) % num_unspent_outputs % m_wallet->get_subaddress_label(subaddr_index); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_balance(const std::vector<std::string>& args/* = std::vector<std::string>()*/) { if (args.size() > 1 || (args.size() == 1 && args[0] != "detail")) { PRINT_USAGE(USAGE_SHOW_BALANCE); return true; } LOCK_IDLE_SCOPE(); show_balance_unlocked(args.size() == 1); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_incoming_transfers(const std::vector<std::string>& args) { if (args.size() > 3) { PRINT_USAGE(USAGE_INCOMING_TRANSFERS); return true; } auto local_args = args; LOCK_IDLE_SCOPE(); bool filter = false; bool available = false; bool verbose = false; bool uses = false; if (local_args.size() > 0) { if (local_args[0] == "available") { filter = true; available = true; local_args.erase(local_args.begin()); } else if (local_args[0] == "unavailable") { filter = true; available = false; local_args.erase(local_args.begin()); } } while (local_args.size() > 0) { if (local_args[0] == "verbose") verbose = true; else if (local_args[0] == "uses") uses = true; else { fail_msg_writer() << tr("Invalid keyword: ") << local_args.front(); break; } local_args.erase(local_args.begin()); } const uint64_t blockchain_height = m_wallet->get_blockchain_current_height(); PAUSE_READLINE(); std::set<uint32_t> subaddr_indices; if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=") { if (!parse_subaddress_indices(local_args[0], subaddr_indices)) return true; local_args.erase(local_args.begin()); } if (local_args.size() > 0) { PRINT_USAGE(USAGE_INCOMING_TRANSFERS); return true; } tools::wallet2::transfer_container transfers; m_wallet->get_transfers(transfers); size_t transfers_found = 0; for (const auto& td : transfers) { if (!filter || available != td.m_spent) { if (m_current_subaddress_account != td.m_subaddr_index.major || (!subaddr_indices.empty() && subaddr_indices.count(td.m_subaddr_index.minor) == 0)) continue; if (!transfers_found) { std::string verbose_string; if (verbose) verbose_string = (boost::format("%68s%68s") % tr("pubkey") % tr("key image")).str(); message_writer() << boost::format("%21s%8s%12s%8s%16s%68s%16s%s") % tr("amount") % tr("spent") % tr("unlocked") % tr("ringct") % tr("global index") % tr("tx id") % tr("addr index") % verbose_string; } std::string extra_string; if (verbose) extra_string += (boost::format("%68s%68s") % td.get_public_key() % (td.m_key_image_known ? epee::string_tools::pod_to_hex(td.m_key_image) : td.m_key_image_partial ? (epee::string_tools::pod_to_hex(td.m_key_image) + "/p") : std::string(64, '?'))).str(); if (uses) { std::vector<uint64_t> heights; for (const auto &e: td.m_uses) heights.push_back(e.first); const std::pair<std::string, std::string> line = show_outputs_line(heights, blockchain_height, td.m_spent_height); extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second; } message_writer(td.m_spent ? console_color_magenta : console_color_green, false) << boost::format("%21s%8s%12s%8s%16u%68s%16u%s") % print_money(td.amount()) % (td.m_spent ? tr("T") : tr("F")) % (m_wallet->frozen(td) ? tr("[frozen]") : m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) % (td.is_rct() ? tr("RingCT") : tr("-")) % td.m_global_output_index % td.m_txid % td.m_subaddr_index.minor % extra_string; ++transfers_found; } } if (!transfers_found) { if (!filter) { success_msg_writer() << tr("No incoming transfers"); } else if (available) { success_msg_writer() << tr("No incoming available transfers"); } else { success_msg_writer() << tr("No incoming unavailable transfers"); } } else { success_msg_writer() << boost::format("Found %u/%u transfers") % transfers_found % transfers.size(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_payments(const std::vector<std::string> &args) { if(args.empty()) { PRINT_USAGE(USAGE_PAYMENTS); return true; } LOCK_IDLE_SCOPE(); PAUSE_READLINE(); message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") % tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index"); bool payments_found = false; for(std::string arg : args) { crypto::hash payment_id; if(tools::wallet2::parse_payment_id(arg, payment_id)) { std::list<tools::wallet2::payment_details> payments; m_wallet->get_payments(payment_id, payments); if(payments.empty()) { success_msg_writer() << tr("No payments with id ") << payment_id; continue; } for (const tools::wallet2::payment_details& pd : payments) { if(!payments_found) { payments_found = true; } success_msg_writer(true) << boost::format("%68s%68s%12s%21s%16s%16s") % payment_id % pd.m_tx_hash % pd.m_block_height % print_money(pd.m_amount) % pd.m_unlock_time % pd.m_subaddr_index.minor; } } else { fail_msg_writer() << tr("payment ID has invalid format, expected 16 or 64 character hex string: ") << arg; } } return true; } //---------------------------------------------------------------------------------------------------- uint64_t simple_wallet::get_daemon_blockchain_height(std::string& err) { if (!m_wallet) { throw std::runtime_error("simple_wallet null wallet"); } return m_wallet->get_daemon_blockchain_height(err); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_blockchain_height(const std::vector<std::string>& args) { if (!try_connect_to_daemon()) return true; std::string err; uint64_t bc_height = get_daemon_blockchain_height(err); if (err.empty()) success_msg_writer() << bc_height; else fail_msg_writer() << tr("failed to get blockchain height: ") << err; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::rescan_spent(const std::vector<std::string> &args) { if (!m_wallet->is_trusted_daemon()) { fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon"); return true; } if (!try_connect_to_daemon()) return true; try { LOCK_IDLE_SCOPE(); m_wallet->rescan_spent(); } catch (const tools::error::daemon_busy&) { fail_msg_writer() << tr("daemon is busy. Please try again later."); } catch (const tools::error::no_connection_to_daemon&) { fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running."); } catch (const tools::error::payment_required&) { fail_msg_writer() << tr("payment required."); m_need_payment = true; } catch (const tools::error::is_key_image_spent_error&) { fail_msg_writer() << tr("failed to get spent status"); } catch (const tools::error::wallet_rpc_error& e) { LOG_ERROR("RPC error: " << e.to_string()); fail_msg_writer() << tr("RPC error: ") << e.what(); } catch (const std::exception& e) { LOG_ERROR("unexpected error: " << e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } //---------------------------------------------------------------------------------------------------- std::pair<std::string, std::string> simple_wallet::show_outputs_line(const std::vector<uint64_t> &heights, uint64_t blockchain_height, uint64_t highlight_height) const { std::stringstream ostr; for (uint64_t h: heights) blockchain_height = std::max(blockchain_height, h); for (size_t j = 0; j < heights.size(); ++j) ostr << (heights[j] == highlight_height ? " *" : " ") << heights[j]; // visualize the distribution, using the code by moneroexamples onion-monero-viewer const uint64_t resolution = 79; std::string ring_str(resolution, '_'); for (size_t j = 0; j < heights.size(); ++j) { uint64_t pos = (heights[j] * resolution) / blockchain_height; ring_str[pos] = 'o'; } if (highlight_height < blockchain_height) { uint64_t pos = (highlight_height * resolution) / blockchain_height; ring_str[pos] = '*'; } return std::make_pair(ostr.str(), ring_str); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::print_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr) { uint32_t version; if (!try_connect_to_daemon(false, &version)) return false; // available for RPC version 1.4 or higher if (version < MAKE_CORE_RPC_VERSION(1, 4)) return true; std::string err; uint64_t blockchain_height = get_daemon_blockchain_height(err); if (!err.empty()) { fail_msg_writer() << tr("failed to get blockchain height: ") << err; return false; } // for each transaction for (size_t n = 0; n < ptx_vector.size(); ++n) { const cryptonote::transaction& tx = ptx_vector[n].tx; const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data; ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx); // for each input std::vector<uint64_t> spent_key_height(tx.vin.size()); std::vector<crypto::hash> spent_key_txid (tx.vin.size()); for (size_t i = 0; i < tx.vin.size(); ++i) { if (tx.vin[i].type() != typeid(cryptonote::txin_to_key)) continue; const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]); const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(construction_data.selected_transfers[i]); const cryptonote::tx_source_entry *sptr = NULL; for (const auto &src: construction_data.sources) if (src.outputs[src.real_output].second.dest == td.get_public_key()) sptr = &src; if (!sptr) { fail_msg_writer() << tr("failed to find construction data for tx input"); return false; } const cryptonote::tx_source_entry& source = *sptr; ostr << boost::format(tr("\nInput %llu/%llu (%s): amount=%s")) % (i + 1) % tx.vin.size() % epee::string_tools::pod_to_hex(in_key.k_image) % print_money(source.amount); // convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets); // get block heights from which those ring member keys originated COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req); req.outputs.resize(absolute_offsets.size()); for (size_t j = 0; j < absolute_offsets.size(); ++j) { req.outputs[j].amount = in_key.amount; req.outputs[j].index = absolute_offsets[j]; } COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res); req.client = cryptonote::make_rpc_payment_signature(m_wallet->get_rpc_client_secret_key()); bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res); err = interpret_rpc_response(r, res.status); if (!err.empty()) { fail_msg_writer() << tr("failed to get output: ") << err; return false; } // make sure that returned block heights are less than blockchain height for (auto& res_out : res.outs) { if (res_out.height >= blockchain_height) { fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height"); return false; } } ostr << tr("\nOriginating block heights: "); spent_key_height[i] = res.outs[source.real_output].height; spent_key_txid [i] = res.outs[source.real_output].txid; std::vector<uint64_t> heights(absolute_offsets.size(), 0); uint64_t highlight_height = std::numeric_limits<uint64_t>::max(); for (size_t j = 0; j < absolute_offsets.size(); ++j) { heights[j] = res.outs[j].height; if (j == source.real_output) highlight_height = heights[j]; } std::pair<std::string, std::string> ring_str = show_outputs_line(heights, blockchain_height, highlight_height); ostr << ring_str.first << tr("\n|") << ring_str.second << tr("|\n"); } // warn if rings contain keys originating from the same tx or temporally very close block heights bool are_keys_from_same_tx = false; bool are_keys_from_close_height = false; for (size_t i = 0; i < tx.vin.size(); ++i) { for (size_t j = i + 1; j < tx.vin.size(); ++j) { if (spent_key_txid[i] == spent_key_txid[j]) are_keys_from_same_tx = true; if (std::abs((int64_t)(spent_key_height[i] - spent_key_height[j])) < (int64_t)5) are_keys_from_close_height = true; } } if (are_keys_from_same_tx || are_keys_from_close_height) { ostr << tr("\nWarning: Some input keys being spent are from ") << (are_keys_from_same_tx ? tr("the same transaction") : tr("blocks that are temporally very close")) << tr(", which can break the anonymity of ring signature. Make sure this is intentional!"); } ostr << ENDL; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::prompt_if_old(const std::vector<tools::wallet2::pending_tx> &ptx_vector) { // count the number of old outputs std::string err; uint64_t bc_height = get_daemon_blockchain_height(err); if (!err.empty()) return true; int max_n_old = 0; for (const auto &ptx: ptx_vector) { int n_old = 0; for (const auto i: ptx.selected_transfers) { const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i); uint64_t age = bc_height - td.m_block_height; if (age > OLD_AGE_WARN_THRESHOLD) ++n_old; } max_n_old = std::max(max_n_old, n_old); } if (max_n_old > 1) { std::stringstream prompt; prompt << tr("Transaction spends more than one very old output. Privacy would be better if they were sent separately."); prompt << ENDL << tr("Spend them now anyway?"); std::string accepted = input_line(prompt.str(), true); if (std::cin.eof()) return false; if (!command_line::is_yes(accepted)) { return false; } } return true; } void simple_wallet::check_for_inactivity_lock(bool user) { if (m_locked) { #ifdef HAVE_READLINE PAUSE_READLINE(); rdln::clear_screen(); #endif tools::clear_screen(); m_in_command = true; if (!user) { const std::string speech = tr("I locked your Coinevo wallet to protect you while you were away"); std::vector<std::pair<std::string, size_t>> lines = tools::split_string_by_width(speech, 45); size_t max_len = 0; for (const auto &i: lines) max_len = std::max(max_len, i.second); const size_t n_u = max_len + 2; tools::msg_writer() << " " << std::string(n_u, '_'); for (size_t i = 0; i < lines.size(); ++i) tools::msg_writer() << (i == 0 ? "/" : i == lines.size() - 1 ? "\\" : "|") << " " << lines[i].first << std::string(max_len - lines[i].second, ' ') << " " << (i == 0 ? "\\" : i == lines.size() - 1 ? "/" : "|"); tools::msg_writer() << " " << std::string(n_u, '-') << std::endl << " \\ (__)" << std::endl << " \\ (oo)\\_______" << std::endl << " (__)\\ )\\/\\" << std::endl << " ||----w |" << std::endl << " || ||" << std::endl << "" << std::endl; } while (1) { tools::msg_writer() << tr("Locked due to inactivity. The wallet password is required to unlock the console."); try { if (get_and_verify_password()) break; } catch (...) { /* do nothing, just let the loop loop */ } } m_last_activity_time = time(NULL); m_in_command = false; m_locked = false; } } //---------------------------------------------------------------------------------------------------- bool simple_wallet::on_command(bool (simple_wallet::*cmd)(const std::vector<std::string>&), const std::vector<std::string> &args) { const time_t now = time(NULL); time_t dt = now - m_last_activity_time; m_last_activity_time = time(NULL); m_in_command = true; epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ m_last_activity_time = time(NULL); m_in_command = false; }); check_for_inactivity_lock(false); return (this->*cmd)(args); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::transfer_main(int transfer_type, const std::vector<std::string> &args_, bool called_by_mms) { // "transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <amount> [<payment_id>]" if (!try_connect_to_daemon()) return false; std::vector<std::string> local_args = args_; std::set<uint32_t> subaddr_indices; if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=") { if (!parse_subaddress_indices(local_args[0], subaddr_indices)) return false; local_args.erase(local_args.begin()); } uint32_t priority = 0; if (local_args.size() > 0 && parse_priority(local_args[0], priority)) local_args.erase(local_args.begin()); priority = m_wallet->adjust_priority(priority); size_t fake_outs_count = DEFAULT_MIX; if(local_args.size() > 0) { size_t ring_size; if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0])) { } else if (ring_size == 0) { fail_msg_writer() << tr("Ring size must not be 0"); return false; } else { fake_outs_count = ring_size - 1; local_args.erase(local_args.begin()); } } uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count); if (adjusted_fake_outs_count > fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return false; } if (adjusted_fake_outs_count < fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return false; } const size_t min_args = (transfer_type == TransferLocked) ? 2 : 1; if(local_args.size() < min_args) { fail_msg_writer() << tr("wrong number of arguments"); return false; } std::vector<uint8_t> extra; bool payment_id_seen = false; if (!local_args.empty()) { std::string payment_id_str = local_args.back(); crypto::hash payment_id; bool r = true; if (tools::wallet2::parse_long_payment_id(payment_id_str, payment_id)) { LONG_PAYMENT_ID_SUPPORT_CHECK(); std::string extra_nonce; set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); r = add_extra_nonce_to_tx_extra(extra, extra_nonce); local_args.pop_back(); payment_id_seen = true; message_writer() << tr("Warning: Unencrypted payment IDs will harm your privacy: ask the recipient to use subaddresses instead"); } if(!r) { fail_msg_writer() << tr("payment id failed to encode"); return false; } } uint64_t locked_blocks = 0; if (transfer_type == TransferLocked) { try { locked_blocks = boost::lexical_cast<uint64_t>(local_args.back()); } catch (const std::exception &e) { fail_msg_writer() << tr("bad locked_blocks parameter:") << " " << local_args.back(); return false; } if (locked_blocks > 1000000) { fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)"); return false; } local_args.pop_back(); } vector<cryptonote::address_parse_info> dsts_info; vector<cryptonote::tx_destination_entry> dsts; size_t num_subaddresses = 0; for (size_t i = 0; i < local_args.size(); ) { dsts_info.emplace_back(); cryptonote::address_parse_info & info = dsts_info.back(); cryptonote::tx_destination_entry de; bool r = true; // check for a URI std::string address_uri, payment_id_uri, tx_description, recipient_name, error; std::vector<std::string> unknown_parameters; uint64_t amount = 0; bool has_uri = m_wallet->parse_uri(local_args[i], address_uri, payment_id_uri, amount, tx_description, recipient_name, unknown_parameters, error); if (has_uri) { r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_uri, oa_prompter); if (payment_id_uri.size() == 16) { if (!tools::wallet2::parse_short_payment_id(payment_id_uri, info.payment_id)) { fail_msg_writer() << tr("failed to parse short payment ID from URI"); return false; } info.has_payment_id = true; } de.amount = amount; de.original = local_args[i]; ++i; } else if (i + 1 < local_args.size()) { r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[i], oa_prompter); bool ok = cryptonote::parse_amount(de.amount, local_args[i + 1]); if(!ok || 0 == de.amount) { fail_msg_writer() << tr("amount is wrong: ") << local_args[i] << ' ' << local_args[i + 1] << ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max()); return false; } de.original = local_args[i]; i += 2; } else { if (boost::starts_with(local_args[i], "coinevo:")) fail_msg_writer() << tr("Invalid last argument: ") << local_args.back() << ": " << error; else fail_msg_writer() << tr("Invalid last argument: ") << local_args.back(); return false; } if (!r) { fail_msg_writer() << tr("failed to parse address"); return false; } de.addr = info.address; de.is_subaddress = info.is_subaddress; de.is_integrated = info.has_payment_id; num_subaddresses += info.is_subaddress; if (info.has_payment_id || !payment_id_uri.empty()) { if (payment_id_seen) { fail_msg_writer() << tr("a single transaction cannot use more than one payment id"); return false; } crypto::hash payment_id; std::string extra_nonce; if (info.has_payment_id) { set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id); } else if (tools::wallet2::parse_payment_id(payment_id_uri, payment_id)) { LONG_PAYMENT_ID_SUPPORT_CHECK(); set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); message_writer() << tr("Warning: Unencrypted payment IDs will harm your privacy: ask the recipient to use subaddresses instead"); } else { fail_msg_writer() << tr("failed to parse payment id, though it was detected"); return false; } bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce); if(!r) { fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly"); return false; } payment_id_seen = true; } dsts.push_back(de); } SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;); try { // figure out what tx will be necessary std::vector<tools::wallet2::pending_tx> ptx_vector; uint64_t bc_height, unlock_block = 0; std::string err; switch (transfer_type) { case TransferLocked: bc_height = get_daemon_blockchain_height(err); if (!err.empty()) { fail_msg_writer() << tr("failed to get blockchain height: ") << err; return false; } unlock_block = bc_height + locked_blocks; ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices); break; default: LOG_ERROR("Unknown transfer method, using default"); /* FALLTHRU */ case Transfer: ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, 0 /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices); break; } if (ptx_vector.empty()) { fail_msg_writer() << tr("No outputs found, or daemon is not ready"); return false; } // if we need to check for backlog, check the worst case tx if (m_wallet->confirm_backlog()) { std::stringstream prompt; double worst_fee_per_byte = std::numeric_limits<double>::max(); for (size_t n = 0; n < ptx_vector.size(); ++n) { const uint64_t blob_size = cryptonote::tx_to_blob(ptx_vector[n].tx).size(); const double fee_per_byte = ptx_vector[n].fee / (double)blob_size; if (fee_per_byte < worst_fee_per_byte) { worst_fee_per_byte = fee_per_byte; } } try { std::vector<std::pair<uint64_t, uint64_t>> nblocks = m_wallet->estimate_backlog({std::make_pair(worst_fee_per_byte, worst_fee_per_byte)}); if (nblocks.size() != 1) { prompt << "Internal error checking for backlog. " << tr("Is this okay anyway?"); } else { if (nblocks[0].first > m_wallet->get_confirm_backlog_threshold()) prompt << (boost::format(tr("There is currently a %u block backlog at that fee level. Is this okay?")) % nblocks[0].first).str(); } } catch (const std::exception &e) { prompt << tr("Failed to check for backlog: ") << e.what() << ENDL << tr("Is this okay anyway?"); } std::string prompt_str = prompt.str(); if (!prompt_str.empty()) { std::string accepted = input_line(prompt_str, true); if (std::cin.eof()) return false; if (!command_line::is_yes(accepted)) { fail_msg_writer() << tr("transaction cancelled."); return false; } } } if (!prompt_if_old(ptx_vector)) { fail_msg_writer() << tr("transaction cancelled."); return false; } // if more than one tx necessary, prompt user to confirm if (m_wallet->always_confirm_transfers() || ptx_vector.size() > 1) { uint64_t total_sent = 0; uint64_t total_fee = 0; uint64_t dust_not_in_fee = 0; uint64_t dust_in_fee = 0; uint64_t change = 0; for (size_t n = 0; n < ptx_vector.size(); ++n) { total_fee += ptx_vector[n].fee; for (auto i: ptx_vector[n].selected_transfers) total_sent += m_wallet->get_transfer_details(i).amount(); total_sent -= ptx_vector[n].change_dts.amount + ptx_vector[n].fee; change += ptx_vector[n].change_dts.amount; if (ptx_vector[n].dust_added_to_fee) dust_in_fee += ptx_vector[n].dust; else dust_not_in_fee += ptx_vector[n].dust; } std::stringstream prompt; for (size_t n = 0; n < ptx_vector.size(); ++n) { prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n"; subaddr_indices.clear(); for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices) subaddr_indices.insert(i); for (uint32_t i : subaddr_indices) prompt << boost::format(tr("Spending from address index %d\n")) % i; if (subaddr_indices.size() > 1) prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n"); } prompt << boost::format(tr("Sending %s. ")) % print_money(total_sent); if (ptx_vector.size() > 1) { prompt << boost::format(tr("Your transaction needs to be split into %llu transactions. " "This will result in a transaction fee being applied to each transaction, for a total fee of %s")) % ((unsigned long long)ptx_vector.size()) % print_money(total_fee); } else { prompt << boost::format(tr("The transaction fee is %s")) % print_money(total_fee); } if (dust_in_fee != 0) prompt << boost::format(tr(", of which %s is dust from change")) % print_money(dust_in_fee); if (dust_not_in_fee != 0) prompt << tr(".") << ENDL << boost::format(tr("A total of %s from dust change will be sent to dust address")) % print_money(dust_not_in_fee); if (transfer_type == TransferLocked) { float days = locked_blocks / 720.0f; prompt << boost::format(tr(".\nThis transaction (including %s change) will unlock on block %llu, in approximately %s days (assuming 2 minutes per block)")) % cryptonote::print_money(change) % ((unsigned long long)unlock_block) % days; } if (m_wallet->print_ring_members()) { if (!print_ring_members(ptx_vector, prompt)) return false; } bool default_ring_size = true; for (const auto &ptx: ptx_vector) { for (const auto &vin: ptx.tx.vin) { if (vin.type() == typeid(txin_to_key)) { const txin_to_key& in_to_key = boost::get<txin_to_key>(vin); if (in_to_key.key_offsets.size() != DEFAULT_MIX + 1) default_ring_size = false; } } } if (m_wallet->confirm_non_default_ring_size() && !default_ring_size) { prompt << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended."); } prompt << ENDL << tr("Is this okay?"); std::string accepted = input_line(prompt.str(), true); if (std::cin.eof()) return false; if (!command_line::is_yes(accepted)) { fail_msg_writer() << tr("transaction cancelled."); return false; } } // actually commit the transactions if (m_wallet->multisig() && called_by_mms) { std::string ciphertext = m_wallet->save_multisig_tx(ptx_vector); if (!ciphertext.empty()) { get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::partially_signed_tx, ciphertext); success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to MMS"); } } else if (m_wallet->multisig()) { bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); return false; } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_coinevo_tx"; } } else if (m_wallet->get_account().get_device().has_tx_cold_sign()) { try { tools::wallet2::signed_tx_set signed_tx; if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){ fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet"); return false; } commit_or_save(signed_tx.ptx, m_do_not_relay); } catch (const std::exception& e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); return false; } catch (...) { LOG_ERROR("Unknown error"); fail_msg_writer() << tr("unknown error"); return false; } } else if (m_wallet->watch_only()) { bool r = m_wallet->save_tx(ptx_vector, "unsigned_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); return false; } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_coinevo_tx"; } } else { commit_or_save(ptx_vector, m_do_not_relay); } } catch (const std::exception &e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); return false; } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); return false; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::transfer(const std::vector<std::string> &args_) { transfer_main(Transfer, args_, false); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::locked_transfer(const std::vector<std::string> &args_) { transfer_main(TransferLocked, args_, false); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::locked_sweep_all(const std::vector<std::string> &args_) { sweep_main(0, true, args_); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sweep_unmixable(const std::vector<std::string> &args_) { if (!try_connect_to_daemon()) return true; SCOPED_WALLET_UNLOCK(); try { // figure out what tx will be necessary auto ptx_vector = m_wallet->create_unmixable_sweep_transactions(); if (ptx_vector.empty()) { fail_msg_writer() << tr("No unmixable outputs found"); return true; } // give user total and fee, and prompt to confirm uint64_t total_fee = 0, total_unmixable = 0; for (size_t n = 0; n < ptx_vector.size(); ++n) { total_fee += ptx_vector[n].fee; for (auto i: ptx_vector[n].selected_transfers) total_unmixable += m_wallet->get_transfer_details(i).amount(); } std::string prompt_str = tr("Sweeping ") + print_money(total_unmixable); if (ptx_vector.size() > 1) { prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) % print_money(total_unmixable) % ((unsigned long long)ptx_vector.size()) % print_money(total_fee)).str(); } else { prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) % print_money(total_unmixable) % print_money(total_fee)).str(); } std::string accepted = input_line(prompt_str, true); if (std::cin.eof()) return true; if (!command_line::is_yes(accepted)) { fail_msg_writer() << tr("transaction cancelled."); return true; } // actually commit the transactions if (m_wallet->multisig()) { bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_coinevo_tx"; } } else if (m_wallet->watch_only()) { bool r = m_wallet->save_tx(ptx_vector, "unsigned_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_coinevo_tx"; } } else { commit_or_save(ptx_vector, m_do_not_relay); } } catch (const tools::error::not_enough_unlocked_money& e) { fail_msg_writer() << tr("Not enough money in unlocked balance"); std::string accepted = input_line((boost::format(tr("Discarding %s of unmixable outputs that cannot be spent, which can be undone by \"rescan_spent\". Is this okay?")) % print_money(e.available())).str(), true); if (std::cin.eof()) return true; if (command_line::is_yes(accepted)) { try { m_wallet->discard_unmixable_outputs(); } catch (...) {} } } catch (const std::exception &e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sweep_main(uint64_t below, bool locked, const std::vector<std::string> &args_) { auto print_usage = [below]() { if (below) { PRINT_USAGE(USAGE_SWEEP_BELOW); } else { PRINT_USAGE(USAGE_SWEEP_ALL); } }; if (args_.size() == 0) { fail_msg_writer() << tr("No address given"); print_usage(); return true; } if (!try_connect_to_daemon()) return true; std::vector<std::string> local_args = args_; std::set<uint32_t> subaddr_indices; if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=") { if (!parse_subaddress_indices(local_args[0], subaddr_indices)) { print_usage(); return true; } local_args.erase(local_args.begin()); } uint32_t priority = 0; if (local_args.size() > 0 && parse_priority(local_args[0], priority)) local_args.erase(local_args.begin()); priority = m_wallet->adjust_priority(priority); size_t fake_outs_count = DEFAULT_MIX; if(local_args.size() > 0) { size_t ring_size; if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0])) { } else if (ring_size == 0) { fail_msg_writer() << tr("Ring size must not be 0"); return true; } else { fake_outs_count = ring_size - 1; local_args.erase(local_args.begin()); } } uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count); if (adjusted_fake_outs_count > fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return true; } if (adjusted_fake_outs_count < fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return true; } uint64_t unlock_block = 0; if (locked) { uint64_t locked_blocks = 0; if (local_args.size() < 2) { fail_msg_writer() << tr("missing lockedblocks parameter"); return true; } try { locked_blocks = boost::lexical_cast<uint64_t>(local_args[1]); } catch (const std::exception &e) { fail_msg_writer() << tr("bad locked_blocks parameter"); return true; } if (locked_blocks > 1000000) { fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)"); return true; } std::string err; uint64_t bc_height = get_daemon_blockchain_height(err); if (!err.empty()) { fail_msg_writer() << tr("failed to get blockchain height: ") << err; return true; } unlock_block = bc_height + locked_blocks; local_args.erase(local_args.begin() + 1); } size_t outputs = 1; if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=") { if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8))) { fail_msg_writer() << tr("Failed to parse number of outputs"); return true; } else if (outputs < 1) { fail_msg_writer() << tr("Amount of outputs should be greater than 0"); return true; } else { local_args.erase(local_args.begin()); } } std::vector<uint8_t> extra; bool payment_id_seen = false; if (local_args.size() >= 2) { std::string payment_id_str = local_args.back(); crypto::hash payment_id; bool r = tools::wallet2::parse_long_payment_id(payment_id_str, payment_id); if(r) { LONG_PAYMENT_ID_SUPPORT_CHECK(); std::string extra_nonce; set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); r = add_extra_nonce_to_tx_extra(extra, extra_nonce); payment_id_seen = true; } if(!r && local_args.size() == 3) { fail_msg_writer() << tr("payment id has invalid format, expected 16 or 64 character hex string: ") << payment_id_str; print_usage(); return true; } if (payment_id_seen) local_args.pop_back(); } cryptonote::address_parse_info info; if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[0], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); print_usage(); return true; } if (info.has_payment_id) { if (payment_id_seen) { fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0]; return true; } std::string extra_nonce; set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id); bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce); if(!r) { fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly"); return true; } payment_id_seen = true; } SCOPED_WALLET_UNLOCK(); try { // figure out what tx will be necessary auto ptx_vector = m_wallet->create_transactions_all(below, info.address, info.is_subaddress, outputs, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices); if (ptx_vector.empty()) { fail_msg_writer() << tr("No outputs found, or daemon is not ready"); return true; } if (!prompt_if_old(ptx_vector)) { fail_msg_writer() << tr("transaction cancelled."); return false; } // give user total and fee, and prompt to confirm uint64_t total_fee = 0, total_sent = 0; for (size_t n = 0; n < ptx_vector.size(); ++n) { total_fee += ptx_vector[n].fee; for (auto i: ptx_vector[n].selected_transfers) total_sent += m_wallet->get_transfer_details(i).amount(); } std::ostringstream prompt; for (size_t n = 0; n < ptx_vector.size(); ++n) { prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n"; subaddr_indices.clear(); for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices) subaddr_indices.insert(i); for (uint32_t i : subaddr_indices) prompt << boost::format(tr("Spending from address index %d\n")) % i; if (subaddr_indices.size() > 1) prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n"); } if (m_wallet->print_ring_members() && !print_ring_members(ptx_vector, prompt)) return true; if (ptx_vector.size() > 1) { prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) % print_money(total_sent) % ((unsigned long long)ptx_vector.size()) % print_money(total_fee); } else { prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) % print_money(total_sent) % print_money(total_fee); } std::string accepted = input_line(prompt.str(), true); if (std::cin.eof()) return true; if (!command_line::is_yes(accepted)) { fail_msg_writer() << tr("transaction cancelled."); return true; } // actually commit the transactions if (m_wallet->multisig()) { bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_coinevo_tx"; } } else if (m_wallet->get_account().get_device().has_tx_cold_sign()) { try { tools::wallet2::signed_tx_set signed_tx; std::vector<cryptonote::address_parse_info> dsts_info; dsts_info.push_back(info); if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){ fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet"); return true; } commit_or_save(signed_tx.ptx, m_do_not_relay); } catch (const std::exception& e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("Unknown error"); fail_msg_writer() << tr("unknown error"); } } else if (m_wallet->watch_only()) { bool r = m_wallet->save_tx(ptx_vector, "unsigned_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_coinevo_tx"; } } else { commit_or_save(ptx_vector, m_do_not_relay); } } catch (const std::exception& e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sweep_single(const std::vector<std::string> &args_) { if (!try_connect_to_daemon()) return true; std::vector<std::string> local_args = args_; uint32_t priority = 0; if (local_args.size() > 0 && parse_priority(local_args[0], priority)) local_args.erase(local_args.begin()); priority = m_wallet->adjust_priority(priority); size_t fake_outs_count = DEFAULT_MIX; if(local_args.size() > 0) { size_t ring_size; if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0])) { } else if (ring_size == 0) { fail_msg_writer() << tr("Ring size must not be 0"); return true; } else { fake_outs_count = ring_size - 1; local_args.erase(local_args.begin()); } } uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count); if (adjusted_fake_outs_count > fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return true; } if (adjusted_fake_outs_count < fake_outs_count) { fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str(); return true; } size_t outputs = 1; if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=") { if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8))) { fail_msg_writer() << tr("Failed to parse number of outputs"); return true; } else if (outputs < 1) { fail_msg_writer() << tr("Amount of outputs should be greater than 0"); return true; } else { local_args.erase(local_args.begin()); } } std::vector<uint8_t> extra; bool payment_id_seen = false; if (local_args.size() == 3) { crypto::hash payment_id; crypto::hash8 payment_id8; std::string extra_nonce; if (tools::wallet2::parse_long_payment_id(local_args.back(), payment_id)) { LONG_PAYMENT_ID_SUPPORT_CHECK(); set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); } else { fail_msg_writer() << tr("failed to parse Payment ID"); return true; } if (!add_extra_nonce_to_tx_extra(extra, extra_nonce)) { fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly"); return true; } local_args.pop_back(); payment_id_seen = true; } if (local_args.size() != 2) { PRINT_USAGE(USAGE_SWEEP_SINGLE); return true; } crypto::key_image ki; if (!epee::string_tools::hex_to_pod(local_args[0], ki)) { fail_msg_writer() << tr("failed to parse key image"); return true; } cryptonote::address_parse_info info; if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[1], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } if (info.has_payment_id) { if (payment_id_seen) { fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0]; return true; } std::string extra_nonce; set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id); if (!add_extra_nonce_to_tx_extra(extra, extra_nonce)) { fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly"); return true; } payment_id_seen = true; } SCOPED_WALLET_UNLOCK(); try { // figure out what tx will be necessary auto ptx_vector = m_wallet->create_transactions_single(ki, info.address, info.is_subaddress, outputs, fake_outs_count, 0 /* unlock_time */, priority, extra); if (ptx_vector.empty()) { fail_msg_writer() << tr("No outputs found"); return true; } if (ptx_vector.size() > 1) { fail_msg_writer() << tr("Multiple transactions are created, which is not supposed to happen"); return true; } if (ptx_vector[0].selected_transfers.size() != 1) { fail_msg_writer() << tr("The transaction uses multiple or no inputs, which is not supposed to happen"); return true; } // give user total and fee, and prompt to confirm uint64_t total_fee = ptx_vector[0].fee; uint64_t total_sent = m_wallet->get_transfer_details(ptx_vector[0].selected_transfers.front()).amount(); std::ostringstream prompt; if (!print_ring_members(ptx_vector, prompt)) return true; prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) % print_money(total_sent) % print_money(total_fee); std::string accepted = input_line(prompt.str(), true); if (std::cin.eof()) return true; if (!command_line::is_yes(accepted)) { fail_msg_writer() << tr("transaction cancelled."); return true; } // actually commit the transactions if (m_wallet->multisig()) { bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_coinevo_tx"; } } else if (m_wallet->watch_only()) { bool r = m_wallet->save_tx(ptx_vector, "unsigned_coinevo_tx"); if (!r) { fail_msg_writer() << tr("Failed to write transaction(s) to file"); } else { success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_coinevo_tx"; } } else { m_wallet->commit_tx(ptx_vector[0]); success_msg_writer(true) << tr("Money successfully sent, transaction: ") << get_transaction_hash(ptx_vector[0].tx); } } catch (const std::exception& e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sweep_all(const std::vector<std::string> &args_) { sweep_main(0, false, args_); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sweep_below(const std::vector<std::string> &args_) { uint64_t below = 0; if (args_.size() < 1) { fail_msg_writer() << tr("missing threshold amount"); return true; } if (!cryptonote::parse_amount(below, args_[0])) { fail_msg_writer() << tr("invalid amount threshold"); return true; } sweep_main(below, false, std::vector<std::string>(++args_.begin(), args_.end())); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::donate(const std::vector<std::string> &args_) { std::vector<std::string> local_args = args_; if(local_args.empty() || local_args.size() > 5) { PRINT_USAGE(USAGE_DONATE); return true; } std::string amount_str; std::string payment_id_str; // get payment id and pop crypto::hash payment_id; crypto::hash8 payment_id8; if (tools::wallet2::parse_long_payment_id (local_args.back(), payment_id ) || tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8)) { payment_id_str = local_args.back(); local_args.pop_back(); } // get amount and pop uint64_t amount; bool ok = cryptonote::parse_amount(amount, local_args.back()); if (ok && amount != 0) { amount_str = local_args.back(); local_args.pop_back(); } else { fail_msg_writer() << tr("amount is wrong: ") << local_args.back() << ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max()); return true; } // push back address, amount, payment id std::string address_str; if (m_wallet->nettype() != cryptonote::MAINNET) { // if not mainnet, convert donation address string to the relevant network type address_parse_info info; if (!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, MONERO_DONATION_ADDR)) { fail_msg_writer() << tr("Failed to parse donation address: ") << MONERO_DONATION_ADDR; return true; } address_str = cryptonote::get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address); } else { address_str = MONERO_DONATION_ADDR; } local_args.push_back(address_str); local_args.push_back(amount_str); if (!payment_id_str.empty()) local_args.push_back(payment_id_str); if (m_wallet->nettype() == cryptonote::MAINNET) message_writer() << (boost::format(tr("Donating %s %s to The Coinevo Project (donate.coinevo.tech or %s).")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % MONERO_DONATION_ADDR).str(); else message_writer() << (boost::format(tr("Donating %s %s to %s.")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % address_str).str(); transfer(local_args); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message) { // gather info to ask the user uint64_t amount = 0, amount_to_dests = 0, change = 0; size_t min_ring_size = ~0; std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> dests; int first_known_non_zero_change_index = -1; std::string payment_id_string = ""; for (size_t n = 0; n < get_num_txes(); ++n) { const tools::wallet2::tx_construction_data &cd = get_tx(n); std::vector<tx_extra_field> tx_extra_fields; bool has_encrypted_payment_id = false; crypto::hash8 payment_id8 = crypto::null_hash8; if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields)) { tx_extra_nonce extra_nonce; if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { crypto::hash payment_id; if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { if (!payment_id_string.empty()) payment_id_string += ", "; // if none of the addresses are integrated addresses, it's a dummy one bool is_dummy = true; for (const auto &e: cd.dests) if (e.is_integrated) is_dummy = false; if (is_dummy) { payment_id_string += std::string("dummy encrypted payment ID"); } else { payment_id_string += std::string("encrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id8); has_encrypted_payment_id = true; } } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) { if (!payment_id_string.empty()) payment_id_string += ", "; payment_id_string += std::string("unencrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id); payment_id_string += " (OBSOLETE)"; } } } for (size_t s = 0; s < cd.sources.size(); ++s) { amount += cd.sources[s].amount; size_t ring_size = cd.sources[s].outputs.size(); if (ring_size < min_ring_size) min_ring_size = ring_size; } for (size_t d = 0; d < cd.splitted_dsts.size(); ++d) { const tx_destination_entry &entry = cd.splitted_dsts[d]; std::string address, standard_address = get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr); if (has_encrypted_payment_id && !entry.is_subaddress && standard_address != entry.original) { address = get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8); address += std::string(" (" + standard_address + " with encrypted payment id " + epee::string_tools::pod_to_hex(payment_id8) + ")"); } else address = standard_address; auto i = dests.find(entry.addr); if (i == dests.end()) dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount))); else i->second.second += entry.amount; amount_to_dests += entry.amount; } if (cd.change_dts.amount > 0) { auto it = dests.find(cd.change_dts.addr); if (it == dests.end()) { fail_msg_writer() << tr("Claimed change does not go to a paid address"); return false; } if (it->second.second < cd.change_dts.amount) { fail_msg_writer() << tr("Claimed change is larger than payment to the change address"); return false; } if (cd.change_dts.amount > 0) { if (first_known_non_zero_change_index == -1) first_known_non_zero_change_index = n; if (memcmp(&cd.change_dts.addr, &get_tx(first_known_non_zero_change_index).change_dts.addr, sizeof(cd.change_dts.addr))) { fail_msg_writer() << tr("Change goes to more than one address"); return false; } } change += cd.change_dts.amount; it->second.second -= cd.change_dts.amount; if (it->second.second == 0) dests.erase(cd.change_dts.addr); } } if (payment_id_string.empty()) payment_id_string = "no payment ID"; std::string dest_string; size_t n_dummy_outputs = 0; for (auto i = dests.begin(); i != dests.end(); ) { if (i->second.second > 0) { if (!dest_string.empty()) dest_string += ", "; dest_string += (boost::format(tr("sending %s to %s")) % print_money(i->second.second) % i->second.first).str(); } else ++n_dummy_outputs; ++i; } if (n_dummy_outputs > 0) { if (!dest_string.empty()) dest_string += ", "; dest_string += std::to_string(n_dummy_outputs) + tr(" dummy output(s)"); } if (dest_string.empty()) dest_string = tr("with no destinations"); std::string change_string; if (change > 0) { std::string address = get_account_address_as_str(m_wallet->nettype(), get_tx(0).subaddr_account > 0, get_tx(0).change_dts.addr); change_string += (boost::format(tr("%s change to %s")) % print_money(change) % address).str(); } else change_string += tr("no change"); uint64_t fee = amount - amount_to_dests; std::string prompt_str = (boost::format(tr("Loaded %lu transactions, for %s, fee %s, %s, %s, with min ring size %lu, %s. %sIs this okay?")) % (unsigned long)get_num_txes() % print_money(amount) % print_money(fee) % dest_string % change_string % (unsigned long)min_ring_size % payment_id_string % extra_message).str(); return command_line::is_yes(input_line(prompt_str, true)); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs) { std::string extra_message; if (!txs.transfers.second.empty()) extra_message = (boost::format("%u outputs to import. ") % (unsigned)txs.transfers.second.size()).str(); return accept_loaded_tx([&txs](){return txs.txes.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.txes[n];}, extra_message); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::accept_loaded_tx(const tools::wallet2::signed_tx_set &txs) { std::string extra_message; if (!txs.key_images.empty()) extra_message = (boost::format("%u key images to import. ") % (unsigned)txs.key_images.size()).str(); return accept_loaded_tx([&txs](){return txs.ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.ptx[n].construction_data;}, extra_message); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sign_transfer(const std::vector<std::string> &args_) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if(m_wallet->multisig()) { fail_msg_writer() << tr("This is a multisig wallet, it can only sign with sign_multisig"); return true; } if(m_wallet->watch_only()) { fail_msg_writer() << tr("This is a watch only wallet"); return true; } if (args_.size() > 1 || (args_.size() == 1 && args_[0] != "export_raw")) { PRINT_USAGE(USAGE_SIGN_TRANSFER); return true; } SCOPED_WALLET_UNLOCK(); const bool export_raw = args_.size() == 1; std::vector<tools::wallet2::pending_tx> ptx; try { bool r = m_wallet->sign_tx("unsigned_coinevo_tx", "signed_coinevo_tx", ptx, [&](const tools::wallet2::unsigned_tx_set &tx){ return accept_loaded_tx(tx); }, export_raw); if (!r) { fail_msg_writer() << tr("Failed to sign transaction"); return true; } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to sign transaction: ") << e.what(); return true; } std::string txids_as_text; for (const auto &t: ptx) { if (!txids_as_text.empty()) txids_as_text += (", "); txids_as_text += epee::string_tools::pod_to_hex(get_transaction_hash(t.tx)); } success_msg_writer(true) << tr("Transaction successfully signed to file ") << "signed_coinevo_tx" << ", txid " << txids_as_text; if (export_raw) { std::string rawfiles_as_text; for (size_t i = 0; i < ptx.size(); ++i) { if (i > 0) rawfiles_as_text += ", "; rawfiles_as_text += "signed_coinevo_tx_raw" + (ptx.size() == 1 ? "" : ("_" + std::to_string(i))); } success_msg_writer(true) << tr("Transaction raw hex data exported to ") << rawfiles_as_text; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::submit_transfer(const std::vector<std::string> &args_) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (!try_connect_to_daemon()) return true; try { std::vector<tools::wallet2::pending_tx> ptx_vector; bool r = m_wallet->load_tx("signed_coinevo_tx", ptx_vector, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); }); if (!r) { fail_msg_writer() << tr("Failed to load transaction from file"); return true; } commit_or_save(ptx_vector, false); } catch (const std::exception& e) { handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon()); } catch (...) { LOG_ERROR("Unknown error"); fail_msg_writer() << tr("unknown error"); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_tx_key(const std::vector<std::string> &args_) { std::vector<std::string> local_args = args_; if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if(local_args.size() != 1) { PRINT_USAGE(USAGE_GET_TX_KEY); return true; } crypto::hash txid; if (!epee::string_tools::hex_to_pod(local_args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } SCOPED_WALLET_UNLOCK(); crypto::secret_key tx_key; std::vector<crypto::secret_key> additional_tx_keys; bool found_tx_key = m_wallet->get_tx_key(txid, tx_key, additional_tx_keys); if (found_tx_key) { ostringstream oss; oss << epee::string_tools::pod_to_hex(tx_key); for (size_t i = 0; i < additional_tx_keys.size(); ++i) oss << epee::string_tools::pod_to_hex(additional_tx_keys[i]); success_msg_writer() << tr("Tx key: ") << oss.str(); return true; } else { fail_msg_writer() << tr("no tx keys found for this txid"); return true; } } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_tx_key(const std::vector<std::string> &args_) { std::vector<std::string> local_args = args_; if(local_args.size() != 2) { PRINT_USAGE(USAGE_SET_TX_KEY); return true; } crypto::hash txid; if (!epee::string_tools::hex_to_pod(local_args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } crypto::secret_key tx_key; std::vector<crypto::secret_key> additional_tx_keys; try { if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key)) { fail_msg_writer() << tr("failed to parse tx_key"); return true; } while(true) { local_args[1] = local_args[1].substr(64); if (local_args[1].empty()) break; additional_tx_keys.resize(additional_tx_keys.size() + 1); if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back())) { fail_msg_writer() << tr("failed to parse tx_key"); return true; } } } catch (const std::out_of_range &e) { fail_msg_writer() << tr("failed to parse tx_key"); return true; } LOCK_IDLE_SCOPE(); try { m_wallet->set_tx_key(txid, tx_key, additional_tx_keys); success_msg_writer() << tr("Tx key successfully stored."); } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to store tx key: ") << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_tx_proof(const std::vector<std::string> &args) { if (args.size() != 2 && args.size() != 3) { PRINT_USAGE(USAGE_GET_TX_PROOF); return true; } crypto::hash txid; if(!epee::string_tools::hex_to_pod(args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } SCOPED_WALLET_UNLOCK(); try { std::string sig_str = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, args.size() == 3 ? args[2] : ""); const std::string filename = "coinevo_tx_proof"; if (m_wallet->save_to_file(filename, sig_str, true)) success_msg_writer() << tr("signature file saved to: ") << filename; else fail_msg_writer() << tr("failed to save signature file"); } catch (const std::exception &e) { fail_msg_writer() << tr("error: ") << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_tx_key(const std::vector<std::string> &args_) { std::vector<std::string> local_args = args_; if(local_args.size() != 3) { PRINT_USAGE(USAGE_CHECK_TX_KEY); return true; } if (!try_connect_to_daemon()) return true; if (!m_wallet) { fail_msg_writer() << tr("wallet is null"); return true; } crypto::hash txid; if(!epee::string_tools::hex_to_pod(local_args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } crypto::secret_key tx_key; std::vector<crypto::secret_key> additional_tx_keys; if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key)) { fail_msg_writer() << tr("failed to parse tx key"); return true; } local_args[1] = local_args[1].substr(64); while (!local_args[1].empty()) { additional_tx_keys.resize(additional_tx_keys.size() + 1); if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back())) { fail_msg_writer() << tr("failed to parse tx key"); return true; } local_args[1] = local_args[1].substr(64); } cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[2], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } try { uint64_t received; bool in_pool; uint64_t confirmations; m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations); if (received > 0) { success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid; if (in_pool) { success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!"); } else { if (confirmations != (uint64_t)-1) { success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations; } else { success_msg_writer() << tr("WARNING: failed to determine number of confirmations!"); } } } else { fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid; } } catch (const std::exception &e) { fail_msg_writer() << tr("error: ") << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_tx_proof(const std::vector<std::string> &args) { if(args.size() != 3 && args.size() != 4) { PRINT_USAGE(USAGE_CHECK_TX_PROOF); return true; } if (!try_connect_to_daemon()) return true; // parse txid crypto::hash txid; if(!epee::string_tools::hex_to_pod(args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } // parse address cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } // read signature file std::string sig_str; if (!m_wallet->load_from_file(args[2], sig_str)) { fail_msg_writer() << tr("failed to load signature file"); return true; } try { uint64_t received; bool in_pool; uint64_t confirmations; if (m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, args.size() == 4 ? args[3] : "", sig_str, received, in_pool, confirmations)) { success_msg_writer() << tr("Good signature"); if (received > 0) { success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid; if (in_pool) { success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!"); } else { if (confirmations != (uint64_t)-1) { success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations; } else { success_msg_writer() << tr("WARNING: failed to determine number of confirmations!"); } } } else { fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid; } } else { fail_msg_writer() << tr("Bad signature"); } } catch (const std::exception &e) { fail_msg_writer() << tr("error: ") << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_spend_proof(const std::vector<std::string> &args) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if(args.size() != 1 && args.size() != 2) { PRINT_USAGE(USAGE_GET_SPEND_PROOF); return true; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot generate the proof"); return true; } crypto::hash txid; if (!epee::string_tools::hex_to_pod(args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } if (!try_connect_to_daemon()) return true; SCOPED_WALLET_UNLOCK(); try { const std::string sig_str = m_wallet->get_spend_proof(txid, args.size() == 2 ? args[1] : ""); const std::string filename = "coinevo_spend_proof"; if (m_wallet->save_to_file(filename, sig_str, true)) success_msg_writer() << tr("signature file saved to: ") << filename; else fail_msg_writer() << tr("failed to save signature file"); } catch (const std::exception &e) { fail_msg_writer() << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_spend_proof(const std::vector<std::string> &args) { if(args.size() != 2 && args.size() != 3) { PRINT_USAGE(USAGE_CHECK_SPEND_PROOF); return true; } crypto::hash txid; if (!epee::string_tools::hex_to_pod(args[0], txid)) { fail_msg_writer() << tr("failed to parse txid"); return true; } if (!try_connect_to_daemon()) return true; std::string sig_str; if (!m_wallet->load_from_file(args[1], sig_str)) { fail_msg_writer() << tr("failed to load signature file"); return true; } try { if (m_wallet->check_spend_proof(txid, args.size() == 3 ? args[2] : "", sig_str)) success_msg_writer() << tr("Good signature"); else fail_msg_writer() << tr("Bad signature"); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_reserve_proof(const std::vector<std::string> &args) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if(args.size() != 1 && args.size() != 2) { PRINT_USAGE(USAGE_GET_RESERVE_PROOF); return true; } if (m_wallet->watch_only() || m_wallet->multisig()) { fail_msg_writer() << tr("The reserve proof can be generated only by a full wallet"); return true; } boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve; if (args[0] != "all") { account_minreserve = std::pair<uint32_t, uint64_t>(); account_minreserve->first = m_current_subaddress_account; if (!cryptonote::parse_amount(account_minreserve->second, args[0])) { fail_msg_writer() << tr("amount is wrong: ") << args[0]; return true; } } if (!try_connect_to_daemon()) return true; SCOPED_WALLET_UNLOCK(); try { const std::string sig_str = m_wallet->get_reserve_proof(account_minreserve, args.size() == 2 ? args[1] : ""); const std::string filename = "coinevo_reserve_proof"; if (m_wallet->save_to_file(filename, sig_str, true)) success_msg_writer() << tr("signature file saved to: ") << filename; else fail_msg_writer() << tr("failed to save signature file"); } catch (const std::exception &e) { fail_msg_writer() << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_reserve_proof(const std::vector<std::string> &args) { if(args.size() != 2 && args.size() != 3) { PRINT_USAGE(USAGE_CHECK_RESERVE_PROOF); return true; } if (!try_connect_to_daemon()) return true; cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[0], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } if (info.is_subaddress) { fail_msg_writer() << tr("Address must not be a subaddress"); return true; } std::string sig_str; if (!m_wallet->load_from_file(args[1], sig_str)) { fail_msg_writer() << tr("failed to load signature file"); return true; } LOCK_IDLE_SCOPE(); try { uint64_t total, spent; if (m_wallet->check_reserve_proof(info.address, args.size() == 3 ? args[2] : "", sig_str, total, spent)) { success_msg_writer() << boost::format(tr("Good signature -- total: %s, spent: %s, unspent: %s")) % print_money(total) % print_money(spent) % print_money(total - spent); } else { fail_msg_writer() << tr("Bad signature"); } } catch (const std::exception& e) { fail_msg_writer() << e.what(); } return true; } //---------------------------------------------------------------------------------------------------- static std::string get_human_readable_timespan(std::chrono::seconds seconds) { uint64_t ts = seconds.count(); if (ts < 60) return std::to_string(ts) + sw::tr(" seconds"); if (ts < 3600) return std::to_string((uint64_t)(ts / 60)) + sw::tr(" minutes"); if (ts < 3600 * 24) return std::to_string((uint64_t)(ts / 3600)) + sw::tr(" hours"); if (ts < 3600 * 24 * 30.5) return std::to_string((uint64_t)(ts / (3600 * 24))) + sw::tr(" days"); if (ts < 3600 * 24 * 365.25) return std::to_string((uint64_t)(ts / (3600 * 24 * 30.5))) + sw::tr(" months"); return sw::tr("a long time"); } //---------------------------------------------------------------------------------------------------- // mutates local_args as it parses and consumes arguments bool simple_wallet::get_transfers(std::vector<std::string>& local_args, std::vector<transfer_view>& transfers) { bool in = true; bool out = true; bool pending = true; bool failed = true; bool pool = true; bool coinbase = true; uint64_t min_height = 0; uint64_t max_height = (uint64_t)-1; // optional in/out selector if (local_args.size() > 0) { if (local_args[0] == "in" || local_args[0] == "incoming") { out = pending = failed = false; local_args.erase(local_args.begin()); } else if (local_args[0] == "out" || local_args[0] == "outgoing") { in = pool = coinbase = false; local_args.erase(local_args.begin()); } else if (local_args[0] == "pending") { in = out = failed = coinbase = false; local_args.erase(local_args.begin()); } else if (local_args[0] == "failed") { in = out = pending = pool = coinbase = false; local_args.erase(local_args.begin()); } else if (local_args[0] == "pool") { in = out = pending = failed = coinbase = false; local_args.erase(local_args.begin()); } else if (local_args[0] == "coinbase") { in = out = pending = failed = pool = false; coinbase = true; local_args.erase(local_args.begin()); } else if (local_args[0] == "all" || local_args[0] == "both") { local_args.erase(local_args.begin()); } } // subaddr_index std::set<uint32_t> subaddr_indices; if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=") { if (!parse_subaddress_indices(local_args[0], subaddr_indices)) return false; local_args.erase(local_args.begin()); } // min height if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) { try { min_height = boost::lexical_cast<uint64_t>(local_args[0]); } catch (const boost::bad_lexical_cast &) { fail_msg_writer() << tr("bad min_height parameter:") << " " << local_args[0]; return false; } local_args.erase(local_args.begin()); } // max height if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) { try { max_height = boost::lexical_cast<uint64_t>(local_args[0]); } catch (const boost::bad_lexical_cast &) { fail_msg_writer() << tr("bad max_height parameter:") << " " << local_args[0]; return false; } local_args.erase(local_args.begin()); } const uint64_t last_block_height = m_wallet->get_blockchain_current_height(); if (in || coinbase) { std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments; m_wallet->get_payments(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices); for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) { const tools::wallet2::payment_details &pd = i->second; if (!pd.m_coinbase && !in) continue; std::string payment_id = string_tools::pod_to_hex(i->first); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); std::string note = m_wallet->get_tx_note(pd.m_tx_hash); std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor}); const std::string type = pd.m_coinbase ? tr("block") : tr("in"); const bool unlocked = m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height); std::string locked_msg = "unlocked"; if (!unlocked) { locked_msg = "locked"; const uint64_t unlock_time = pd.m_unlock_time; if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER) { uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE); if (bh >= last_block_height) locked_msg = std::to_string(bh - last_block_height) + " blks"; } else { uint64_t current_time = static_cast<uint64_t>(time(NULL)); uint64_t threshold = current_time + (m_wallet->use_fork_rules(2, 0) ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1); if (threshold < pd.m_unlock_time) locked_msg = get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold)); } } transfers.push_back({ type, pd.m_block_height, pd.m_timestamp, type, true, pd.m_amount, pd.m_tx_hash, payment_id, 0, {{destination, pd.m_amount}}, {pd.m_subaddr_index.minor}, note, locked_msg }); } } if (out) { std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments; m_wallet->get_payments_out(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices); for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) { const tools::wallet2::confirmed_transfer_details &pd = i->second; uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known uint64_t fee = pd.m_amount_in - pd.m_amount_out; std::vector<std::pair<std::string, uint64_t>> destinations; for (const auto &d: pd.m_dests) { destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount}); } std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); std::string note = m_wallet->get_tx_note(i->first); transfers.push_back({ "out", pd.m_block_height, pd.m_timestamp, "out", true, pd.m_amount_in - change - fee, i->first, payment_id, fee, destinations, pd.m_subaddr_indices, note, "-" }); } } if (pool) { try { m_in_manual_refresh.store(true, std::memory_order_relaxed); epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);}); std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs; m_wallet->update_pool_state(process_txs); if (!process_txs.empty()) m_wallet->process_pool_state(process_txs); std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments; m_wallet->get_unconfirmed_payments(payments, m_current_subaddress_account, subaddr_indices); for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) { const tools::wallet2::payment_details &pd = i->second.m_pd; std::string payment_id = string_tools::pod_to_hex(i->first); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); std::string note = m_wallet->get_tx_note(pd.m_tx_hash); std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor}); std::string double_spend_note; if (i->second.m_double_spend_seen) double_spend_note = tr("[Double spend seen on the network: this transaction may or may not end up being mined] "); transfers.push_back({ "pool", "pool", pd.m_timestamp, "in", false, pd.m_amount, pd.m_tx_hash, payment_id, 0, {{destination, pd.m_amount}}, {pd.m_subaddr_index.minor}, note + double_spend_note, "locked" }); } } catch (const std::exception& e) { fail_msg_writer() << "Failed to get pool state:" << e.what(); } } // print unconfirmed last if (pending || failed) { std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments; m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account, subaddr_indices); for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) { const tools::wallet2::unconfirmed_transfer_details &pd = i->second; uint64_t amount = pd.m_amount_in; uint64_t fee = amount - pd.m_amount_out; std::vector<std::pair<std::string, uint64_t>> destinations; for (const auto &d: pd.m_dests) { destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount}); } std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); std::string note = m_wallet->get_tx_note(i->first); bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed; if ((failed && is_failed) || (!is_failed && pending)) { transfers.push_back({ (is_failed ? "failed" : "pending"), (is_failed ? "failed" : "pending"), pd.m_timestamp, "out", false, amount - pd.m_change - fee, i->first, payment_id, fee, destinations, pd.m_subaddr_indices, note, "-" }); } } } // sort by block, then by timestamp (unconfirmed last) std::sort(transfers.begin(), transfers.end(), [](const transfer_view& a, const transfer_view& b) -> bool { if (a.confirmed && !b.confirmed) return true; if (a.block == b.block) return a.timestamp < b.timestamp; return a.block < b.block; }); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_transfers(const std::vector<std::string> &args_) { std::vector<std::string> local_args = args_; if(local_args.size() > 4) { fail_msg_writer() << tr("usage: show_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]"); return true; } LOCK_IDLE_SCOPE(); std::vector<transfer_view> all_transfers; if (!get_transfers(local_args, all_transfers)) return true; PAUSE_READLINE(); for (const auto& transfer : all_transfers) { const auto color = transfer.type == "failed" ? console_color_red : transfer.confirmed ? ((transfer.direction == "in" || transfer.direction == "block") ? console_color_green : console_color_magenta) : console_color_default; std::string destinations = "-"; if (!transfer.outputs.empty()) { destinations = ""; for (const auto& output : transfer.outputs) { if (!destinations.empty()) destinations += ", "; destinations += (transfer.direction == "in" ? output.first.substr(0, 6) : output.first) + ":" + print_money(output.second); } } auto formatter = boost::format("%8.8llu %6.6s %8.8s %25.25s %20.20s %s %s %14.14s %s %s - %s"); message_writer(color, false) << formatter % transfer.block % transfer.direction % transfer.unlocked % tools::get_human_readable_timestamp(transfer.timestamp) % print_money(transfer.amount) % string_tools::pod_to_hex(transfer.hash) % transfer.payment_id % print_money(transfer.fee) % destinations % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ") % transfer.note; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::export_transfers(const std::vector<std::string>& args_) { std::vector<std::string> local_args = args_; if(local_args.size() > 5) { fail_msg_writer() << tr("usage: export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<path>]"); return true; } LOCK_IDLE_SCOPE(); std::vector<transfer_view> all_transfers; // might consumes arguments in local_args if (!get_transfers(local_args, all_transfers)) return true; // output filename std::string filename = (boost::format("output%u.csv") % m_current_subaddress_account).str(); if (local_args.size() > 0 && local_args[0].substr(0, 7) == "output=") { filename = local_args[0].substr(7, -1); local_args.erase(local_args.begin()); } std::ofstream file(filename); // header file << boost::format("%8.8s,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,%s,%s") % tr("block") % tr("direction") % tr("unlocked") % tr("timestamp") % tr("amount") % tr("running balance") % tr("hash") % tr("payment ID") % tr("fee") % tr("destination") % tr("amount") % tr("index") % tr("note") << std::endl; uint64_t running_balance = 0; auto formatter = boost::format("%8.8llu,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,\"%s\",%s"); for (const auto& transfer : all_transfers) { // ignore unconfirmed transfers in running balance if (transfer.confirmed) { if (transfer.direction == "in" || transfer.direction == "block") running_balance += transfer.amount; else running_balance -= transfer.amount + transfer.fee; } file << formatter % transfer.block % transfer.direction % transfer.unlocked % tools::get_human_readable_timestamp(transfer.timestamp) % print_money(transfer.amount) % print_money(running_balance) % string_tools::pod_to_hex(transfer.hash) % transfer.payment_id % print_money(transfer.fee) % (transfer.outputs.size() ? transfer.outputs[0].first : "-") % (transfer.outputs.size() ? print_money(transfer.outputs[0].second) : "") % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ") % transfer.note << std::endl; for (size_t i = 1; i < transfer.outputs.size(); ++i) { file << formatter % "" % "" % "" % "" % "" % "" % "" % "" % "" % transfer.outputs[i].first % print_money(transfer.outputs[i].second) % "" % "" << std::endl; } } file.close(); success_msg_writer() << tr("CSV exported to ") << filename; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::unspent_outputs(const std::vector<std::string> &args_) { if(args_.size() > 3) { PRINT_USAGE(USAGE_UNSPENT_OUTPUTS); return true; } auto local_args = args_; std::set<uint32_t> subaddr_indices; if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=") { if (!parse_subaddress_indices(local_args[0], subaddr_indices)) return true; local_args.erase(local_args.begin()); } uint64_t min_amount = 0; uint64_t max_amount = std::numeric_limits<uint64_t>::max(); if (local_args.size() > 0) { if (!cryptonote::parse_amount(min_amount, local_args[0])) { fail_msg_writer() << tr("amount is wrong: ") << local_args[0]; return true; } local_args.erase(local_args.begin()); if (local_args.size() > 0) { if (!cryptonote::parse_amount(max_amount, local_args[0])) { fail_msg_writer() << tr("amount is wrong: ") << local_args[0]; return true; } local_args.erase(local_args.begin()); } if (min_amount > max_amount) { fail_msg_writer() << tr("<min_amount> should be smaller than <max_amount>"); return true; } } tools::wallet2::transfer_container transfers; m_wallet->get_transfers(transfers); std::map<uint64_t, tools::wallet2::transfer_container> amount_to_tds; uint64_t min_height = std::numeric_limits<uint64_t>::max(); uint64_t max_height = 0; uint64_t found_min_amount = std::numeric_limits<uint64_t>::max(); uint64_t found_max_amount = 0; uint64_t count = 0; for (const auto& td : transfers) { uint64_t amount = td.amount(); if (td.m_spent || amount < min_amount || amount > max_amount || td.m_subaddr_index.major != m_current_subaddress_account || (subaddr_indices.count(td.m_subaddr_index.minor) == 0 && !subaddr_indices.empty())) continue; amount_to_tds[amount].push_back(td); if (min_height > td.m_block_height) min_height = td.m_block_height; if (max_height < td.m_block_height) max_height = td.m_block_height; if (found_min_amount > amount) found_min_amount = amount; if (found_max_amount < amount) found_max_amount = amount; ++count; } if (amount_to_tds.empty()) { success_msg_writer() << tr("There is no unspent output in the specified address"); return true; } for (const auto& amount_tds : amount_to_tds) { auto& tds = amount_tds.second; success_msg_writer() << tr("\nAmount: ") << print_money(amount_tds.first) << tr(", number of keys: ") << tds.size(); for (size_t i = 0; i < tds.size(); ) { std::ostringstream oss; for (size_t j = 0; j < 8 && i < tds.size(); ++i, ++j) oss << tds[i].m_block_height << tr(" "); success_msg_writer() << oss.str(); } } success_msg_writer() << tr("\nMin block height: ") << min_height << tr("\nMax block height: ") << max_height << tr("\nMin amount found: ") << print_money(found_min_amount) << tr("\nMax amount found: ") << print_money(found_max_amount) << tr("\nTotal count: ") << count; const size_t histogram_height = 10; const size_t histogram_width = 50; double bin_size = (max_height - min_height + 1.0) / histogram_width; size_t max_bin_count = 0; std::vector<size_t> histogram(histogram_width, 0); for (const auto& amount_tds : amount_to_tds) { for (auto& td : amount_tds.second) { uint64_t bin_index = (td.m_block_height - min_height + 1) / bin_size; if (bin_index >= histogram_width) bin_index = histogram_width - 1; histogram[bin_index]++; if (max_bin_count < histogram[bin_index]) max_bin_count = histogram[bin_index]; } } for (size_t x = 0; x < histogram_width; ++x) { double bin_count = histogram[x]; if (max_bin_count > histogram_height) bin_count *= histogram_height / (double)max_bin_count; if (histogram[x] > 0 && bin_count < 1.0) bin_count = 1.0; histogram[x] = bin_count; } std::vector<std::string> histogram_line(histogram_height, std::string(histogram_width, ' ')); for (size_t y = 0; y < histogram_height; ++y) { for (size_t x = 0; x < histogram_width; ++x) { if (y < histogram[x]) histogram_line[y][x] = '*'; } } double count_per_star = max_bin_count / (double)histogram_height; if (count_per_star < 1) count_per_star = 1; success_msg_writer() << tr("\nBin size: ") << bin_size << tr("\nOutputs per *: ") << count_per_star; ostringstream histogram_str; histogram_str << tr("count\n ^\n"); for (size_t y = histogram_height; y > 0; --y) histogram_str << tr(" |") << histogram_line[y - 1] << tr("|\n"); histogram_str << tr(" +") << std::string(histogram_width, '-') << tr("+--> block height\n") << tr(" ^") << std::string(histogram_width - 2, ' ') << tr("^\n") << tr(" ") << min_height << std::string(histogram_width - 8, ' ') << max_height; success_msg_writer() << histogram_str.str(); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::rescan_blockchain(const std::vector<std::string> &args_) { uint64_t start_height = 0; ResetType reset_type = ResetSoft; if (!args_.empty()) { if (args_[0] == "hard") { reset_type = ResetHard; } else if (args_[0] == "soft") { reset_type = ResetSoft; } else if (args_[0] == "keep_ki") { reset_type = ResetSoftKeepKI; } else { PRINT_USAGE(USAGE_RESCAN_BC); return true; } if (args_.size() > 1) { try { start_height = boost::lexical_cast<uint64_t>( args_[1] ); } catch(const boost::bad_lexical_cast &) { start_height = 0; } } } if (reset_type == ResetHard) { message_writer() << tr("Warning: this will lose any information which can not be recovered from the blockchain."); message_writer() << tr("This includes destination addresses, tx secret keys, tx notes, etc"); std::string confirm = input_line(tr("Rescan anyway?"), true); if(!std::cin.eof()) { if (!command_line::is_yes(confirm)) return true; } } const uint64_t wallet_from_height = m_wallet->get_refresh_from_block_height(); if (start_height > wallet_from_height) { message_writer() << tr("Warning: your restore height is higher than wallet restore height: ") << wallet_from_height; std::string confirm = input_line(tr("Rescan anyway ? (Y/Yes/N/No): ")); if(!std::cin.eof()) { if (!command_line::is_yes(confirm)) return true; } } return refresh_main(start_height, reset_type, true); } //---------------------------------------------------------------------------------------------------- void simple_wallet::check_for_messages() { try { std::vector<mms::message> new_messages; bool new_message = get_message_store().check_for_messages(get_multisig_wallet_state(), new_messages); if (new_message) { message_writer(console_color_magenta, true) << tr("MMS received new message"); list_mms_messages(new_messages); m_cmd_binder.print_prompt(); } } catch(...) {} } //---------------------------------------------------------------------------------------------------- void simple_wallet::wallet_idle_thread() { const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time(); while (true) { boost::unique_lock<boost::mutex> lock(m_idle_mutex); if (!m_idle_run.load(std::memory_order_relaxed)) break; // if another thread was busy (ie, a foreground refresh thread), we'll end up here at // some random time that's not what we slept for, so we should not call refresh now // or we'll be leaking that fact through timing const boost::posix_time::ptime now0 = boost::posix_time::microsec_clock::universal_time(); const uint64_t dt_actual = (now0 - start_time).total_microseconds() % 1000000; #ifdef _WIN32 static const uint64_t threshold = 10000; #else static const uint64_t threshold = 2000; #endif if (dt_actual < threshold) // if less than a threshold... would a very slow machine always miss it ? { #ifndef _WIN32 m_inactivity_checker.do_call(boost::bind(&simple_wallet::check_inactivity, this)); #endif m_refresh_checker.do_call(boost::bind(&simple_wallet::check_refresh, this)); m_mms_checker.do_call(boost::bind(&simple_wallet::check_mms, this)); m_rpc_payment_checker.do_call(boost::bind(&simple_wallet::check_rpc_payment, this)); if (!m_idle_run.load(std::memory_order_relaxed)) break; } // aim for the next multiple of 1 second const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); const auto dt = (now - start_time).total_microseconds(); const auto wait = 1000000 - dt % 1000000; m_idle_cond.wait_for(lock, boost::chrono::microseconds(wait)); } } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_inactivity() { // inactivity lock if (!m_locked && !m_in_command) { const uint32_t seconds = m_wallet->inactivity_lock_timeout(); if (seconds > 0 && time(NULL) - m_last_activity_time > seconds) { m_locked = true; m_cmd_binder.cancel_input(); } } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_refresh() { // auto refresh if (m_auto_refresh_enabled) { m_auto_refresh_refreshing = true; try { uint64_t fetched_blocks; bool received_money; if (try_connect_to_daemon(true)) m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, fetched_blocks, received_money, false); // don't check the pool in background mode } catch(...) {} m_auto_refresh_refreshing = false; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_mms() { // Check for new MMS messages; // For simplicity auto message check is ALSO controlled by "m_auto_refresh_enabled" and has no // separate thread either; thread syncing is tricky enough with only this one idle thread here if (m_auto_refresh_enabled && get_message_store().get_active()) { check_for_messages(); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::check_rpc_payment() { if (!m_rpc_payment_mining_requested && m_wallet->auto_mine_for_rpc_payment_threshold() == 0.0f) return true; uint64_t target = m_wallet->credits_target(); if (target == 0) target = CREDITS_TARGET; if (m_rpc_payment_mining_requested) target = std::numeric_limits<uint64_t>::max(); bool need_payment = m_need_payment || m_rpc_payment_mining_requested || (m_wallet->credits() < target && m_wallet->daemon_requires_payment()); if (need_payment) { const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time(); auto startfunc = [this](uint64_t diff, uint64_t credits_per_hash_found) { const float cph = credits_per_hash_found / (float)diff; bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE); if (credits_per_hash_found > 0 && cph >= m_wallet->auto_mine_for_rpc_payment_threshold()) { MINFO(std::to_string(cph) << " credits per hash is >= our threshold (" << m_wallet->auto_mine_for_rpc_payment_threshold() << "), starting mining"); return true; } else if (m_rpc_payment_mining_requested) { MINFO("Mining for RPC payment was requested, starting mining"); return true; } else { if (!m_daemon_rpc_payment_message_displayed) { success_msg_writer() << boost::format(tr("Daemon requests payment at diff %llu, with %f credits/hash%s. Run start_mining_for_rpc to start mining to pay for RPC access, or use another daemon")) % diff % cph % (low ? " - this is low" : ""); m_cmd_binder.print_prompt(); m_daemon_rpc_payment_message_displayed = true; } return false; } }; auto contfunc = [&,this](unsigned n_hashes) { if (m_suspend_rpc_payment_mining.load(std::memory_order_relaxed)) return false; const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); m_last_rpc_payment_mining_time = now; if ((now - start_time).total_microseconds() >= 2 * 1000000) m_rpc_payment_hash_rate = n_hashes / (float)((now - start_time).total_seconds()); if ((now - start_time).total_microseconds() >= REFRESH_PERIOD * 1000000) return false; return true; }; auto foundfunc = [this, target](uint64_t credits) { m_need_payment = false; return credits < target; }; auto errorfunc = [this](const std::string &error) { fail_msg_writer() << tr("Error mining to daemon: ") << error; m_cmd_binder.print_prompt(); }; bool ret = m_wallet->search_for_rpc_payment(target, startfunc, contfunc, foundfunc, errorfunc); if (!ret) { fail_msg_writer() << tr("Failed to start mining for RPC payment"); m_cmd_binder.print_prompt(); } } return true; } //---------------------------------------------------------------------------------------------------- std::string simple_wallet::get_prompt() const { if (m_locked) return std::string("[") + tr("locked due to inactivity") + "]"; std::string addr_start = m_wallet->get_subaddress_as_str({m_current_subaddress_account, 0}).substr(0, 6); std::string prompt = std::string("[") + tr("wallet") + " " + addr_start; if (!m_wallet->check_connection(NULL)) prompt += tr(" (no daemon)"); else if (!m_wallet->is_synced()) prompt += tr(" (out of sync)"); prompt += "]: "; return prompt; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::run() { // check and display warning, but go on anyway try_connect_to_daemon(); refresh_main(0, ResetNone, true); m_auto_refresh_enabled = m_wallet->auto_refresh(); m_idle_thread = boost::thread([&]{wallet_idle_thread();}); message_writer(console_color_green, false) << "Background refresh thread started"; return m_cmd_binder.run_handling([this](){return get_prompt();}, ""); } //---------------------------------------------------------------------------------------------------- void simple_wallet::stop() { m_cmd_binder.stop_handling(); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::account(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { // Usage: // account // account new <label text with white spaces allowed> // account switch <index> // account label <index> <label text with white spaces allowed> // account tag <tag_name> <account_index_1> [<account_index_2> ...] // account untag <account_index_1> [<account_index_2> ...] // account tag_description <tag_name> <description> if (args.empty()) { // print all the existing accounts LOCK_IDLE_SCOPE(); print_accounts(); return true; } std::vector<std::string> local_args = args; std::string command = local_args[0]; local_args.erase(local_args.begin()); if (command == "new") { // create a new account and switch to it std::string label = boost::join(local_args, " "); if (label.empty()) label = tr("(Untitled account)"); m_wallet->add_subaddress_account(label); m_current_subaddress_account = m_wallet->get_num_subaddress_accounts() - 1; // update_prompt(); LOCK_IDLE_SCOPE(); print_accounts(); } else if (command == "switch" && local_args.size() == 1) { // switch to the specified account uint32_t index_major; if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[0]; return true; } if (index_major >= m_wallet->get_num_subaddress_accounts()) { fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddress_accounts() - 1); return true; } m_current_subaddress_account = index_major; // update_prompt(); show_balance(); } else if (command == "label" && local_args.size() >= 1) { // set label of the specified account uint32_t index_major; if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[0]; return true; } local_args.erase(local_args.begin()); std::string label = boost::join(local_args, " "); try { m_wallet->set_subaddress_label({index_major, 0}, label); LOCK_IDLE_SCOPE(); print_accounts(); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } } else if (command == "tag" && local_args.size() >= 2) { const std::string tag = local_args[0]; std::set<uint32_t> account_indices; for (size_t i = 1; i < local_args.size(); ++i) { uint32_t account_index; if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[i]; return true; } account_indices.insert(account_index); } try { m_wallet->set_account_tag(account_indices, tag); print_accounts(tag); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } } else if (command == "untag" && local_args.size() >= 1) { std::set<uint32_t> account_indices; for (size_t i = 0; i < local_args.size(); ++i) { uint32_t account_index; if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[i]; return true; } account_indices.insert(account_index); } try { m_wallet->set_account_tag(account_indices, ""); print_accounts(); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } } else if (command == "tag_description" && local_args.size() >= 1) { const std::string tag = local_args[0]; std::string description; if (local_args.size() > 1) { local_args.erase(local_args.begin()); description = boost::join(local_args, " "); } try { m_wallet->set_account_tag_description(tag, description); print_accounts(tag); } catch (const std::exception& e) { fail_msg_writer() << e.what(); } } else { PRINT_USAGE(USAGE_ACCOUNT); } return true; } //---------------------------------------------------------------------------------------------------- void simple_wallet::print_accounts() { const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags(); size_t num_untagged_accounts = m_wallet->get_num_subaddress_accounts(); for (const std::pair<std::string, std::string>& p : account_tags.first) { const std::string& tag = p.first; print_accounts(tag); num_untagged_accounts -= std::count(account_tags.second.begin(), account_tags.second.end(), tag); success_msg_writer() << ""; } if (num_untagged_accounts > 0) print_accounts(""); if (num_untagged_accounts < m_wallet->get_num_subaddress_accounts()) success_msg_writer() << tr("\nGrand total:\n Balance: ") << print_money(m_wallet->balance_all(false)) << tr(", unlocked balance: ") << print_money(m_wallet->unlocked_balance_all(false)); } //---------------------------------------------------------------------------------------------------- void simple_wallet::print_accounts(const std::string& tag) { const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags(); if (tag.empty()) { success_msg_writer() << tr("Untagged accounts:"); } else { if (account_tags.first.count(tag) == 0) { fail_msg_writer() << boost::format(tr("Tag %s is unregistered.")) % tag; return; } success_msg_writer() << tr("Accounts with tag: ") << tag; success_msg_writer() << tr("Tag's description: ") << account_tags.first.find(tag)->second; } success_msg_writer() << boost::format(" %15s %21s %21s %21s") % tr("Account") % tr("Balance") % tr("Unlocked balance") % tr("Label"); uint64_t total_balance = 0, total_unlocked_balance = 0; for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index) { if (account_tags.second[account_index] != tag) continue; success_msg_writer() << boost::format(tr(" %c%8u %6s %21s %21s %21s")) % (m_current_subaddress_account == account_index ? '*' : ' ') % account_index % m_wallet->get_subaddress_as_str({account_index, 0}).substr(0, 6) % print_money(m_wallet->balance(account_index, false)) % print_money(m_wallet->unlocked_balance(account_index, false)) % m_wallet->get_subaddress_label({account_index, 0}); total_balance += m_wallet->balance(account_index, false); total_unlocked_balance += m_wallet->unlocked_balance(account_index, false); } success_msg_writer() << tr("----------------------------------------------------------------------------------"); success_msg_writer() << boost::format(tr("%15s %21s %21s")) % "Total" % print_money(total_balance) % print_money(total_unlocked_balance); } //---------------------------------------------------------------------------------------------------- bool simple_wallet::print_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { // Usage: // address // address new <label text with white spaces allowed> // address all // address <index_min> [<index_max>] // address label <index> <label text with white spaces allowed> // address device [<index>] std::vector<std::string> local_args = args; tools::wallet2::transfer_container transfers; m_wallet->get_transfers(transfers); auto print_address_sub = [this, &transfers](uint32_t index) { bool used = std::find_if( transfers.begin(), transfers.end(), [this, &index](const tools::wallet2::transfer_details& td) { return td.m_subaddr_index == cryptonote::subaddress_index{ m_current_subaddress_account, index }; }) != transfers.end(); success_msg_writer() << index << " " << m_wallet->get_subaddress_as_str({m_current_subaddress_account, index}) << " " << (index == 0 ? tr("Primary address") : m_wallet->get_subaddress_label({m_current_subaddress_account, index})) << " " << (used ? tr("(used)") : ""); }; uint32_t index = 0; if (local_args.empty()) { print_address_sub(index); } else if (local_args.size() == 1 && local_args[0] == "all") { local_args.erase(local_args.begin()); for (; index < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++index) print_address_sub(index); } else if (local_args[0] == "new") { local_args.erase(local_args.begin()); std::string label; if (local_args.size() > 0) label = boost::join(local_args, " "); if (label.empty()) label = tr("(Untitled address)"); m_wallet->add_subaddress(m_current_subaddress_account, label); print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1); m_wallet->device_show_address(m_current_subaddress_account, m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1, boost::none); } else if (local_args.size() >= 2 && local_args[0] == "label") { if (!epee::string_tools::get_xtype_from_string(index, local_args[1])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[1]; return true; } if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account)) { fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1); return true; } local_args.erase(local_args.begin()); local_args.erase(local_args.begin()); std::string label = boost::join(local_args, " "); m_wallet->set_subaddress_label({m_current_subaddress_account, index}, label); print_address_sub(index); } else if (local_args.size() <= 2 && epee::string_tools::get_xtype_from_string(index, local_args[0])) { local_args.erase(local_args.begin()); uint32_t index_min = index; uint32_t index_max = index_min; if (local_args.size() > 0) { if (!epee::string_tools::get_xtype_from_string(index_max, local_args[0])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[0]; return true; } local_args.erase(local_args.begin()); } if (index_max < index_min) std::swap(index_min, index_max); if (index_min >= m_wallet->get_num_subaddresses(m_current_subaddress_account)) { fail_msg_writer() << tr("<index_min> is already out of bound"); return true; } if (index_max >= m_wallet->get_num_subaddresses(m_current_subaddress_account)) { message_writer() << tr("<index_max> exceeds the bound"); index_max = m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1; } for (index = index_min; index <= index_max; ++index) print_address_sub(index); } else if (local_args[0] == "device") { index = 0; local_args.erase(local_args.begin()); if (local_args.size() > 0) { if (!epee::string_tools::get_xtype_from_string(index, local_args[0])) { fail_msg_writer() << tr("failed to parse index: ") << local_args[0]; return true; } if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account)) { fail_msg_writer() << tr("<index> is out of bounds"); return true; } } print_address_sub(index); m_wallet->device_show_address(m_current_subaddress_account, index, boost::none); } else { PRINT_USAGE(USAGE_ADDRESS); } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::print_integrated_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { crypto::hash8 payment_id; bool display_on_device = false; std::vector<std::string> local_args = args; if (local_args.size() > 0 && local_args[0] == "device") { local_args.erase(local_args.begin()); display_on_device = true; } auto device_show_integrated = [this, display_on_device](crypto::hash8 payment_id) { if (display_on_device) { m_wallet->device_show_address(m_current_subaddress_account, 0, payment_id); } }; if (local_args.size() > 1) { PRINT_USAGE(USAGE_INTEGRATED_ADDRESS); return true; } if (local_args.size() == 0) { if (m_current_subaddress_account != 0) { fail_msg_writer() << tr("Integrated addresses can only be created for account 0"); return true; } payment_id = crypto::rand<crypto::hash8>(); success_msg_writer() << tr("Random payment ID: ") << payment_id; success_msg_writer() << tr("Matching integrated address: ") << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype()); device_show_integrated(payment_id); return true; } if(tools::wallet2::parse_short_payment_id(local_args.back(), payment_id)) { if (m_current_subaddress_account != 0) { fail_msg_writer() << tr("Integrated addresses can only be created for account 0"); return true; } success_msg_writer() << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype()); device_show_integrated(payment_id); return true; } else { address_parse_info info; if(get_account_address_from_str(info, m_wallet->nettype(), local_args.back())) { if (info.has_payment_id) { success_msg_writer() << boost::format(tr("Integrated address: %s, payment ID: %s")) % get_account_address_as_str(m_wallet->nettype(), false, info.address) % epee::string_tools::pod_to_hex(info.payment_id); device_show_integrated(info.payment_id); } else { success_msg_writer() << (info.is_subaddress ? tr("Subaddress: ") : tr("Standard address: ")) << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address); } return true; } } fail_msg_writer() << tr("failed to parse payment ID or address"); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (args.size() == 0) { } else if (args.size() == 1 || (args[0] != "add" && args[0] != "delete")) { PRINT_USAGE(USAGE_ADDRESS_BOOK); return true; } else if (args[0] == "add") { cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } crypto::hash payment_id = crypto::null_hash; size_t description_start = 2; if (info.has_payment_id) { memcpy(payment_id.data, info.payment_id.data, 8); } else if (!info.has_payment_id && args.size() >= 4 && args[2] == "pid") { if (tools::wallet2::parse_long_payment_id(args[3], payment_id)) { LONG_PAYMENT_ID_SUPPORT_CHECK(); description_start += 2; } else if (tools::wallet2::parse_short_payment_id(args[3], info.payment_id)) { fail_msg_writer() << tr("Short payment IDs are to be used within an integrated address only"); return true; } else { fail_msg_writer() << tr("failed to parse payment ID"); return true; } } std::string description; for (size_t i = description_start; i < args.size(); ++i) { if (i > description_start) description += " "; description += args[i]; } m_wallet->add_address_book_row(info.address, payment_id, description, info.is_subaddress); } else { size_t row_id; if(!epee::string_tools::get_xtype_from_string(row_id, args[1])) { fail_msg_writer() << tr("failed to parse index"); return true; } m_wallet->delete_address_book_row(row_id); } auto address_book = m_wallet->get_address_book(); if (address_book.empty()) { success_msg_writer() << tr("Address book is empty."); } else { for (size_t i = 0; i < address_book.size(); ++i) { auto& row = address_book[i]; success_msg_writer() << tr("Index: ") << i; success_msg_writer() << tr("Address: ") << get_account_address_as_str(m_wallet->nettype(), row.m_is_subaddress, row.m_address); success_msg_writer() << tr("Payment ID: ") << row.m_payment_id << " (OBSOLETE)"; success_msg_writer() << tr("Description: ") << row.m_description << "\n"; } } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_tx_note(const std::vector<std::string> &args) { if (args.size() == 0) { PRINT_USAGE(USAGE_SET_TX_NOTE); return true; } cryptonote::blobdata txid_data; if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash)) { fail_msg_writer() << tr("failed to parse txid"); return true; } crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data()); std::string note = ""; for (size_t n = 1; n < args.size(); ++n) { if (n > 1) note += " "; note += args[n]; } m_wallet->set_tx_note(txid, note); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_tx_note(const std::vector<std::string> &args) { if (args.size() != 1) { PRINT_USAGE(USAGE_GET_TX_NOTE); return true; } cryptonote::blobdata txid_data; if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash)) { fail_msg_writer() << tr("failed to parse txid"); return true; } crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data()); std::string note = m_wallet->get_tx_note(txid); if (note.empty()) success_msg_writer() << "no note found"; else success_msg_writer() << "note found: " << note; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::set_description(const std::vector<std::string> &args) { // 0 arguments allowed, for setting the description to empty string std::string description = ""; for (size_t n = 0; n < args.size(); ++n) { if (n > 0) description += " "; description += args[n]; } m_wallet->set_description(description); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::get_description(const std::vector<std::string> &args) { if (args.size() != 0) { PRINT_USAGE(USAGE_GET_DESCRIPTION); return true; } std::string description = m_wallet->get_description(); if (description.empty()) success_msg_writer() << tr("no description found"); else success_msg_writer() << tr("description found: ") << description; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::status(const std::vector<std::string> &args) { uint64_t local_height = m_wallet->get_blockchain_current_height(); uint32_t version = 0; bool ssl = false; if (!m_wallet->check_connection(&version, &ssl)) { success_msg_writer() << "Refreshed " << local_height << "/?, no daemon connected"; return true; } std::string err; uint64_t bc_height = get_daemon_blockchain_height(err); if (err.empty()) { bool synced = local_height == bc_height; success_msg_writer() << "Refreshed " << local_height << "/" << bc_height << ", " << (synced ? "synced" : "syncing") << ", daemon RPC v" << get_version_string(version) << ", " << (ssl ? "SSL" : "no SSL"); } else { fail_msg_writer() << "Refreshed " << local_height << "/?, daemon connection error"; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::wallet_info(const std::vector<std::string> &args) { bool ready; uint32_t threshold, total; std::string description = m_wallet->get_description(); if (description.empty()) { description = "<Not set>"; } message_writer() << tr("Filename: ") << m_wallet->get_wallet_file(); message_writer() << tr("Description: ") << description; message_writer() << tr("Address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); std::string type; if (m_wallet->watch_only()) type = tr("Watch only"); else if (m_wallet->multisig(&ready, &threshold, &total)) type = (boost::format(tr("%u/%u multisig%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str(); else type = tr("Normal"); message_writer() << tr("Type: ") << type; message_writer() << tr("Network type: ") << ( m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") : m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet")); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::sign(const std::vector<std::string> &args) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (args.size() != 1) { PRINT_USAGE(USAGE_SIGN); return true; } if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot sign"); return true; } if (m_wallet->multisig()) { fail_msg_writer() << tr("This wallet is multisig and cannot sign"); return true; } std::string filename = args[0]; std::string data; bool r = m_wallet->load_from_file(filename, data); if (!r) { fail_msg_writer() << tr("failed to read file ") << filename; return true; } SCOPED_WALLET_UNLOCK(); std::string signature = m_wallet->sign(data); success_msg_writer() << signature; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::verify(const std::vector<std::string> &args) { if (args.size() != 3) { PRINT_USAGE(USAGE_VERIFY); return true; } std::string filename = args[0]; std::string address_string = args[1]; std::string signature= args[2]; std::string data; bool r = m_wallet->load_from_file(filename, data); if (!r) { fail_msg_writer() << tr("failed to read file ") << filename; return true; } cryptonote::address_parse_info info; if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_string, oa_prompter)) { fail_msg_writer() << tr("failed to parse address"); return true; } r = m_wallet->verify(data, info.address, signature); if (!r) { fail_msg_writer() << tr("Bad signature from ") << address_string; } else { success_msg_writer() << tr("Good signature from ") << address_string; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::export_key_images(const std::vector<std::string> &args_) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } auto args = args_; if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot export key images"); return true; } bool all = false; if (args.size() >= 2 && args[0] == "all") { all = true; args.erase(args.begin()); } if (args.size() != 1) { PRINT_USAGE(USAGE_EXPORT_KEY_IMAGES); return true; } std::string filename = args[0]; if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename)) return true; SCOPED_WALLET_UNLOCK(); try { if (!m_wallet->export_key_images(filename, all)) { fail_msg_writer() << tr("failed to save file ") << filename; return true; } } catch (const std::exception &e) { LOG_ERROR("Error exporting key images: " << e.what()); fail_msg_writer() << "Error exporting key images: " << e.what(); return true; } success_msg_writer() << tr("Signed key images exported to ") << filename; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::import_key_images(const std::vector<std::string> &args) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (!m_wallet->is_trusted_daemon()) { fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon"); return true; } if (args.size() != 1) { PRINT_USAGE(USAGE_IMPORT_KEY_IMAGES); return true; } std::string filename = args[0]; LOCK_IDLE_SCOPE(); try { uint64_t spent = 0, unspent = 0; uint64_t height = m_wallet->import_key_images(filename, spent, unspent); success_msg_writer() << "Signed key images imported to height " << height << ", " << print_money(spent) << " spent, " << print_money(unspent) << " unspent"; } catch (const std::exception &e) { fail_msg_writer() << "Failed to import key images: " << e.what(); return true; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::hw_key_images_sync(const std::vector<std::string> &args) { if (!m_wallet->key_on_device()) { fail_msg_writer() << tr("command only supported by HW wallet"); return true; } if (!m_wallet->get_account().get_device().has_ki_cold_sync()) { fail_msg_writer() << tr("hw wallet does not support cold KI sync"); return true; } LOCK_IDLE_SCOPE(); key_images_sync_intern(); return true; } //---------------------------------------------------------------------------------------------------- void simple_wallet::key_images_sync_intern(){ try { message_writer(console_color_white, false) << tr("Please confirm the key image sync on the device"); uint64_t spent = 0, unspent = 0; uint64_t height = m_wallet->cold_key_image_sync(spent, unspent); if (height > 0) { success_msg_writer() << tr("Key images synchronized to height ") << height; if (!m_wallet->is_trusted_daemon()) { message_writer() << tr("Running untrusted daemon, cannot determine which transaction output is spent. Use a trusted daemon with --trusted-daemon and run rescan_spent"); } else { success_msg_writer() << print_money(spent) << tr(" spent, ") << print_money(unspent) << tr(" unspent"); } } else { fail_msg_writer() << tr("Failed to import key images"); } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to import key images: ") << e.what(); } } //---------------------------------------------------------------------------------------------------- bool simple_wallet::hw_reconnect(const std::vector<std::string> &args) { if (!m_wallet->key_on_device()) { fail_msg_writer() << tr("command only supported by HW wallet"); return true; } LOCK_IDLE_SCOPE(); try { bool r = m_wallet->reconnect_device(); if (!r){ fail_msg_writer() << tr("Failed to reconnect device"); } } catch (const std::exception &e) { fail_msg_writer() << tr("Failed to reconnect device: ") << tr(e.what()); return true; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::export_outputs(const std::vector<std::string> &args_) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } auto args = args_; bool all = false; if (args.size() >= 2 && args[0] == "all") { all = true; args.erase(args.begin()); } if (args.size() != 1) { PRINT_USAGE(USAGE_EXPORT_OUTPUTS); return true; } std::string filename = args[0]; if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename)) return true; SCOPED_WALLET_UNLOCK(); try { std::string data = m_wallet->export_outputs_to_str(all); bool r = m_wallet->save_to_file(filename, data); if (!r) { fail_msg_writer() << tr("failed to save file ") << filename; return true; } } catch (const std::exception &e) { LOG_ERROR("Error exporting outputs: " << e.what()); fail_msg_writer() << "Error exporting outputs: " << e.what(); return true; } success_msg_writer() << tr("Outputs exported to ") << filename; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::import_outputs(const std::vector<std::string> &args) { if (m_wallet->key_on_device()) { fail_msg_writer() << tr("command not supported by HW wallet"); return true; } if (args.size() != 1) { PRINT_USAGE(USAGE_IMPORT_OUTPUTS); return true; } std::string filename = args[0]; std::string data; bool r = m_wallet->load_from_file(filename, data); if (!r) { fail_msg_writer() << tr("failed to read file ") << filename; return true; } try { SCOPED_WALLET_UNLOCK(); size_t n_outputs = m_wallet->import_outputs_from_str(data); success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported"; } catch (const std::exception &e) { fail_msg_writer() << "Failed to import outputs " << filename << ": " << e.what(); return true; } return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::show_transfer(const std::vector<std::string> &args) { if (args.size() != 1) { PRINT_USAGE(USAGE_SHOW_TRANSFER); return true; } cryptonote::blobdata txid_data; if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash)) { fail_msg_writer() << tr("failed to parse txid"); return true; } crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data()); const uint64_t last_block_height = m_wallet->get_blockchain_current_height(); std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments; m_wallet->get_payments(payments, 0, (uint64_t)-1, m_current_subaddress_account); for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) { const tools::wallet2::payment_details &pd = i->second; if (pd.m_tx_hash == txid) { std::string payment_id = string_tools::pod_to_hex(i->first); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); success_msg_writer() << "Incoming transaction found"; success_msg_writer() << "txid: " << txid; success_msg_writer() << "Height: " << pd.m_block_height; success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp); success_msg_writer() << "Amount: " << print_money(pd.m_amount); success_msg_writer() << "Payment ID: " << payment_id; if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER) { uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE); uint64_t last_block_reward = m_wallet->get_last_block_reward(); uint64_t suggested_threshold = last_block_reward ? (pd.m_amount + last_block_reward - 1) / last_block_reward : 0; if (bh >= last_block_height) success_msg_writer() << "Locked: " << (bh - last_block_height) << " blocks to unlock"; else if (suggested_threshold > 0) success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations (" << suggested_threshold << " suggested threshold)"; else success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations"; } else { uint64_t current_time = static_cast<uint64_t>(time(NULL)); uint64_t threshold = current_time + (m_wallet->use_fork_rules(2, 0) ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1); if (threshold >= pd.m_unlock_time) success_msg_writer() << "unlocked for " << get_human_readable_timespan(std::chrono::seconds(threshold - pd.m_unlock_time)); else success_msg_writer() << "locked for " << get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold)); } success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor; success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid); return true; } } std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out; m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, m_current_subaddress_account); for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) { if (i->first == txid) { const tools::wallet2::confirmed_transfer_details &pd = i->second; uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known uint64_t fee = pd.m_amount_in - pd.m_amount_out; std::string dests; for (const auto &d: pd.m_dests) { if (!dests.empty()) dests += ", "; dests += d.address(m_wallet->nettype(), pd.m_payment_id) + ": " + print_money(d.amount); } std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); success_msg_writer() << "Outgoing transaction found"; success_msg_writer() << "txid: " << txid; success_msg_writer() << "Height: " << pd.m_block_height; success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp); success_msg_writer() << "Amount: " << print_money(pd.m_amount_in - change - fee); success_msg_writer() << "Payment ID: " << payment_id; success_msg_writer() << "Change: " << print_money(change); success_msg_writer() << "Fee: " << print_money(fee); success_msg_writer() << "Destinations: " << dests; success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid); return true; } } try { std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs; m_wallet->update_pool_state(process_txs); if (!process_txs.empty()) m_wallet->process_pool_state(process_txs); std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments; m_wallet->get_unconfirmed_payments(pool_payments, m_current_subaddress_account); for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) { const tools::wallet2::payment_details &pd = i->second.m_pd; if (pd.m_tx_hash == txid) { std::string payment_id = string_tools::pod_to_hex(i->first); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); success_msg_writer() << "Unconfirmed incoming transaction found in the txpool"; success_msg_writer() << "txid: " << txid; success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp); success_msg_writer() << "Amount: " << print_money(pd.m_amount); success_msg_writer() << "Payment ID: " << payment_id; success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor; success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid); if (i->second.m_double_spend_seen) success_msg_writer() << tr("Double spend seen on the network: this transaction may or may not end up being mined"); return true; } } } catch (...) { fail_msg_writer() << "Failed to get pool state"; } std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments; m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account); for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) { if (i->first == txid) { const tools::wallet2::unconfirmed_transfer_details &pd = i->second; uint64_t amount = pd.m_amount_in; uint64_t fee = amount - pd.m_amount_out; std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id); if (payment_id.substr(16).find_first_not_of('0') == std::string::npos) payment_id = payment_id.substr(0,16); bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed; success_msg_writer() << (is_failed ? "Failed" : "Pending") << " outgoing transaction found"; success_msg_writer() << "txid: " << txid; success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp); success_msg_writer() << "Amount: " << print_money(amount - pd.m_change - fee); success_msg_writer() << "Payment ID: " << payment_id; success_msg_writer() << "Change: " << print_money(pd.m_change); success_msg_writer() << "Fee: " << print_money(fee); success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid); return true; } } fail_msg_writer() << tr("Transaction ID not found"); return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::process_command(const std::vector<std::string> &args) { return m_cmd_binder.process_command_vec(args); } //---------------------------------------------------------------------------------------------------- void simple_wallet::interrupt() { if (m_in_manual_refresh.load(std::memory_order_relaxed)) { m_wallet->stop(); } else { stop(); } } //---------------------------------------------------------------------------------------------------- void simple_wallet::commit_or_save(std::vector<tools::wallet2::pending_tx>& ptx_vector, bool do_not_relay) { size_t i = 0; while (!ptx_vector.empty()) { auto & ptx = ptx_vector.back(); const crypto::hash txid = get_transaction_hash(ptx.tx); if (do_not_relay) { cryptonote::blobdata blob; tx_to_blob(ptx.tx, blob); const std::string blob_hex = epee::string_tools::buff_to_hex_nodelimer(blob); const std::string filename = "raw_coinevo_tx" + (ptx_vector.size() == 1 ? "" : ("_" + std::to_string(i++))); if (m_wallet->save_to_file(filename, blob_hex, true)) success_msg_writer(true) << tr("Transaction successfully saved to ") << filename << tr(", txid ") << txid; else fail_msg_writer() << tr("Failed to save transaction to ") << filename << tr(", txid ") << txid; } else { m_wallet->commit_tx(ptx); success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << txid << ENDL << tr("You can check its status by using the `show_transfers` command."); } // if no exception, remove element from vector ptx_vector.pop_back(); } } //---------------------------------------------------------------------------------------------------- int main(int argc, char* argv[]) { TRY_ENTRY(); #ifdef WIN32 // Activate UTF-8 support for Boost filesystem classes on Windows std::locale::global(boost::locale::generator().generate("")); boost::filesystem::path::imbue(std::locale()); #endif setlocale(LC_CTYPE, ""); po::options_description desc_params(wallet_args::tr("Wallet options")); tools::wallet2::init_options(desc_params); command_line::add_arg(desc_params, arg_wallet_file); command_line::add_arg(desc_params, arg_generate_new_wallet); command_line::add_arg(desc_params, arg_generate_from_device); command_line::add_arg(desc_params, arg_generate_from_view_key); command_line::add_arg(desc_params, arg_generate_from_spend_key); command_line::add_arg(desc_params, arg_generate_from_keys); command_line::add_arg(desc_params, arg_generate_from_multisig_keys); command_line::add_arg(desc_params, arg_generate_from_json); command_line::add_arg(desc_params, arg_mnemonic_language); command_line::add_arg(desc_params, arg_command); command_line::add_arg(desc_params, arg_restore_deterministic_wallet ); command_line::add_arg(desc_params, arg_restore_from_seed ); command_line::add_arg(desc_params, arg_restore_multisig_wallet ); command_line::add_arg(desc_params, arg_non_deterministic ); command_line::add_arg(desc_params, arg_electrum_seed ); command_line::add_arg(desc_params, arg_allow_mismatched_daemon_version); command_line::add_arg(desc_params, arg_restore_height); command_line::add_arg(desc_params, arg_restore_date); command_line::add_arg(desc_params, arg_do_not_relay); command_line::add_arg(desc_params, arg_create_address_file); command_line::add_arg(desc_params, arg_subaddress_lookahead); command_line::add_arg(desc_params, arg_use_english_language_names); command_line::add_arg(desc_params, arg_rpc_client_secret_key); po::positional_options_description positional_options; positional_options.add(arg_command.name, -1); boost::optional<po::variables_map> vm; bool should_terminate = false; std::tie(vm, should_terminate) = wallet_args::main( argc, argv, "coinevo-wallet-cli [--wallet-file=<filename>|--generate-new-wallet=<filename>] [<COMMAND>]", sw::tr("This is the command line coinevo wallet. It needs to connect to a coinevo\ndaemon to work correctly.\nWARNING: Do not reuse your Coinevo keys on another fork, UNLESS this fork has key reuse mitigations built in. Doing so will harm your privacy."), desc_params, positional_options, [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; }, "coinevo-wallet-cli.log" ); if (!vm) { return 1; } if (should_terminate) { return 0; } cryptonote::simple_wallet w; const bool r = w.init(*vm); CHECK_AND_ASSERT_MES(r, 1, sw::tr("Failed to initialize wallet")); std::vector<std::string> command = command_line::get_arg(*vm, arg_command); if (!command.empty()) { if (!w.process_command(command)) fail_msg_writer() << sw::tr("Unknown command: ") << command.front(); w.stop(); w.deinit(); } else { tools::signal_handler::install([&w](int type) { if (tools::password_container::is_prompting.load()) { // must be prompting for password so return and let the signal stop prompt return; } #ifdef WIN32 if (type == CTRL_C_EVENT) #else if (type == SIGINT) #endif { // if we're pressing ^C when refreshing, just stop refreshing w.interrupt(); } else { w.stop(); } }); w.run(); w.deinit(); } return 0; CATCH_ENTRY_L0("main", 1); } // MMS --------------------------------------------------------------------------------------------------- // Access to the message store, or more exactly to the list of the messages that can be changed // by the idle thread, is guarded by the same mutex-based mechanism as access to the wallet // as a whole and thus e.g. uses the "LOCK_IDLE_SCOPE" macro. This is a little over-cautious, but // simple and safe. Care has to be taken however where MMS methods call other simplewallet methods // that use "LOCK_IDLE_SCOPE" as this cannot be nested! // Methods for commands like "export_multisig_info" usually read data from file(s) or write data // to files. The MMS calls now those methods as well, to produce data for messages and to process data // from messages. As it would be quite inconvenient for the MMS to write data for such methods to files // first or get data out of result files after the call, those methods detect a call from the MMS and // expect data as arguments instead of files and give back data by calling 'process_wallet_created_data'. bool simple_wallet::user_confirms(const std::string &question) { std::string answer = input_line(question + tr(" (Y/Yes/N/No): ")); return !std::cin.eof() && command_line::is_yes(answer); } bool simple_wallet::get_number_from_arg(const std::string &arg, uint32_t &number, const uint32_t lower_bound, const uint32_t upper_bound) { bool valid = false; try { number = boost::lexical_cast<uint32_t>(arg); valid = (number >= lower_bound) && (number <= upper_bound); } catch(const boost::bad_lexical_cast &) { } return valid; } bool simple_wallet::choose_mms_processing(const std::vector<mms::processing_data> &data_list, uint32_t &choice) { size_t choices = data_list.size(); if (choices == 1) { choice = 0; return true; } mms::message_store& ms = m_wallet->get_message_store(); message_writer() << tr("Choose processing:"); std::string text; for (size_t i = 0; i < choices; ++i) { const mms::processing_data &data = data_list[i]; text = std::to_string(i+1) + ": "; switch (data.processing) { case mms::message_processing::sign_tx: text += tr("Sign tx"); break; case mms::message_processing::send_tx: { mms::message m; ms.get_message_by_id(data.message_ids[0], m); if (m.type == mms::message_type::fully_signed_tx) { text += tr("Send the tx for submission to "); } else { text += tr("Send the tx for signing to "); } mms::authorized_signer signer = ms.get_signer(data.receiving_signer_index); text += ms.signer_to_string(signer, 50); break; } case mms::message_processing::submit_tx: text += tr("Submit tx"); break; default: text += tr("unknown"); break; } message_writer() << text; } std::string line = input_line(tr("Choice: ")); if (std::cin.eof() || line.empty()) { return false; } bool choice_ok = get_number_from_arg(line, choice, 1, choices); if (choice_ok) { choice--; } else { fail_msg_writer() << tr("Wrong choice"); } return choice_ok; } void simple_wallet::list_mms_messages(const std::vector<mms::message> &messages) { message_writer() << boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") % tr("Id") % tr("I/O") % tr("Authorized Signer") % tr("Message Type") % tr("Height") % tr("R") % tr("Message State") % tr("Since"); mms::message_store& ms = m_wallet->get_message_store(); uint64_t now = (uint64_t)time(NULL); for (size_t i = 0; i < messages.size(); ++i) { const mms::message &m = messages[i]; const mms::authorized_signer &signer = ms.get_signer(m.signer_index); bool highlight = (m.state == mms::message_state::ready_to_send) || (m.state == mms::message_state::waiting); message_writer(m.direction == mms::message_direction::out ? console_color_green : console_color_magenta, highlight) << boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") % m.id % ms.message_direction_to_string(m.direction) % ms.signer_to_string(signer, 30) % ms.message_type_to_string(m.type) % m.wallet_height % m.round % ms.message_state_to_string(m.state) % (tools::get_human_readable_timestamp(m.modified) + ", " + get_human_readable_timespan(std::chrono::seconds(now - m.modified)) + tr(" ago")); } } void simple_wallet::list_signers(const std::vector<mms::authorized_signer> &signers) { message_writer() << boost::format("%2s %-20s %-s") % tr("#") % tr("Label") % tr("Transport Address"); message_writer() << boost::format("%2s %-20s %-s") % "" % tr("Auto-Config Token") % tr("Coinevo Address"); for (size_t i = 0; i < signers.size(); ++i) { const mms::authorized_signer &signer = signers[i]; std::string label = signer.label.empty() ? tr("<not set>") : signer.label; std::string monero_address; if (signer.monero_address_known) { monero_address = get_account_address_as_str(m_wallet->nettype(), false, signer.monero_address); } else { monero_address = tr("<not set>"); } std::string transport_address = signer.transport_address.empty() ? tr("<not set>") : signer.transport_address; message_writer() << boost::format("%2s %-20s %-s") % (i + 1) % label % transport_address; message_writer() << boost::format("%2s %-20s %-s") % "" % signer.auto_config_token % monero_address; message_writer() << ""; } } void simple_wallet::add_signer_config_messages() { mms::message_store& ms = m_wallet->get_message_store(); std::string signer_config; ms.get_signer_config(signer_config); const std::vector<mms::authorized_signer> signers = ms.get_all_signers(); mms::multisig_wallet_state state = get_multisig_wallet_state(); uint32_t num_authorized_signers = ms.get_num_authorized_signers(); for (uint32_t i = 1 /* without me */; i < num_authorized_signers; ++i) { ms.add_message(state, i, mms::message_type::signer_config, mms::message_direction::out, signer_config); } } void simple_wallet::show_message(const mms::message &m) { mms::message_store& ms = m_wallet->get_message_store(); const mms::authorized_signer &signer = ms.get_signer(m.signer_index); bool display_content; std::string sanitized_text; switch (m.type) { case mms::message_type::key_set: case mms::message_type::additional_key_set: case mms::message_type::note: display_content = true; ms.get_sanitized_message_text(m, sanitized_text); break; default: display_content = false; } uint64_t now = (uint64_t)time(NULL); message_writer() << ""; message_writer() << tr("Message ") << m.id; message_writer() << tr("In/out: ") << ms.message_direction_to_string(m.direction); message_writer() << tr("Type: ") << ms.message_type_to_string(m.type); message_writer() << tr("State: ") << boost::format(tr("%s since %s, %s ago")) % ms.message_state_to_string(m.state) % tools::get_human_readable_timestamp(m.modified) % get_human_readable_timespan(std::chrono::seconds(now - m.modified)); if (m.sent == 0) { message_writer() << tr("Sent: Never"); } else { message_writer() << boost::format(tr("Sent: %s, %s ago")) % tools::get_human_readable_timestamp(m.sent) % get_human_readable_timespan(std::chrono::seconds(now - m.sent)); } message_writer() << tr("Authorized signer: ") << ms.signer_to_string(signer, 100); message_writer() << tr("Content size: ") << m.content.length() << tr(" bytes"); message_writer() << tr("Content: ") << (display_content ? sanitized_text : tr("(binary data)")); if (m.type == mms::message_type::note) { // Showing a note and read its text is "processing" it: Set the state accordingly // which will also delete it from Bitmessage as a side effect // (Without this little "twist" it would never change the state, and never get deleted) ms.set_message_processed_or_sent(m.id); } } void simple_wallet::ask_send_all_ready_messages() { mms::message_store& ms = m_wallet->get_message_store(); std::vector<mms::message> ready_messages; const std::vector<mms::message> &messages = ms.get_all_messages(); for (size_t i = 0; i < messages.size(); ++i) { const mms::message &m = messages[i]; if (m.state == mms::message_state::ready_to_send) { ready_messages.push_back(m); } } if (ready_messages.size() != 0) { list_mms_messages(ready_messages); bool send = ms.get_auto_send(); if (!send) { send = user_confirms(tr("Send these messages now?")); } if (send) { mms::multisig_wallet_state state = get_multisig_wallet_state(); for (size_t i = 0; i < ready_messages.size(); ++i) { ms.send_message(state, ready_messages[i].id); ms.set_message_processed_or_sent(ready_messages[i].id); } success_msg_writer() << tr("Queued for sending."); } } } bool simple_wallet::get_message_from_arg(const std::string &arg, mms::message &m) { mms::message_store& ms = m_wallet->get_message_store(); bool valid_id = false; uint32_t id; try { id = (uint32_t)boost::lexical_cast<uint32_t>(arg); valid_id = ms.get_message_by_id(id, m); } catch (const boost::bad_lexical_cast &) { } if (!valid_id) { fail_msg_writer() << tr("Invalid message id"); } return valid_id; } void simple_wallet::mms_init(const std::vector<std::string> &args) { if (args.size() != 3) { fail_msg_writer() << tr("usage: mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>"); return; } mms::message_store& ms = m_wallet->get_message_store(); if (ms.get_active()) { if (!user_confirms(tr("The MMS is already initialized. Re-initialize by deleting all signer info and messages?"))) { return; } } uint32_t num_required_signers; uint32_t num_authorized_signers; const std::string &mn = args[0]; std::vector<std::string> numbers; boost::split(numbers, mn, boost::is_any_of("/")); bool mn_ok = (numbers.size() == 2) && get_number_from_arg(numbers[1], num_authorized_signers, 2, 100) && get_number_from_arg(numbers[0], num_required_signers, 2, num_authorized_signers); if (!mn_ok) { fail_msg_writer() << tr("Error in the number of required signers and/or authorized signers"); return; } LOCK_IDLE_SCOPE(); ms.init(get_multisig_wallet_state(), args[1], args[2], num_authorized_signers, num_required_signers); } void simple_wallet::mms_info(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); if (ms.get_active()) { message_writer() << boost::format("The MMS is active for %s/%s multisig.") % ms.get_num_required_signers() % ms.get_num_authorized_signers(); } else { message_writer() << tr("The MMS is not active."); } } void simple_wallet::mms_signer(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); const std::vector<mms::authorized_signer> &signers = ms.get_all_signers(); if (args.size() == 0) { // Without further parameters list all defined signers list_signers(signers); return; } uint32_t index; bool index_valid = get_number_from_arg(args[0], index, 1, ms.get_num_authorized_signers()); if (index_valid) { index--; } else { fail_msg_writer() << tr("Invalid signer number ") + args[0]; return; } if ((args.size() < 2) || (args.size() > 4)) { fail_msg_writer() << tr("mms signer [<number> <label> [<transport_address> [<coinevo_address>]]]"); return; } boost::optional<string> label = args[1]; boost::optional<string> transport_address; if (args.size() >= 3) { transport_address = args[2]; } boost::optional<cryptonote::account_public_address> monero_address; LOCK_IDLE_SCOPE(); mms::multisig_wallet_state state = get_multisig_wallet_state(); if (args.size() == 4) { cryptonote::address_parse_info info; bool ok = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[3], oa_prompter); if (!ok) { fail_msg_writer() << tr("Invalid Coinevo address"); return; } monero_address = info.address; const std::vector<mms::message> &messages = ms.get_all_messages(); if ((messages.size() > 0) || state.multisig) { fail_msg_writer() << tr("Wallet state does not allow changing Coinevo addresses anymore"); return; } } ms.set_signer(state, index, label, transport_address, monero_address); } void simple_wallet::mms_list(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); if (args.size() != 0) { fail_msg_writer() << tr("Usage: mms list"); return; } LOCK_IDLE_SCOPE(); const std::vector<mms::message> &messages = ms.get_all_messages(); list_mms_messages(messages); } void simple_wallet::mms_next(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); if ((args.size() > 1) || ((args.size() == 1) && (args[0] != "sync"))) { fail_msg_writer() << tr("Usage: mms next [sync]"); return; } bool avail = false; std::vector<mms::processing_data> data_list; bool force_sync = false; uint32_t choice = 0; { LOCK_IDLE_SCOPE(); if ((args.size() == 1) && (args[0] == "sync")) { // Force the MMS to process any waiting sync info although on its own it would just ignore // those messages because no need to process them can be seen force_sync = true; } string wait_reason; { avail = ms.get_processable_messages(get_multisig_wallet_state(), force_sync, data_list, wait_reason); } if (avail) { avail = choose_mms_processing(data_list, choice); } else if (!wait_reason.empty()) { message_writer() << tr("No next step: ") << wait_reason; } } if (avail) { mms::processing_data data = data_list[choice]; bool command_successful = false; switch(data.processing) { case mms::message_processing::prepare_multisig: message_writer() << tr("prepare_multisig"); command_successful = prepare_multisig_main(std::vector<std::string>(), true); break; case mms::message_processing::make_multisig: { message_writer() << tr("make_multisig"); size_t number_of_key_sets = data.message_ids.size(); std::vector<std::string> sig_args(number_of_key_sets + 1); sig_args[0] = std::to_string(ms.get_num_required_signers()); for (size_t i = 0; i < number_of_key_sets; ++i) { mms::message m = ms.get_message_by_id(data.message_ids[i]); sig_args[i+1] = m.content; } command_successful = make_multisig_main(sig_args, true); break; } case mms::message_processing::exchange_multisig_keys: { message_writer() << tr("exchange_multisig_keys"); size_t number_of_key_sets = data.message_ids.size(); // Other than "make_multisig" only the key sets as parameters, no num_required_signers std::vector<std::string> sig_args(number_of_key_sets); for (size_t i = 0; i < number_of_key_sets; ++i) { mms::message m = ms.get_message_by_id(data.message_ids[i]); sig_args[i] = m.content; } command_successful = exchange_multisig_keys_main(sig_args, true); break; } case mms::message_processing::create_sync_data: { message_writer() << tr("export_multisig_info"); std::vector<std::string> export_args; export_args.push_back("MMS"); // dummy filename command_successful = export_multisig_main(export_args, true); break; } case mms::message_processing::process_sync_data: { message_writer() << tr("import_multisig_info"); std::vector<std::string> import_args; for (size_t i = 0; i < data.message_ids.size(); ++i) { mms::message m = ms.get_message_by_id(data.message_ids[i]); import_args.push_back(m.content); } command_successful = import_multisig_main(import_args, true); break; } case mms::message_processing::sign_tx: { message_writer() << tr("sign_multisig"); std::vector<std::string> sign_args; mms::message m = ms.get_message_by_id(data.message_ids[0]); sign_args.push_back(m.content); command_successful = sign_multisig_main(sign_args, true); break; } case mms::message_processing::submit_tx: { message_writer() << tr("submit_multisig"); std::vector<std::string> submit_args; mms::message m = ms.get_message_by_id(data.message_ids[0]); submit_args.push_back(m.content); command_successful = submit_multisig_main(submit_args, true); break; } case mms::message_processing::send_tx: { message_writer() << tr("Send tx"); mms::message m = ms.get_message_by_id(data.message_ids[0]); LOCK_IDLE_SCOPE(); ms.add_message(get_multisig_wallet_state(), data.receiving_signer_index, m.type, mms::message_direction::out, m.content); command_successful = true; break; } case mms::message_processing::process_signer_config: { message_writer() << tr("Process signer config"); LOCK_IDLE_SCOPE(); mms::message m = ms.get_message_by_id(data.message_ids[0]); mms::authorized_signer me = ms.get_signer(0); mms::multisig_wallet_state state = get_multisig_wallet_state(); if (!me.auto_config_running) { // If no auto-config is running, the config sent may be unsolicited or problematic // so show what arrived and ask for confirmation before taking it in std::vector<mms::authorized_signer> signers; ms.unpack_signer_config(state, m.content, signers); list_signers(signers); if (!user_confirms(tr("Replace current signer config with the one displayed above?"))) { break; } } ms.process_signer_config(state, m.content); ms.stop_auto_config(); list_signers(ms.get_all_signers()); command_successful = true; break; } case mms::message_processing::process_auto_config_data: { message_writer() << tr("Process auto config data"); LOCK_IDLE_SCOPE(); for (size_t i = 0; i < data.message_ids.size(); ++i) { ms.process_auto_config_data_message(data.message_ids[i]); } ms.stop_auto_config(); list_signers(ms.get_all_signers()); add_signer_config_messages(); command_successful = true; break; } default: message_writer() << tr("Nothing ready to process"); break; } if (command_successful) { { LOCK_IDLE_SCOPE(); ms.set_messages_processed(data); ask_send_all_ready_messages(); } } } } void simple_wallet::mms_sync(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); if (args.size() != 0) { fail_msg_writer() << tr("Usage: mms sync"); return; } // Force the start of a new sync round, for exceptional cases where something went wrong // Can e.g. solve the problem "This signature was made with stale data" after trying to // create 2 transactions in a row somehow // Code is identical to the code for 'message_processing::create_sync_data' message_writer() << tr("export_multisig_info"); std::vector<std::string> export_args; export_args.push_back("MMS"); // dummy filename export_multisig_main(export_args, true); ask_send_all_ready_messages(); } void simple_wallet::mms_transfer(const std::vector<std::string> &args) { // It's too complicated to check any arguments here, just let 'transfer_main' do the whole job transfer_main(Transfer, args, true); } void simple_wallet::mms_delete(const std::vector<std::string> &args) { if (args.size() != 1) { fail_msg_writer() << tr("Usage: mms delete (<message_id> | all)"); return; } LOCK_IDLE_SCOPE(); mms::message_store& ms = m_wallet->get_message_store(); if (args[0] == "all") { if (user_confirms(tr("Delete all messages?"))) { ms.delete_all_messages(); } } else { mms::message m; bool valid_id = get_message_from_arg(args[0], m); if (valid_id) { // If only a single message and not all delete even if unsent / unprocessed ms.delete_message(m.id); } } } void simple_wallet::mms_send(const std::vector<std::string> &args) { if (args.size() == 0) { ask_send_all_ready_messages(); return; } else if (args.size() != 1) { fail_msg_writer() << tr("Usage: mms send [<message_id>]"); return; } LOCK_IDLE_SCOPE(); mms::message_store& ms = m_wallet->get_message_store(); mms::message m; bool valid_id = get_message_from_arg(args[0], m); if (valid_id) { ms.send_message(get_multisig_wallet_state(), m.id); } } void simple_wallet::mms_receive(const std::vector<std::string> &args) { if (args.size() != 0) { fail_msg_writer() << tr("Usage: mms receive"); return; } std::vector<mms::message> new_messages; LOCK_IDLE_SCOPE(); mms::message_store& ms = m_wallet->get_message_store(); bool avail = ms.check_for_messages(get_multisig_wallet_state(), new_messages); if (avail) { list_mms_messages(new_messages); } } void simple_wallet::mms_export(const std::vector<std::string> &args) { if (args.size() != 1) { fail_msg_writer() << tr("Usage: mms export <message_id>"); return; } LOCK_IDLE_SCOPE(); mms::message_store& ms = m_wallet->get_message_store(); mms::message m; bool valid_id = get_message_from_arg(args[0], m); if (valid_id) { const std::string filename = "mms_message_content"; if (m_wallet->save_to_file(filename, m.content)) { success_msg_writer() << tr("Message content saved to: ") << filename; } else { fail_msg_writer() << tr("Failed to to save message content"); } } } void simple_wallet::mms_note(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); if (args.size() == 0) { LOCK_IDLE_SCOPE(); const std::vector<mms::message> &messages = ms.get_all_messages(); for (size_t i = 0; i < messages.size(); ++i) { const mms::message &m = messages[i]; if ((m.type == mms::message_type::note) && (m.state == mms::message_state::waiting)) { show_message(m); } } return; } if (args.size() < 2) { fail_msg_writer() << tr("Usage: mms note [<label> <text>]"); return; } uint32_t signer_index; bool found = ms.get_signer_index_by_label(args[0], signer_index); if (!found) { fail_msg_writer() << tr("No signer found with label ") << args[0]; return; } std::string note = ""; for (size_t n = 1; n < args.size(); ++n) { if (n > 1) { note += " "; } note += args[n]; } LOCK_IDLE_SCOPE(); ms.add_message(get_multisig_wallet_state(), signer_index, mms::message_type::note, mms::message_direction::out, note); ask_send_all_ready_messages(); } void simple_wallet::mms_show(const std::vector<std::string> &args) { if (args.size() != 1) { fail_msg_writer() << tr("Usage: mms show <message_id>"); return; } LOCK_IDLE_SCOPE(); mms::message_store& ms = m_wallet->get_message_store(); mms::message m; bool valid_id = get_message_from_arg(args[0], m); if (valid_id) { show_message(m); } } void simple_wallet::mms_set(const std::vector<std::string> &args) { bool set = args.size() == 2; bool query = args.size() == 1; if (!set && !query) { fail_msg_writer() << tr("Usage: mms set <option_name> [<option_value>]"); return; } mms::message_store& ms = m_wallet->get_message_store(); LOCK_IDLE_SCOPE(); if (args[0] == "auto-send") { if (set) { bool result; bool ok = parse_bool(args[1], result); if (ok) { ms.set_auto_send(result); } else { fail_msg_writer() << tr("Wrong option value"); } } else { message_writer() << (ms.get_auto_send() ? tr("Auto-send is on") : tr("Auto-send is off")); } } else { fail_msg_writer() << tr("Unknown option"); } } void simple_wallet::mms_help(const std::vector<std::string> &args) { if (args.size() > 1) { fail_msg_writer() << tr("Usage: mms help [<subcommand>]"); return; } std::vector<std::string> help_args; help_args.push_back("mms"); if (args.size() == 1) { help_args.push_back(args[0]); } help(help_args); } void simple_wallet::mms_send_signer_config(const std::vector<std::string> &args) { if (args.size() != 0) { fail_msg_writer() << tr("Usage: mms send_signer_config"); return; } mms::message_store& ms = m_wallet->get_message_store(); if (!ms.signer_config_complete()) { fail_msg_writer() << tr("Signer config not yet complete"); return; } LOCK_IDLE_SCOPE(); add_signer_config_messages(); ask_send_all_ready_messages(); } void simple_wallet::mms_start_auto_config(const std::vector<std::string> &args) { mms::message_store& ms = m_wallet->get_message_store(); uint32_t other_signers = ms.get_num_authorized_signers() - 1; size_t args_size = args.size(); if ((args_size != 0) && (args_size != other_signers)) { fail_msg_writer() << tr("Usage: mms start_auto_config [<label> <label> ...]"); return; } if ((args_size == 0) && !ms.signer_labels_complete()) { fail_msg_writer() << tr("There are signers without a label set. Complete labels before auto-config or specify them as parameters here."); return; } mms::authorized_signer me = ms.get_signer(0); if (me.auto_config_running) { if (!user_confirms(tr("Auto-config is already running. Cancel and restart?"))) { return; } } LOCK_IDLE_SCOPE(); mms::multisig_wallet_state state = get_multisig_wallet_state(); if (args_size != 0) { // Set (or overwrite) all the labels except "me" from the arguments for (uint32_t i = 1; i < (other_signers + 1); ++i) { ms.set_signer(state, i, args[i - 1], boost::none, boost::none); } } ms.start_auto_config(state); // List the signers to show the generated auto-config tokens list_signers(ms.get_all_signers()); } void simple_wallet::mms_stop_auto_config(const std::vector<std::string> &args) { if (args.size() != 0) { fail_msg_writer() << tr("Usage: mms stop_auto_config"); return; } if (!user_confirms(tr("Delete any auto-config tokens and stop auto-config?"))) { return; } mms::message_store& ms = m_wallet->get_message_store(); LOCK_IDLE_SCOPE(); ms.stop_auto_config(); } void simple_wallet::mms_auto_config(const std::vector<std::string> &args) { if (args.size() != 1) { fail_msg_writer() << tr("Usage: mms auto_config <auto_config_token>"); return; } mms::message_store& ms = m_wallet->get_message_store(); std::string adjusted_token; if (!ms.check_auto_config_token(args[0], adjusted_token)) { fail_msg_writer() << tr("Invalid auto-config token"); return; } mms::authorized_signer me = ms.get_signer(0); if (me.auto_config_running) { if (!user_confirms(tr("Auto-config already running. Cancel and restart?"))) { return; } } LOCK_IDLE_SCOPE(); ms.add_auto_config_data_message(get_multisig_wallet_state(), adjusted_token); ask_send_all_ready_messages(); } bool simple_wallet::mms(const std::vector<std::string> &args) { try { m_wallet->get_multisig_wallet_state(); } catch(const std::exception &e) { fail_msg_writer() << tr("MMS not available in this wallet"); return true; } try { mms::message_store& ms = m_wallet->get_message_store(); if (args.size() == 0) { mms_info(args); return true; } const std::string &sub_command = args[0]; std::vector<std::string> mms_args = args; mms_args.erase(mms_args.begin()); if (sub_command == "init") { mms_init(mms_args); return true; } if (!ms.get_active()) { fail_msg_writer() << tr("The MMS is not active. Activate using the \"mms init\" command"); return true; } else if (sub_command == "info") { mms_info(mms_args); } else if (sub_command == "signer") { mms_signer(mms_args); } else if (sub_command == "list") { mms_list(mms_args); } else if (sub_command == "next") { mms_next(mms_args); } else if (sub_command == "sync") { mms_sync(mms_args); } else if (sub_command == "transfer") { mms_transfer(mms_args); } else if (sub_command == "delete") { mms_delete(mms_args); } else if (sub_command == "send") { mms_send(mms_args); } else if (sub_command == "receive") { mms_receive(mms_args); } else if (sub_command == "export") { mms_export(mms_args); } else if (sub_command == "note") { mms_note(mms_args); } else if (sub_command == "show") { mms_show(mms_args); } else if (sub_command == "set") { mms_set(mms_args); } else if (sub_command == "help") { mms_help(mms_args); } else if (sub_command == "send_signer_config") { mms_send_signer_config(mms_args); } else if (sub_command == "start_auto_config") { mms_start_auto_config(mms_args); } else if (sub_command == "stop_auto_config") { mms_stop_auto_config(mms_args); } else if (sub_command == "auto_config") { mms_auto_config(mms_args); } else { fail_msg_writer() << tr("Invalid MMS subcommand"); } } catch (const tools::error::no_connection_to_daemon &e) { fail_msg_writer() << tr("Error in MMS command: ") << e.what() << " " << e.request(); } catch (const std::exception &e) { fail_msg_writer() << tr("Error in MMS command: ") << e.what(); PRINT_USAGE(USAGE_MMS); return true; } return true; } // End MMS ------------------------------------------------------------------------------------------------
/** \file tb2system.hpp * \brief System dependent functions. * */ #ifndef TB2SYSTEM_HPP_ #define TB2SYSTEM_HPP_ #if __cplusplus > 199711L #define FINAL final #else #define FINAL #endif extern const char* PrintFormatProb; double cpuTime(); ///< \brief return CPU time in seconds with high resolution (microseconds) if available void timeOut(int sig); void timer(int t); ///< \brief set a timer (in seconds) void timerStop(); ///< \brief stop a timer #ifdef WIDE_STRING typedef wchar_t Char; typedef wstring String; #define Cout wcout #include <cwchar> #define Strcpy wcscpy // #define Strncpy wcsncpy // #define Strcat wcscat // #define Strncat wcsncat #define Strcmp wcscmp // #define Strncmp wcsncmp #define Strlen wcslen #else typedef char Char; typedef string String; #define Cout cout #define Strcpy strcpy #define Strncpy strncpy #define Strcat strcat #define Strncat strncat #define Strcmp strcmp #define Strncmp strncmp #define Strlen strlen #endif typedef long long Long; #ifndef LONGLONG_MAX #ifdef LINUX #ifdef LONG_LONG_MAX const Long LONGLONG_MAX = LONG_LONG_MAX; #else const Long LONGLONG_MAX = LLONG_MAX; #endif #endif #ifdef WINDOWS const Long LONGLONG_MAX = 0x7FFFFFFFFFFFFFFFLL; #endif #endif typedef long double Double; #ifdef LINUX inline void mysrand(int seed) { return srand48(seed); } inline int myrand() { return lrand48(); } inline Long myrandl() { return (Long)((Long)lrand48() /**LONGLONG_MAX*/); } inline double mydrand() { return drand48(); } #endif #ifdef WINDOWS inline void mysrand(int seed) { return srand(seed); } inline int myrand() { return rand(); } inline Long myrandl() { return (Long)((Long)rand() /**LONGLONG_MAX*/); } inline double mydrand() { return drand(); } //If compiler warning, replace by (double(rand()) / RAND_MAX); #endif #ifdef DOUBLE_PROB #ifdef LINUX inline double Pow(double x, double y) { return pow(x, y); } inline double Exp10(double x) { return exp10(x); } inline double Exp(double x) { return exp(x); } inline double Log10(double x) { return log10(x); } inline double Expm1(double x) { return expm1(x); } inline double Log(double x) { return log(x); } inline double Log1p(double x) { return log1p(x); } #endif #ifdef WINDOWS inline double Pow(double x, double y) { return pow(x, y); } inline double Exp10(double x) { return pow(10., x); } inline double Exp(double x) { return exp(x); } inline double Log10(double x) { return log(x) / log(10.); } inline double Log(double x) { return log(x); } inline double Log1p(double x) { return log(1. + x); } inline double Expm1(double x) { return exp(x) - 1.; } #endif #endif #ifdef LONGDOUBLE_PROB #ifdef LINUX inline Double Pow(Double x, Double y) { return powl(x, y); } inline Double Exp10(Double x) { return powl(10.l, (Double)x); } inline Double Exp(Double x) { return expl(x); } inline Double Log10(Double x) { return log10l(x); } inline Double Expm1(Double x) { return expm1l(x); } inline Double Log(Double x) { return logl(x); } inline Double Log1p(Double x) { return log1pl(x); } #endif #ifdef WINDOWS inline Double Pow(Double x, Double y) { return pow(x, y); } inline Double Exp10(Double x) { return pow(10., x); } inline Double Log10(Double x) { return log(x) / log(10.); } inline Double Log(Double x) { return log(x); } inline Double Log1p(Double x) { return log(1. + x); } inline Double Expm1(Double x) { return exp(x) - 1.; } #endif #endif #ifdef INT_COST inline double to_double(const int cost) { return (double)cost; } inline int ceil(const int e) { return e; } inline int floor(const int e) { return e; } inline int randomCost(int min, int max) { return min + (myrand() % (max - min + 1)); } inline int string2Cost(const char* ptr) { return atoi(ptr); } //cost= 0 log2= -1 //cost= 1 log2= 0 //cost= 2 log2= 1 //cost= 3 log2= 1 //cost= 4 log2= 2 //cost= 5 log2= 2 //cost= 6 log2= 2 //cost= 7 log2= 2 //cost= 8 log2= 3 //cost= 9 log2= 3 //cost= 10 log2= 3 //cost= 11 log2= 3 //cost= 12 log2= 3 //cost= 13 log2= 3 //cost= 14 log2= 3 //cost= 15 log2= 3 //cost= 16 log2= 4 // This only works for a 32bits machine // and compiler g++ version < 4.0 /* inline int cost2log2(int v) { float x; if (v==0) return -1; x=(float) v; return (*(int*)&x >> 23) - 127; } */ inline int cost2log2(int x) { if (x <= 0) return -1; int l2 = 0; x >>= 1; for (; x != 0; x >>= 1) { ++l2; } return (l2); } inline int cost2log2glb(int x) { return cost2log2(x); } inline int cost2log2gub(int x) { return cost2log2(x); } #endif #ifdef LONGLONG_COST inline double to_double(const Long cost) { return (double)cost; } inline Long ceil(const Long e) { return e; } inline Long floor(const Long e) { return e; } inline Long randomCost(Long min, Long max) { return min + (myrandl() % (max - min + 1)); } #ifdef LINUX inline Long string2Cost(const char* ptr) { return atoll(ptr); } #endif #ifdef WINDOWS inline Long string2Cost(const char* ptr) { return atol(ptr); } #endif inline int cost2log2(Long x) { if (x <= 0) return -1; int l2 = 0; x >>= 1; for (; x != 0; x >>= 1) { ++l2; } return (l2); } inline int cost2log2glb(Long x) { return cost2log2(x); } inline int cost2log2gub(Long x) { return cost2log2(x); } #endif //luby(0)= N/A //luby(1)= 1 //luby(2)= 1 //luby(3)= 2 //luby(4)= 1 //luby(5)= 1 //luby(6)= 2 //luby(7)= 4 //luby(8)= 1 //luby(9)= 1 //luby(10)= 2 //luby(11)= 1 //luby(12)= 1 //luby(13)= 2 //luby(14)= 4 //luby(15)= 8 //luby(16)= 1 inline Long luby(Long r) { int j = cost2log2(r + 1); if (r + 1 == (1L << j)) return (1L << (j - 1)); else return luby(r - (1L << j) + 1); } // function mkdir #ifdef LINUX #include <sys/stat.h> #include <signal.h> #endif #ifdef WIN32 #include <direct.h> // for WINDOWS? #endif #ifndef SIZE_MAX #define SIZE_MAX ((size_t)-1) #endif #endif /* TB2SYSTEM_HPP_ */ /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 4 */ /* indent-tabs-mode: nil */ /* c-default-style: "k&r" */ /* End: */
/* Copyright 2016 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h" #include <limits> #include <map> #include <unordered_map> #include "grpcpp/create_channel.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace { string MakeAddress(const string& job, int task) { return strings::StrCat("/job:", job, "/replica:0/task:", task); } // Allows the host to be a raw IP (either v4 or v6). Status ValidateHostPortPair(const string& host_port) { string bns_prefix = "/bns/"; if (host_port.substr(0, bns_prefix.length()) == bns_prefix) { return Status::OK(); } uint32 port; auto colon_index = host_port.find_last_of(':'); if (!strings::safe_strtou32(host_port.substr(colon_index + 1), &port) || host_port.substr(0, colon_index).find("/") != string::npos) { return errors::InvalidArgument("Could not interpret \"", host_port, "\" as a host-port pair."); } return Status::OK(); } } // namespace ::grpc::ChannelArguments GetChannelArguments(const RPCOptions* rpc_options) { // TODO(mrry): Implement secure channels. ::grpc::ChannelArguments args; args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, std::numeric_limits<int32>::max()); // NOTE(mrry): Some versions of gRPC use a 20-second minimum backoff // on connection failure, which makes our tests time out. args.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS, 1000); if (rpc_options != nullptr) { if (rpc_options->compression_algorithm() == "deflate") { args.SetCompressionAlgorithm(GRPC_COMPRESS_DEFLATE); args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, rpc_options->compression_level()); VLOG(5) << "Setting GRPC compression : algo='" << rpc_options->compression_algorithm() << "' level=" << rpc_options->compression_level(); } else if (rpc_options->compression_algorithm() == "gzip") { args.SetCompressionAlgorithm(GRPC_COMPRESS_GZIP); args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, rpc_options->compression_level()); VLOG(5) << "Setting GRPC compression : algo='" << rpc_options->compression_algorithm() << "' level=" << rpc_options->compression_level(); } else if (!rpc_options->compression_algorithm().empty()) { LOG(ERROR) << "Invalid compression algorithm: " << rpc_options->compression_algorithm(); } if (rpc_options->disable_session_connection_sharing()) { VLOG(5) << "Disabling TCP connection sharing"; args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true); } } return args; } Status NewHostPortGrpcChannel(const string& target, const RPCOptions* rpc_options, SharedGrpcChannelPtr* channel_pointer) { // Minimally ensure that the target is valid TF_RETURN_IF_ERROR(ValidateHostPortPair(target)); ::grpc::ChannelArguments args = GetChannelArguments(rpc_options); *channel_pointer = ::grpc::CreateCustomChannel( "dns:///" + target, ::grpc::InsecureChannelCredentials(), args); return Status::OK(); } ChannelCreationFunction ConvertToChannelCreationFunction( const std::function<Status(string, const RPCOptions*, SharedGrpcChannelPtr*)>& new_channel_func_ptr) { return [new_channel_func_ptr](const string& target) -> SharedGrpcChannelPtr { SharedGrpcChannelPtr channel_ptr; if (new_channel_func_ptr(target, /*rpc_options=*/nullptr, &channel_ptr) .ok()) { return channel_ptr; } else { return nullptr; } }; } Status GrpcChannelSpec::AddHostPortsJob(const string& job_id, const std::vector<string>& host_ports) { std::map<int, string> host_ports_map; for (size_t i = 0; i < host_ports.size(); ++i) { host_ports_map[i] = host_ports[i]; } return AddHostPortsJob(job_id, host_ports_map); } Status GrpcChannelSpec::AddHostPortsJob( const string& job_id, const std::map<int, string>& host_ports) { if (!job_ids_.insert(job_id).second) { return errors::InvalidArgument( "Duplicate job ID in cluster specification: ", job_id); } for (const auto& id_host_port : host_ports) { TF_RETURN_IF_ERROR(ValidateHostPortPair(id_host_port.second)); } host_ports_jobs_.emplace_back(job_id, host_ports); return Status::OK(); } namespace { // GrpcChannelCache that caches results to FindWorkerChannel() calls. class CachingGrpcChannelCache : public GrpcChannelCache { public: CachingGrpcChannelCache() {} ~CachingGrpcChannelCache() override {} SharedGrpcChannelPtr FindWorkerChannel(const string& target) override { SharedGrpcChannelPtr ch = nullptr; { mutex_lock l(mu_); // could use reader lock ch = gtl::FindPtrOrNull(channels_, target); if (ch) { return ch; } } ch = FindChannelOnce(target); if (ch) { mutex_lock l(mu_); channels_.insert({target, ch}); } return ch; } protected: // Find the ClientChannel for "target". Only called when no channel was // found in the channels_ cache for "target". A non nullptr result will be // cached in channels_. virtual SharedGrpcChannelPtr FindChannelOnce(const string& target) = 0; private: // TODO(zhifengc): Eviction when the map becomes too big. mutex mu_; std::unordered_map<string, SharedGrpcChannelPtr> channels_ GUARDED_BY(mu_); }; // A ChannelCache that is the union of multiple ChannelCaches. // Takes ownership of the caches passed to the constructor. class MultiGrpcChannelCache : public CachingGrpcChannelCache { public: explicit MultiGrpcChannelCache(const std::vector<GrpcChannelCache*>& caches) : CachingGrpcChannelCache(), caches_(caches) {} ~MultiGrpcChannelCache() override { for (GrpcChannelCache* cache : caches_) { delete cache; } } void ListWorkers(std::vector<string>* workers) override { for (GrpcChannelCache* cache : caches_) { cache->ListWorkers(workers); } } void ListWorkersInJob(const string& job_name, std::vector<string>* workers) override { for (GrpcChannelCache* cache : caches_) { cache->ListWorkersInJob(job_name, workers); } } string TranslateTask(const string& target) override { mutex_lock l(mu_); // could use reader lock GrpcChannelCache* cache = gtl::FindPtrOrNull(target_caches_, target); if (cache == nullptr) { for (GrpcChannelCache* c : caches_) { string r = c->TranslateTask(target); if (!r.empty()) { target_caches_.insert({target, c}); cache = c; break; } } } CHECK(cache) << "Could not find GrpcChannelCache holding channel for " << target; return cache->TranslateTask(target); } protected: SharedGrpcChannelPtr FindChannelOnce(const string& target) override { for (GrpcChannelCache* cache : caches_) { SharedGrpcChannelPtr ch(cache->FindWorkerChannel(target)); if (ch) { mutex_lock l(mu_); target_caches_.insert({target, cache}); return ch; } } return nullptr; } private: // List of channels used by this MultiGrpcChannelCache. const std::vector<GrpcChannelCache*> caches_; mutex mu_; // Cache of channels keyed by the target they are handling. // The same GrpcChannelCache can appear multiple times in the cache. std::unordered_map<string, GrpcChannelCache*> target_caches_ GUARDED_BY(mu_); }; class SparseGrpcChannelCache : public CachingGrpcChannelCache { public: SparseGrpcChannelCache(const string& job_id, const std::map<int, string>& host_ports, ChannelCreationFunction channel_func) : job_id_(job_id), host_ports_(host_ports), channel_func_(std::move(channel_func)) { LOG(INFO) << "Initialize GrpcChannelCache for job " << ToString(); } ~SparseGrpcChannelCache() override {} void ListWorkers(std::vector<string>* workers) override { workers->reserve(workers->size() + host_ports_.size()); for (const auto& id_host_port : host_ports_) { workers->emplace_back(MakeAddress(job_id_, id_host_port.first)); } } void ListWorkersInJob(const string& job_name, std::vector<string>* workers) override { if (job_name == job_id_) { ListWorkers(workers); } } string TranslateTask(const string& target) override { DeviceNameUtils::ParsedName parsed; if (!DeviceNameUtils::ParseFullName(target, &parsed)) { LOG(WARNING) << "Invalid target: " << target; return ""; } if (!parsed.has_job || parsed.job != job_id_) { return ""; } if (!parsed.has_replica || parsed.replica != 0) { LOG(WARNING) << "Replica ID must be 0 in target: " << target; return ""; } int32 task = parsed.has_task ? parsed.task : -1; auto iter = host_ports_.find(task); if (iter == host_ports_.end()) { LOG(WARNING) << "Task " << task << " was not defined in sparse job " << job_id_ << ": " << target; return ""; } return iter->second; } protected: SharedGrpcChannelPtr FindChannelOnce(const string& target) override { const string host_port = TranslateTask(target); if (host_port.empty()) { return nullptr; } return channel_func_(host_port); } private: string ToString() { std::vector<string> task_strings; task_strings.reserve(host_ports_.size()); for (const auto& id_host_port : host_ports_) { task_strings.emplace_back( strings::StrCat(id_host_port.first, " -> ", id_host_port.second)); } return strings::StrCat(job_id_, " -> {", absl::StrJoin(task_strings, ", "), "}"); } const string job_id_; const std::map<int, string> host_ports_; const ChannelCreationFunction channel_func_; TF_DISALLOW_COPY_AND_ASSIGN(SparseGrpcChannelCache); }; } // namespace GrpcChannelCache* NewGrpcChannelCache(const GrpcChannelSpec& spec, ChannelCreationFunction channel_func) { const int num_jobs = spec.host_ports_jobs().size(); if (!num_jobs) { LOG(ERROR) << "Empty channel spec."; return nullptr; } std::vector<GrpcChannelCache*> caches; caches.reserve(num_jobs); for (auto& job : spec.host_ports_jobs()) { caches.push_back( new SparseGrpcChannelCache(job.job_id, job.host_ports, channel_func)); } return caches.size() == 1 ? caches[0] : new MultiGrpcChannelCache(caches); } } // end namespace tensorflow
/* ------------------------------------------------------------------------------- Copyright (c) 2009-2010 Nico de Poel 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 "Common.h" #include "MD3Model.h" MD3Model::MD3Model(): frames(NULL), tags(NULL), meshes(NULL) { } MD3Model::~MD3Model() { free(); } bool MD3Model::load( const string &filename ) { FILE *f; if ( !( f = fopen( filename.c_str(), "rb" ) ) ) { return false; } fread( &header, sizeof( MD3Header ), 1, f ); if ( header.magic[0] != 'I' || header.magic[1] != 'D' || header.magic[2] != 'P' || header.magic[3] != '3' || header.version != 15 ) { fclose( f ); return false; } frames = new MD3Frame[ header.numFrames ]; tags = new MD3Tag[ header.numTags * header.numFrames ]; meshes = new MD3Mesh[ header.numMeshes ]; fseek( f, header.offsetFrames, SEEK_SET ); fread( frames, sizeof( MD3Frame ), header.numFrames, f ); fseek( f, header.offsetTags, SEEK_SET ); fread( tags, sizeof( MD3Tag ), header.numTags * header.numFrames, f ); int offset = header.offsetMeshes; for ( int i = 0; i < header.numMeshes; i++ ) { MD3Mesh &mesh = meshes[i]; fseek( f, offset, SEEK_SET ); fread( &mesh.header, sizeof( MD3MeshHeader ), 1, f ); mesh.shaders = new MD3Shader[ mesh.header.numShaders ]; mesh.triangles = new MD3Triangle[ mesh.header.numTriangles ]; mesh.texCoords = new MD3TexCoord[ mesh.header.numVertices ]; mesh.vertices = new MD3Vertex[ mesh.header.numFrames * mesh.header.numVertices ]; fseek( f, offset + mesh.header.offsetShaders, SEEK_SET ); fread( mesh.shaders, sizeof( MD3Shader ), mesh.header.numShaders, f ); fseek( f, offset + mesh.header.offsetTriangles, SEEK_SET ); fread( mesh.triangles, sizeof( MD3Triangle ), mesh.header.numTriangles, f ); fseek( f, offset + mesh.header.offsetTexCoords, SEEK_SET ); fread( mesh.texCoords, sizeof( MD3TexCoord ), mesh.header.numVertices, f ); fseek( f, offset + mesh.header.offsetVertices, SEEK_SET ); fread( mesh.vertices, sizeof( MD3Vertex ), mesh.header.numFrames * mesh.header.numVertices, f ); offset += mesh.header.length; } printf( "MD3Model::load() - Loaded %i frames, %i meshes\n", header.numFrames, header.numMeshes ); fclose( f ); return true; } void MD3Model::free() { if ( frames ) { delete[] frames; frames = NULL; } if ( tags ) { delete[] tags; tags = NULL; } if ( meshes ) { for ( int i = 0; i < header.numMeshes; i++ ) { delete[] meshes[i].shaders; delete[] meshes[i].triangles; delete[] meshes[i].texCoords; delete[] meshes[i].vertices; } delete[] meshes; meshes = NULL; } } void MD3Model::printInfo() const { cout << "MD3 file info" << endl; for ( int i = 0; i < header.numFrames; i++ ) { cout << "Frame " << i << " = " << frames[i].name << endl; } cout << header.numFrames << " frames total" << endl; for ( int i = 0; i < header.numTags; i++ ) { cout << "Tag " << i << " = " << tags[i].name << endl; } cout << header.numTags << " tags total" << endl; for ( int i = 0; i < header.numMeshes; i++ ) { cout << "Mesh " << i << " = " << meshes[i].header.name << endl; for ( int j = 0; j < meshes[i].header.numShaders; j++ ) { cout << "Mesh " << i << " shader " << j << " = " << meshes[i].shaders[j].name << endl; } cout << "Mesh " << i << " has " << meshes[i].header.numShaders << " shaders total" << endl; } cout << header.numMeshes << " meshes total" << endl; }
// Copyright (c) 2014-2018, The Monero Project // // 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 its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <cstring> #include <cstdint> #include <cstdio> #include <iostream> #include <vector> #include <boost/foreach.hpp> #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_basic_impl.h" #include "serialization/serialization.h" #include "serialization/binary_archive.h" #include "serialization/json_archive.h" #include "serialization/debug_archive.h" #include "serialization/variant.h" #include "serialization/vector.h" #include "serialization/binary_utils.h" #include "gtest/gtest.h" using namespace std; TEST(varint, equal) { for (uint64_t idx = 0; idx < 65537; ++idx) { char buf[12]; char *bufptr = buf; tools::write_varint(bufptr, idx); uint64_t bytes = bufptr - buf; ASSERT_TRUE (bytes > 0 && bytes <= sizeof(buf)); uint64_t idx2; bufptr = buf; std::string s(buf, bytes); int read = tools::read_varint(s.begin(), s.end(), idx2); ASSERT_EQ (read, bytes); ASSERT_TRUE(idx2 == idx); } }
// 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 <stddef.h> #include <stdint.h> #include <map> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/containers/queue.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/location.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "components/services/filesystem/public/interfaces/types.mojom.h" #include "storage/browser/fileapi/copy_or_move_file_validator.h" #include "storage/browser/fileapi/copy_or_move_operation_delegate.h" #include "storage/browser/fileapi/file_stream_reader.h" #include "storage/browser/fileapi/file_stream_writer.h" #include "storage/browser/fileapi/file_system_backend.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation.h" #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/quota/quota_manager.h" #include "storage/browser/test/async_file_test_helper.h" #include "storage/browser/test/fileapi_test_file_set.h" #include "storage/browser/test/mock_quota_manager.h" #include "storage/browser/test/mock_quota_manager_proxy.h" #include "storage/browser/test/test_file_system_backend.h" #include "storage/browser/test/test_file_system_context.h" #include "storage/common/fileapi/file_system_mount_option.h" #include "storage/common/fileapi/file_system_util.h" #include "testing/gtest/include/gtest/gtest.h" using content::AsyncFileTestHelper; using storage::CopyOrMoveOperationDelegate; using storage::FileStreamWriter; using storage::FileSystemOperation; using storage::FileSystemURL; namespace content { using FileEntryList = storage::FileSystemOperation::FileEntryList; namespace { void ExpectOk(const GURL& origin_url, const std::string& name, base::File::Error error) { ASSERT_EQ(base::File::FILE_OK, error); } class TestValidatorFactory : public storage::CopyOrMoveFileValidatorFactory { public: // A factory that creates validators that accept everything or nothing. TestValidatorFactory() = default; ~TestValidatorFactory() override = default; storage::CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator( const FileSystemURL& /*src_url*/, const base::FilePath& /*platform_path*/) override { // Move arg management to TestValidator? return new TestValidator(true, true, std::string("2")); } private: class TestValidator : public storage::CopyOrMoveFileValidator { public: explicit TestValidator(bool pre_copy_valid, bool post_copy_valid, const std::string& reject_string) : result_(pre_copy_valid ? base::File::FILE_OK : base::File::FILE_ERROR_SECURITY), write_result_(post_copy_valid ? base::File::FILE_OK : base::File::FILE_ERROR_SECURITY), reject_string_(reject_string) { } ~TestValidator() override = default; void StartPreWriteValidation( const ResultCallback& result_callback) override { // Post the result since a real validator must do work asynchronously. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(result_callback, result_)); } void StartPostWriteValidation( const base::FilePath& dest_platform_path, const ResultCallback& result_callback) override { base::File::Error result = write_result_; std::string unsafe = dest_platform_path.BaseName().AsUTF8Unsafe(); if (unsafe.find(reject_string_) != std::string::npos) { result = base::File::FILE_ERROR_SECURITY; } // Post the result since a real validator must do work asynchronously. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(result_callback, result)); } private: base::File::Error result_; base::File::Error write_result_; std::string reject_string_; DISALLOW_COPY_AND_ASSIGN(TestValidator); }; }; // Records CopyProgressCallback invocations. struct ProgressRecord { storage::FileSystemOperation::CopyProgressType type; FileSystemURL source_url; FileSystemURL dest_url; int64_t size; }; void RecordProgressCallback(std::vector<ProgressRecord>* records, storage::FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, const FileSystemURL& dest_url, int64_t size) { ProgressRecord record; record.type = type; record.source_url = source_url; record.dest_url = dest_url; record.size = size; records->push_back(record); } void RecordFileProgressCallback(std::vector<int64_t>* records, int64_t progress) { records->push_back(progress); } void AssignAndQuit(base::RunLoop* run_loop, base::File::Error* result_out, base::File::Error result) { *result_out = result; run_loop->Quit(); } class ScopedThreadStopper { public: ScopedThreadStopper(base::Thread* thread) : thread_(thread) { } ~ScopedThreadStopper() { if (thread_) { // Give another chance for deleted streams to perform Close. base::RunLoop run_loop; thread_->task_runner()->PostTaskAndReply(FROM_HERE, base::DoNothing(), run_loop.QuitClosure()); run_loop.Run(); thread_->Stop(); } } bool is_valid() const { return thread_; } private: base::Thread* thread_; DISALLOW_COPY_AND_ASSIGN(ScopedThreadStopper); }; } // namespace class CopyOrMoveOperationTestHelper { public: CopyOrMoveOperationTestHelper(const GURL& origin, storage::FileSystemType src_type, storage::FileSystemType dest_type) : origin_(origin), src_type_(src_type), dest_type_(dest_type), scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO) {} ~CopyOrMoveOperationTestHelper() { file_system_context_ = NULL; quota_manager_proxy_->SimulateQuotaManagerDestroyed(); quota_manager_ = NULL; quota_manager_proxy_ = NULL; scoped_task_environment_.RunUntilIdle(); } void SetUp() { SetUp(true, true); } void SetUpNoValidator() { SetUp(true, false); } void SetUp(bool require_copy_or_move_validator, bool init_copy_or_move_validator) { ASSERT_TRUE(base_.CreateUniqueTempDir()); base::FilePath base_dir = base_.GetPath(); quota_manager_ = new MockQuotaManager(false /* is_incognito */, base_dir, base::ThreadTaskRunnerHandle::Get().get(), NULL /* special storage policy */); quota_manager_proxy_ = new MockQuotaManagerProxy( quota_manager_.get(), base::ThreadTaskRunnerHandle::Get().get()); file_system_context_ = CreateFileSystemContextForTesting(quota_manager_proxy_.get(), base_dir); // Prepare the origin's root directory. storage::FileSystemBackend* backend = file_system_context_->GetFileSystemBackend(src_type_); backend->ResolveURL( FileSystemURL::CreateForTest(origin_, src_type_, base::FilePath()), storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk)); backend = file_system_context_->GetFileSystemBackend(dest_type_); if (dest_type_ == storage::kFileSystemTypeTest) { TestFileSystemBackend* test_backend = static_cast<TestFileSystemBackend*>(backend); std::unique_ptr<storage::CopyOrMoveFileValidatorFactory> factory( new TestValidatorFactory); test_backend->set_require_copy_or_move_validator( require_copy_or_move_validator); if (init_copy_or_move_validator) test_backend->InitializeCopyOrMoveFileValidatorFactory( std::move(factory)); } backend->ResolveURL( FileSystemURL::CreateForTest(origin_, dest_type_, base::FilePath()), storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk)); scoped_task_environment_.RunUntilIdle(); // Grant relatively big quota initially. quota_manager_->SetQuota( origin_, storage::FileSystemTypeToQuotaStorageType(src_type_), 1024 * 1024); quota_manager_->SetQuota( origin_, storage::FileSystemTypeToQuotaStorageType(dest_type_), 1024 * 1024); } int64_t GetSourceUsage() { int64_t usage = 0; GetUsageAndQuota(src_type_, &usage, NULL); return usage; } int64_t GetDestUsage() { int64_t usage = 0; GetUsageAndQuota(dest_type_, &usage, NULL); return usage; } FileSystemURL SourceURL(const std::string& path) { return file_system_context_->CreateCrackedFileSystemURL( origin_, src_type_, base::FilePath::FromUTF8Unsafe(path)); } FileSystemURL DestURL(const std::string& path) { return file_system_context_->CreateCrackedFileSystemURL( origin_, dest_type_, base::FilePath::FromUTF8Unsafe(path)); } base::File::Error Copy(const FileSystemURL& src, const FileSystemURL& dest) { return AsyncFileTestHelper::Copy(file_system_context_.get(), src, dest); } base::File::Error CopyWithProgress( const FileSystemURL& src, const FileSystemURL& dest, const AsyncFileTestHelper::CopyProgressCallback& progress_callback) { return AsyncFileTestHelper::CopyWithProgress( file_system_context_.get(), src, dest, progress_callback); } base::File::Error Move(const FileSystemURL& src, const FileSystemURL& dest) { return AsyncFileTestHelper::Move(file_system_context_.get(), src, dest); } base::File::Error SetUpTestCaseFiles( const FileSystemURL& root, const FileSystemTestCaseRecord* const test_cases, size_t test_case_size) { base::File::Error result = base::File::FILE_ERROR_FAILED; for (size_t i = 0; i < test_case_size; ++i) { const FileSystemTestCaseRecord& test_case = test_cases[i]; FileSystemURL url = file_system_context_->CreateCrackedFileSystemURL( root.origin(), root.mount_type(), root.virtual_path().Append(test_case.path)); if (test_case.is_directory) result = CreateDirectory(url); else result = CreateFile(url, test_case.data_file_size); EXPECT_EQ(base::File::FILE_OK, result) << url.DebugString(); if (result != base::File::FILE_OK) return result; } return result; } void VerifyTestCaseFiles( const FileSystemURL& root, const FileSystemTestCaseRecord* const test_cases, size_t test_case_size) { std::map<base::FilePath, const FileSystemTestCaseRecord*> test_case_map; for (size_t i = 0; i < test_case_size; ++i) { test_case_map[ base::FilePath(test_cases[i].path).NormalizePathSeparators()] = &test_cases[i]; } base::queue<FileSystemURL> directories; FileEntryList entries; directories.push(root); while (!directories.empty()) { FileSystemURL dir = directories.front(); directories.pop(); ASSERT_EQ(base::File::FILE_OK, ReadDirectory(dir, &entries)); for (size_t i = 0; i < entries.size(); ++i) { FileSystemURL url = file_system_context_->CreateCrackedFileSystemURL( dir.origin(), dir.mount_type(), dir.virtual_path().Append(entries[i].name)); base::FilePath relative; root.virtual_path().AppendRelativePath(url.virtual_path(), &relative); relative = relative.NormalizePathSeparators(); ASSERT_TRUE(base::ContainsKey(test_case_map, relative)); if (entries[i].type == filesystem::mojom::FsFileType::DIRECTORY) { EXPECT_TRUE(test_case_map[relative]->is_directory); directories.push(url); } else { EXPECT_FALSE(test_case_map[relative]->is_directory); EXPECT_TRUE(FileExists(url, test_case_map[relative]->data_file_size)); } test_case_map.erase(relative); } } EXPECT_TRUE(test_case_map.empty()); for (const auto& path_record_pair : test_case_map) { LOG(ERROR) << "Extra entry: " << path_record_pair.first.LossyDisplayName(); } } base::File::Error ReadDirectory(const FileSystemURL& url, FileEntryList* entries) { return AsyncFileTestHelper::ReadDirectory( file_system_context_.get(), url, entries); } base::File::Error CreateDirectory(const FileSystemURL& url) { return AsyncFileTestHelper::CreateDirectory(file_system_context_.get(), url); } base::File::Error CreateFile(const FileSystemURL& url, size_t size) { base::File::Error result = AsyncFileTestHelper::CreateFile(file_system_context_.get(), url); if (result != base::File::FILE_OK) return result; return AsyncFileTestHelper::TruncateFile( file_system_context_.get(), url, size); } bool FileExists(const FileSystemURL& url, int64_t expected_size) { return AsyncFileTestHelper::FileExists( file_system_context_.get(), url, expected_size); } bool DirectoryExists(const FileSystemURL& url) { return AsyncFileTestHelper::DirectoryExists(file_system_context_.get(), url); } private: void GetUsageAndQuota(storage::FileSystemType type, int64_t* usage, int64_t* quota) { blink::mojom::QuotaStatusCode status = AsyncFileTestHelper::GetUsageAndQuota(quota_manager_.get(), origin_, type, usage, quota); ASSERT_EQ(blink::mojom::QuotaStatusCode::kOk, status); } private: base::ScopedTempDir base_; const GURL origin_; const storage::FileSystemType src_type_; const storage::FileSystemType dest_type_; base::test::ScopedTaskEnvironment scoped_task_environment_; scoped_refptr<storage::FileSystemContext> file_system_context_; scoped_refptr<MockQuotaManagerProxy> quota_manager_proxy_; scoped_refptr<MockQuotaManager> quota_manager_; DISALLOW_COPY_AND_ASSIGN(CopyOrMoveOperationTestHelper); }; TEST(LocalFileSystemCopyOrMoveOperationTest, CopySingleFile) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source file. ASSERT_EQ(base::File::FILE_OK, helper.CreateFile(src, 10)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Copy it. ASSERT_EQ(base::File::FILE_OK, helper.Copy(src, dest)); // Verify. ASSERT_TRUE(helper.FileExists(src, 10)); ASSERT_TRUE(helper.FileExists(dest, 10)); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage + src_increase, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, MoveSingleFile) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source file. ASSERT_EQ(base::File::FILE_OK, helper.CreateFile(src, 10)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Move it. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest)); // Verify. ASSERT_FALSE(helper.FileExists(src, AsyncFileTestHelper::kDontCheckSize)); ASSERT_TRUE(helper.FileExists(dest, 10)); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, CopySingleDirectory) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Copy it. ASSERT_EQ(base::File::FILE_OK, helper.Copy(src, dest)); // Verify. ASSERT_TRUE(helper.DirectoryExists(src)); ASSERT_TRUE(helper.DirectoryExists(dest)); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage + src_increase, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, MoveSingleDirectory) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Move it. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest)); // Verify. ASSERT_FALSE(helper.DirectoryExists(src)); ASSERT_TRUE(helper.DirectoryExists(dest)); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, CopyDirectory) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); ASSERT_EQ(base::File::FILE_OK, helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Copy it. ASSERT_EQ(base::File::FILE_OK, helper.CopyWithProgress( src, dest, AsyncFileTestHelper::CopyProgressCallback())); // Verify. ASSERT_TRUE(helper.DirectoryExists(src)); ASSERT_TRUE(helper.DirectoryExists(dest)); helper.VerifyTestCaseFiles(dest, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage + src_increase, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, MoveDirectory) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); int64_t src_initial_usage = helper.GetSourceUsage(); int64_t dest_initial_usage = helper.GetDestUsage(); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); ASSERT_EQ(base::File::FILE_OK, helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize)); int64_t src_increase = helper.GetSourceUsage() - src_initial_usage; // Move it. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest)); // Verify. ASSERT_FALSE(helper.DirectoryExists(src)); ASSERT_TRUE(helper.DirectoryExists(dest)); helper.VerifyTestCaseFiles(dest, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize); int64_t src_new_usage = helper.GetSourceUsage(); ASSERT_EQ(src_initial_usage, src_new_usage); int64_t dest_increase = helper.GetDestUsage() - dest_initial_usage; ASSERT_EQ(src_increase, dest_increase); } TEST(LocalFileSystemCopyOrMoveOperationTest, MoveDirectoryFailPostWriteValidation) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypeTest); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); ASSERT_EQ(base::File::FILE_OK, helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize)); // Move it. helper.Move(src, dest); // Verify. ASSERT_TRUE(helper.DirectoryExists(src)); ASSERT_TRUE(helper.DirectoryExists(dest)); // In the move operation, [file 0, file 2, file 3] are processed as LIFO. // After file 3 is processed, file 2 is rejected by the validator and the // operation fails. That is, only file 3 should be in dest. FileSystemTestCaseRecord kMoveDirResultCases[] = { {false, FILE_PATH_LITERAL("file 3"), 0}, }; helper.VerifyTestCaseFiles(dest, kMoveDirResultCases, arraysize(kMoveDirResultCases)); } TEST(LocalFileSystemCopyOrMoveOperationTest, CopySingleFileNoValidator) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypeTest); helper.SetUpNoValidator(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); // Set up a source file. ASSERT_EQ(base::File::FILE_OK, helper.CreateFile(src, 10)); // The copy attempt should fail with a security error -- getting // the factory returns a security error, and the copy operation must // respect that. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.Copy(src, dest)); } TEST(LocalFileSystemCopyOrMoveOperationTest, ProgressCallback) { CopyOrMoveOperationTestHelper helper(GURL("http://foo"), storage::kFileSystemTypeTemporary, storage::kFileSystemTypePersistent); helper.SetUp(); FileSystemURL src = helper.SourceURL("a"); FileSystemURL dest = helper.DestURL("b"); // Set up a source directory. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src)); ASSERT_EQ(base::File::FILE_OK, helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize)); std::vector<ProgressRecord> records; ASSERT_EQ(base::File::FILE_OK, helper.CopyWithProgress(src, dest, base::Bind(&RecordProgressCallback, base::Unretained(&records)))); // Verify progress callback. for (size_t i = 0; i < kRegularFileSystemTestCaseSize; ++i) { const FileSystemTestCaseRecord& test_case = kRegularFileSystemTestCases[i]; FileSystemURL src_url = helper.SourceURL( std::string("a/") + base::FilePath(test_case.path).AsUTF8Unsafe()); FileSystemURL dest_url = helper.DestURL( std::string("b/") + base::FilePath(test_case.path).AsUTF8Unsafe()); // Find the first and last progress record. size_t begin_index = records.size(); size_t end_index = records.size(); for (size_t j = 0; j < records.size(); ++j) { if (records[j].source_url == src_url) { if (begin_index == records.size()) begin_index = j; end_index = j; } } // The record should be found. ASSERT_NE(begin_index, records.size()); ASSERT_NE(end_index, records.size()); ASSERT_NE(begin_index, end_index); EXPECT_EQ(FileSystemOperation::BEGIN_COPY_ENTRY, records[begin_index].type); EXPECT_FALSE(records[begin_index].dest_url.is_valid()); EXPECT_EQ(FileSystemOperation::END_COPY_ENTRY, records[end_index].type); EXPECT_EQ(dest_url, records[end_index].dest_url); if (test_case.is_directory) { // For directory copy, the progress shouldn't be interlaced. EXPECT_EQ(begin_index + 1, end_index); } else { // PROGRESS event's size should be assending order. int64_t current_size = 0; for (size_t j = begin_index + 1; j < end_index; ++j) { if (records[j].source_url == src_url) { EXPECT_EQ(FileSystemOperation::PROGRESS, records[j].type); EXPECT_FALSE(records[j].dest_url.is_valid()); EXPECT_GE(records[j].size, current_size); current_size = records[j].size; } } } } } TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelper) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath source_path = temp_dir.GetPath().AppendASCII("source"); base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest"); const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789"; base::WriteFile(source_path, kTestData, arraysize(kTestData) - 1); // Exclude trailing '\0'. base::MessageLoopForIO message_loop; base::Thread file_thread("file_thread"); ASSERT_TRUE(file_thread.Start()); ScopedThreadStopper thread_stopper(&file_thread); ASSERT_TRUE(thread_stopper.is_valid()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = file_thread.task_runner(); std::unique_ptr<storage::FileStreamReader> reader( storage::FileStreamReader::CreateForLocalFile( task_runner.get(), source_path, 0, base::Time())); std::unique_ptr<FileStreamWriter> writer(FileStreamWriter::CreateForLocalFile( task_runner.get(), dest_path, 0, FileStreamWriter::CREATE_NEW_FILE)); std::vector<int64_t> progress; CopyOrMoveOperationDelegate::StreamCopyHelper helper( std::move(reader), std::move(writer), storage::FlushPolicy::NO_FLUSH_ON_COMPLETION, 10, // buffer size base::Bind(&RecordFileProgressCallback, base::Unretained(&progress)), base::TimeDelta()); // For testing, we need all the progress. base::File::Error error = base::File::FILE_ERROR_FAILED; base::RunLoop run_loop; helper.Run(base::Bind(&AssignAndQuit, &run_loop, &error)); run_loop.Run(); EXPECT_EQ(base::File::FILE_OK, error); ASSERT_EQ(5U, progress.size()); EXPECT_EQ(0, progress[0]); EXPECT_EQ(10, progress[1]); EXPECT_EQ(20, progress[2]); EXPECT_EQ(30, progress[3]); EXPECT_EQ(36, progress[4]); std::string content; ASSERT_TRUE(base::ReadFileToString(dest_path, &content)); EXPECT_EQ(kTestData, content); } TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelperWithFlush) { // Testing the same configuration as StreamCopyHelper, but with |need_flush| // parameter set to true. Since it is hard to test that the flush is indeed // taking place, this test just only verifies that the file is correctly // written with or without the flag. base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath source_path = temp_dir.GetPath().AppendASCII("source"); base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest"); const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789"; base::WriteFile(source_path, kTestData, arraysize(kTestData) - 1); // Exclude trailing '\0'. base::MessageLoopForIO message_loop; base::Thread file_thread("file_thread"); ASSERT_TRUE(file_thread.Start()); ScopedThreadStopper thread_stopper(&file_thread); ASSERT_TRUE(thread_stopper.is_valid()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = file_thread.task_runner(); std::unique_ptr<storage::FileStreamReader> reader( storage::FileStreamReader::CreateForLocalFile( task_runner.get(), source_path, 0, base::Time())); std::unique_ptr<FileStreamWriter> writer(FileStreamWriter::CreateForLocalFile( task_runner.get(), dest_path, 0, FileStreamWriter::CREATE_NEW_FILE)); std::vector<int64_t> progress; CopyOrMoveOperationDelegate::StreamCopyHelper helper( std::move(reader), std::move(writer), storage::FlushPolicy::NO_FLUSH_ON_COMPLETION, 10, // buffer size base::Bind(&RecordFileProgressCallback, base::Unretained(&progress)), base::TimeDelta()); // For testing, we need all the progress. base::File::Error error = base::File::FILE_ERROR_FAILED; base::RunLoop run_loop; helper.Run(base::Bind(&AssignAndQuit, &run_loop, &error)); run_loop.Run(); EXPECT_EQ(base::File::FILE_OK, error); ASSERT_EQ(5U, progress.size()); EXPECT_EQ(0, progress[0]); EXPECT_EQ(10, progress[1]); EXPECT_EQ(20, progress[2]); EXPECT_EQ(30, progress[3]); EXPECT_EQ(36, progress[4]); std::string content; ASSERT_TRUE(base::ReadFileToString(dest_path, &content)); EXPECT_EQ(kTestData, content); } TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelper_Cancel) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath source_path = temp_dir.GetPath().AppendASCII("source"); base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest"); const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789"; base::WriteFile(source_path, kTestData, arraysize(kTestData) - 1); // Exclude trailing '\0'. base::MessageLoopForIO message_loop; base::Thread file_thread("file_thread"); ASSERT_TRUE(file_thread.Start()); ScopedThreadStopper thread_stopper(&file_thread); ASSERT_TRUE(thread_stopper.is_valid()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = file_thread.task_runner(); std::unique_ptr<storage::FileStreamReader> reader( storage::FileStreamReader::CreateForLocalFile( task_runner.get(), source_path, 0, base::Time())); std::unique_ptr<FileStreamWriter> writer(FileStreamWriter::CreateForLocalFile( task_runner.get(), dest_path, 0, FileStreamWriter::CREATE_NEW_FILE)); std::vector<int64_t> progress; CopyOrMoveOperationDelegate::StreamCopyHelper helper( std::move(reader), std::move(writer), storage::FlushPolicy::NO_FLUSH_ON_COMPLETION, 10, // buffer size base::Bind(&RecordFileProgressCallback, base::Unretained(&progress)), base::TimeDelta()); // For testing, we need all the progress. // Call Cancel() later. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CopyOrMoveOperationDelegate::StreamCopyHelper::Cancel, base::Unretained(&helper))); base::File::Error error = base::File::FILE_ERROR_FAILED; base::RunLoop run_loop; helper.Run(base::Bind(&AssignAndQuit, &run_loop, &error)); run_loop.Run(); EXPECT_EQ(base::File::FILE_ERROR_ABORT, error); } } // namespace content
/* // Copyright (c) 2018 Intel 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 "utils.hpp" #include <sdbusplus/timer.hpp> namespace phosphor { namespace service { static constexpr const char* serviceConfigSrvName = "xyz.openbmc_project.Control.Service.Manager"; static constexpr const char* serviceConfigIntfName = "xyz.openbmc_project.Control.Service.Attributes"; static constexpr const char* sockAttrIntfName = "xyz.openbmc_project.Control.Service.SocketAttributes"; static constexpr const char* srcCfgMgrBasePath = "/xyz/openbmc_project/control/service"; static constexpr const char* sockAttrPropPort = "Port"; static constexpr const char* srvCfgPropMasked = "Masked"; static constexpr const char* srvCfgPropEnabled = "Enabled"; static constexpr const char* srvCfgPropRunning = "Running"; enum class UpdatedProp { port = 1, maskedState, enabledState, runningState }; using VariantType = std::variant<std::string, int64_t, uint64_t, double, int32_t, uint32_t, int16_t, uint16_t, uint8_t, bool, std::vector<std::tuple<std::string, std::string>>>; class ServiceConfig { public: ServiceConfig(sdbusplus::asio::object_server& srv_, std::shared_ptr<sdbusplus::asio::connection>& conn_, const std::string& objPath_, const std::string& baseUnitName, const std::string& instanceName, const std::string& serviceObjPath, const std::string& socketObjPath); ~ServiceConfig() = default; std::shared_ptr<sdbusplus::asio::connection> conn; uint8_t updatedFlag; void stopAndApplyUnitConfig(boost::asio::yield_context yield); void restartUnitConfig(boost::asio::yield_context yield); void startServiceRestartTimer(); #ifdef USB_CODE_UPDATE void saveUSBCodeUpdateStateToFile(const bool& maskedState, const bool& enabledState); void getUSBCodeUpdateStateFromFile(); void setUSBCodeUpdateState(const bool& state); #endif private: sdbusplus::asio::object_server& server; std::shared_ptr<sdbusplus::asio::dbus_interface> srvCfgIface; std::shared_ptr<sdbusplus::asio::dbus_interface> sockAttrIface; bool internalSet = false; std::string objPath; std::string baseUnitName; std::string instanceName; std::string instantiatedUnitName; std::string serviceObjectPath; std::string socketObjectPath; std::string overrideConfDir; // Properties std::string activeState; std::string subState; uint16_t portNum; std::vector<std::string> channelList; std::string protocol; std::string stateValue; bool unitMaskedState = false; bool unitEnabledState = false; bool unitRunningState = false; bool isSocketActivatedService = false; std::string subStateValue; bool isMaskedOut(); void registerProperties(); void queryAndUpdateProperties(); void createSocketOverrideConf(); void updateServiceProperties( const boost::container::flat_map<std::string, VariantType>& propertyMap); void updateSocketProperties( const boost::container::flat_map<std::string, VariantType>& propertyMap); std::string getSocketUnitName(); std::string getServiceUnitName(); }; } // namespace service } // namespace phosphor
// // File: ContingencyTableTest.cpp // Created by: Julien Dutheil // Created on: Thu Dec 09 14:20 2010 // /* Copyright or © or Copr. Bio++ Development Team, (November 17, 2004) This software is a computer program whose purpose is to provide classes for numerical calculus. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #include "ContingencyTableTest.h" #include "../Random/ContingencyTableGenerator.h" #include "../../App/ApplicationTools.h" #include "../VectorTools.h" #include "../Random/RandomTools.h" #include <iostream> #include <algorithm> using namespace bpp; using namespace std; ContingencyTableTest::ContingencyTableTest(const std::vector< std::vector<size_t> >& table, unsigned int nbPermutations, bool warn): statistic_(0), pvalue_(0), df_(0), margin1_(table.size()), margin2_(0) { //Compute marginals: size_t n = table.size(); if (n < 2) throw Exception("ContingencyTableTest. Table size should be at least 2x2!"); size_t m = table[0].size(); if (m < 2) throw Exception("ContingencyTableTest. Table size should be at least 2x2!"); margin2_.resize(m); for (size_t j = 0; j < m; ++j) margin2_[j] = 0; bool test = false; for (size_t i = 0; i < n; ++i) { if (table[i].size() != m) throw Exception("ContingencyTableTest. Input array has non-homogeneous dimensions!"); for (size_t j = 0; j < m; ++j) { size_t c = table[i][j]; if (c <= 5) test = true; margin1_[i] += c; margin2_[j] += c; } } for (size_t i = 0; i < n; ++i) if (margin1_[i] == 0) throw Exception("ContingencyTableTest. Row " + TextTools::toString(i) + " sums to 0."); for (size_t j = 0; j < m; ++j) if (margin2_[j] == 0) throw Exception("ContingencyTableTest. Column " + TextTools::toString(j) + " sums to 0."); size_t tot = VectorTools::sum(margin1_); df_ = static_cast<double>((m - 1) * (n - 1)); RowMatrix<long double> expc(n, m); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { long double c = table[i][j]; long double e = static_cast<long double>(margin1_[i] * margin2_[j]) / static_cast<long double>(tot); expc(i, j) = e; statistic_ += static_cast<double>(std::pow(c - e, 2.L) / e); } } if (nbPermutations > 0) { size_t count = 0; ContingencyTableGenerator ctgen(margin1_, margin2_); for (unsigned int k = 0; k < nbPermutations; ++k) { //Randomize: RowMatrix<size_t> table_rep = ctgen.rcont2(); //Recompute statistic: double stat_rep = 0; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { long double c = table_rep(i , j); long double e = expc(i, j); stat_rep += static_cast<double>(std::pow(c - e, 2.L) / e); } } if (stat_rep >= statistic_) count++; } pvalue_ = static_cast<double>(count + 1) / static_cast<double>(nbPermutations + 1); } else { if (test && warn) ApplicationTools::displayWarning("Unsufficient observations, p-value might be incorrect."); //Compute p-value: pvalue_ = 1. - RandomTools::pChisq(statistic_, df_); } }
// Copyright (c) 2018, 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. #include "real.h" #include "int-power.h" #include "../common/idioms.h" #include "../parser/characters.h" #include <limits> namespace Fortran::evaluate::value { template<typename W, int P, bool IM> Relation Real<W, P, IM>::Compare(const Real &y) const { if (IsNotANumber() || y.IsNotANumber()) { // NaN vs x, x vs NaN return Relation::Unordered; } else if (IsInfinite()) { if (y.IsInfinite()) { if (IsNegative()) { // -Inf vs +/-Inf return y.IsNegative() ? Relation::Equal : Relation::Less; } else { // +Inf vs +/-Inf return y.IsNegative() ? Relation::Greater : Relation::Equal; } } else { // +/-Inf vs finite return IsNegative() ? Relation::Less : Relation::Greater; } } else if (y.IsInfinite()) { // finite vs +/-Inf return y.IsNegative() ? Relation::Greater : Relation::Less; } else { // two finite numbers bool isNegative{IsNegative()}; if (isNegative != y.IsNegative()) { if (word_.IOR(y.word_).IBCLR(bits - 1).IsZero()) { return Relation::Equal; // +/-0.0 == -/+0.0 } else { return isNegative ? Relation::Less : Relation::Greater; } } else { // same sign Ordering order{evaluate::Compare(Exponent(), y.Exponent())}; if (order == Ordering::Equal) { order = GetSignificand().CompareUnsigned(y.GetSignificand()); } if (isNegative) { order = Reverse(order); } return RelationFromOrdering(order); } } } template<typename W, int P, bool IM> ValueWithRealFlags<Real<W, P, IM>> Real<W, P, IM>::Add( const Real &y, Rounding rounding) const { ValueWithRealFlags<Real> result; if (IsNotANumber() || y.IsNotANumber()) { result.value = NotANumber(); // NaN + x -> NaN if (IsSignalingNaN() || y.IsSignalingNaN()) { result.flags.set(RealFlag::InvalidArgument); } return result; } bool isNegative{IsNegative()}; bool yIsNegative{y.IsNegative()}; if (IsInfinite()) { if (y.IsInfinite()) { if (isNegative == yIsNegative) { result.value = *this; // +/-Inf + +/-Inf -> +/-Inf } else { result.value = NotANumber(); // +/-Inf + -/+Inf -> NaN result.flags.set(RealFlag::InvalidArgument); } } else { result.value = *this; // +/-Inf + x -> +/-Inf } return result; } if (y.IsInfinite()) { result.value = y; // x + +/-Inf -> +/-Inf return result; } std::uint64_t exponent{Exponent()}; std::uint64_t yExponent{y.Exponent()}; if (exponent < yExponent) { // y is larger in magnitude; simplify by reversing operands return y.Add(*this, rounding); } if (exponent == yExponent && isNegative != yIsNegative) { Ordering order{GetSignificand().CompareUnsigned(y.GetSignificand())}; if (order == Ordering::Less) { // Same exponent, opposite signs, and y is larger in magnitude return y.Add(*this, rounding); } if (order == Ordering::Equal) { // x + (-x) -> +0.0 unless rounding is directed downwards if (rounding == Rounding::Down) { result.value.word_ = result.value.word_.IBSET(bits - 1); // -0.0 } return result; } } // Our exponent is greater than y's, or the exponents match and y is not // of the opposite sign and greater magnitude. So (x+y) will have the // same sign as x. Fraction fraction{GetFraction()}; Fraction yFraction{y.GetFraction()}; int rshift = exponent - yExponent; if (exponent > 0 && yExponent == 0) { --rshift; // correct overshift when only y is denormal } RoundingBits roundingBits{yFraction, rshift}; yFraction = yFraction.SHIFTR(rshift); bool carry{false}; if (isNegative != yIsNegative) { // Opposite signs: subtract via addition of two's complement of y and // the rounding bits. yFraction = yFraction.NOT(); carry = roundingBits.Negate(); } auto sum{fraction.AddUnsigned(yFraction, carry)}; fraction = sum.value; if (isNegative == yIsNegative && sum.carry) { roundingBits.ShiftRight(sum.value.BTEST(0)); fraction = fraction.SHIFTR(1).IBSET(fraction.bits - 1); ++exponent; } NormalizeAndRound( result, isNegative, exponent, fraction, rounding, roundingBits); return result; } template<typename W, int P, bool IM> ValueWithRealFlags<Real<W, P, IM>> Real<W, P, IM>::Multiply( const Real &y, Rounding rounding) const { ValueWithRealFlags<Real> result; if (IsNotANumber() || y.IsNotANumber()) { result.value = NotANumber(); // NaN * x -> NaN if (IsSignalingNaN() || y.IsSignalingNaN()) { result.flags.set(RealFlag::InvalidArgument); } } else { bool isNegative{IsNegative() != y.IsNegative()}; if (IsInfinite() || y.IsInfinite()) { if (IsZero() || y.IsZero()) { result.value = NotANumber(); // 0 * Inf -> NaN result.flags.set(RealFlag::InvalidArgument); } else { result.value = Infinity(isNegative); } } else { auto product{GetFraction().MultiplyUnsigned(y.GetFraction())}; std::int64_t exponent{CombineExponents(y, false)}; if (exponent < 1) { int rshift = 1 - exponent; exponent = 1; bool sticky{false}; if (rshift >= product.upper.bits + product.lower.bits) { sticky = !product.lower.IsZero() || !product.upper.IsZero(); } else if (rshift >= product.lower.bits) { sticky = !product.lower.IsZero() || !product.upper .IAND(product.upper.MASKR(rshift - product.lower.bits)) .IsZero(); } else { sticky = !product.lower.IAND(product.lower.MASKR(rshift)).IsZero(); } product.lower = product.lower.DSHIFTR(product.upper, rshift); product.upper = product.upper.SHIFTR(rshift); if (sticky) { product.lower = product.lower.IBSET(0); } } int leadz{product.upper.LEADZ()}; if (leadz >= product.upper.bits) { leadz += product.lower.LEADZ(); } int lshift{leadz}; if (lshift > exponent - 1) { lshift = exponent - 1; } exponent -= lshift; product.upper = product.upper.DSHIFTL(product.lower, lshift); product.lower = product.lower.SHIFTL(lshift); RoundingBits roundingBits{product.lower, product.lower.bits}; NormalizeAndRound(result, isNegative, exponent, product.upper, rounding, roundingBits, true /*multiply*/); } } return result; } template<typename W, int P, bool IM> ValueWithRealFlags<Real<W, P, IM>> Real<W, P, IM>::Divide( const Real &y, Rounding rounding) const { ValueWithRealFlags<Real> result; if (IsNotANumber() || y.IsNotANumber()) { result.value = NotANumber(); // NaN / x -> NaN, x / NaN -> NaN if (IsSignalingNaN() || y.IsSignalingNaN()) { result.flags.set(RealFlag::InvalidArgument); } } else { bool isNegative{IsNegative() != y.IsNegative()}; if (IsInfinite()) { if (y.IsInfinite()) { result.value = NotANumber(); // Inf/Inf -> NaN result.flags.set(RealFlag::InvalidArgument); } else { // Inf/x -> Inf, Inf/0 -> Inf result.value = Infinity(isNegative); } } else if (y.IsZero()) { if (IsZero()) { // 0/0 -> NaN result.value = NotANumber(); result.flags.set(RealFlag::InvalidArgument); } else { // x/0 -> Inf, Inf/0 -> Inf result.value = Infinity(isNegative); result.flags.set(RealFlag::DivideByZero); } } else if (IsZero() || y.IsInfinite()) { // 0/x, x/Inf -> 0 if (isNegative) { result.value.word_ = result.value.word_.IBSET(bits - 1); } } else { // dividend and divisor are both finite and nonzero numbers Fraction top{GetFraction()}, divisor{y.GetFraction()}; std::int64_t exponent{CombineExponents(y, true)}; Fraction quotient; bool msb{false}; if (!top.BTEST(top.bits - 1) || !divisor.BTEST(divisor.bits - 1)) { // One or two denormals int topLshift{top.LEADZ()}; top = top.SHIFTL(topLshift); int divisorLshift{divisor.LEADZ()}; divisor = divisor.SHIFTL(divisorLshift); exponent += divisorLshift - topLshift; } for (int j{1}; j <= quotient.bits; ++j) { if (NextQuotientBit(top, msb, divisor)) { quotient = quotient.IBSET(quotient.bits - j); } } bool guard{NextQuotientBit(top, msb, divisor)}; bool round{NextQuotientBit(top, msb, divisor)}; bool sticky{msb || !top.IsZero()}; RoundingBits roundingBits{guard, round, sticky}; if (exponent < 1) { std::int64_t rshift{1 - exponent}; for (; rshift > 0; --rshift) { roundingBits.ShiftRight(quotient.BTEST(0)); quotient = quotient.SHIFTR(1); } exponent = 1; } NormalizeAndRound( result, isNegative, exponent, quotient, rounding, roundingBits); } } return result; } template<typename W, int P, bool IM> RealFlags Real<W, P, IM>::Normalize(bool negative, std::uint64_t exponent, const Fraction &fraction, Rounding rounding, RoundingBits *roundingBits) { std::uint64_t lshift = fraction.LEADZ(); if (lshift == fraction.bits /* fraction is zero */ && (roundingBits == nullptr || roundingBits->empty())) { // No fraction, no rounding bits -> +/-0.0 exponent = lshift = 0; } else if (lshift < exponent) { exponent -= lshift; } else if (exponent > 0) { lshift = exponent - 1; exponent = 0; } else if (lshift == 0) { exponent = 1; } else { lshift = 0; } if (exponent >= maxExponent) { // Infinity or overflow if (rounding == Rounding::TiesToEven || rounding == Rounding::TiesAwayFromZero || (rounding == Rounding::Up && !negative) || (rounding == Rounding::Down && negative)) { word_ = Word{maxExponent}.SHIFTL(significandBits); // Inf } else { // directed rounding: round to largest finite value rather than infinity // (x86 does this, not sure whether it's standard behavior) word_ = Word{word_.MASKR(word_.bits - 1)}.IBCLR(significandBits); } if (negative) { word_ = word_.IBSET(bits - 1); } RealFlags flags{RealFlag::Overflow}; if (!fraction.IsZero()) { flags.set(RealFlag::Inexact); } return flags; } word_ = Word::ConvertUnsigned(fraction).value; if (lshift > 0) { word_ = word_.SHIFTL(lshift); if (roundingBits != nullptr) { for (; lshift > 0; --lshift) { if (roundingBits->ShiftLeft()) { word_ = word_.IBSET(lshift - 1); } } } } if constexpr (implicitMSB) { word_ = word_.IBCLR(significandBits); } word_ = word_.IOR(Word{exponent}.SHIFTL(significandBits)); if (negative) { word_ = word_.IBSET(bits - 1); } return {}; } template<typename W, int P, bool IM> RealFlags Real<W, P, IM>::Round( Rounding rounding, const RoundingBits &bits, bool multiply) { std::uint64_t origExponent{Exponent()}; RealFlags flags; bool inexact{!bits.empty()}; if (inexact) { flags.set(RealFlag::Inexact); } if (origExponent < maxExponent && bits.MustRound(rounding, IsNegative(), word_.BTEST(0) /* is odd */)) { typename Fraction::ValueWithCarry sum{ GetFraction().AddUnsigned(Fraction{}, true)}; std::uint64_t newExponent{origExponent}; if (sum.carry) { // The fraction was all ones before rounding; sum.value is now zero sum.value = sum.value.IBSET(precision - 1); if (++newExponent >= maxExponent) { flags.set(RealFlag::Overflow); // rounded away to an infinity } } flags |= Normalize(IsNegative(), newExponent, sum.value); } if (inexact && origExponent == 0) { // inexact denormal input if (Exponent() == 0) { flags.set(RealFlag::Underflow); // output still denormal -> Underflow } else { // Rounding went up to the smallest normal number. // Still signal Underflow unless we're in a weird x86 edge case with // multiplication: if the sticky bit is set (i.e., the lower half of // the full product had bits below the top 2), Underflow gets set in // a directed rounding mode only if the guard bit was also set. if (multiply && bits.sticky() && (bits.guard() || !(rounding == Rounding::Up || rounding == Rounding::Down))) { } else { flags.set(RealFlag::Underflow); } } } return flags; } template<typename W, int P, bool IM> void Real<W, P, IM>::NormalizeAndRound(ValueWithRealFlags<Real> &result, bool isNegative, std::uint64_t exponent, const Fraction &fraction, Rounding rounding, RoundingBits roundingBits, bool multiply) { result.flags |= result.value.Normalize( isNegative, exponent, fraction, rounding, &roundingBits); result.flags |= result.value.Round(rounding, roundingBits, multiply); } template<typename W, int P, bool IM> ValueWithRealFlags<Real<W, P, IM>> Real<W, P, IM>::Read( const char *&p, Rounding rounding) { ValueWithRealFlags<Real> result; Real ten{FromInteger(Integer<32>{10}).value}; for (; parser::IsDecimalDigit(*p); ++p) { result.value = result.value.Multiply(ten, rounding).AccumulateFlags(result.flags); result.value = result.value.Add(FromInteger(Integer<32>{*p - '0'}).value, rounding) .AccumulateFlags(result.flags); } std::int64_t exponent{0}; if (*p == '.') { for (++p; parser::IsDecimalDigit(*p); ++p) { --exponent; result.value = result.value.Multiply(ten, rounding).AccumulateFlags(result.flags); result.value = result.value.Add(FromInteger(Integer<32>{*p - '0'}).value, rounding) .AccumulateFlags(result.flags); } } if (parser::IsLetter(*p)) { bool negExpo{false}; if (*++p == '-') { negExpo = true; ++p; } else if (*p == '+') { ++p; } auto expo{Integer<32>::ReadUnsigned(p)}; std::int64_t expoVal{expo.value.ToInt64()}; if (expo.overflow) { expoVal = std::numeric_limits<std::int32_t>::max(); } else if (negExpo) { expoVal *= -1; } exponent += expoVal; } if (exponent == 0) { return result; } Real tenPower{IntPower(ten, Integer<64>{std::abs(exponent)}, rounding) .AccumulateFlags(result.flags)}; if (exponent > 0) { result.value = result.value.Multiply(tenPower, rounding).AccumulateFlags(result.flags); } else { result.value = result.value.Divide(tenPower, rounding).AccumulateFlags(result.flags); } return result; } template<typename W, int P, bool IM> std::string Real<W, P, IM>::DumpHexadecimal() const { if (IsNotANumber()) { return "NaN 0x"s + word_.Hexadecimal(); } else if (IsNegative()) { return "-"s + Negate().DumpHexadecimal(); } else if (IsInfinite()) { return "Inf"s; } else if (IsZero()) { return "0.0"s; } else { Fraction frac{GetFraction()}; std::string result{"0x"}; char intPart = '0' + frac.BTEST(frac.bits - 1); result += intPart; result += '.'; int trailz{frac.TRAILZ()}; if (trailz >= frac.bits - 1) { result += '0'; } else { int remainingBits{frac.bits - 1 - trailz}; int wholeNybbles{remainingBits / 4}; int lostBits{remainingBits - 4 * wholeNybbles}; if (wholeNybbles > 0) { std::string fracHex{frac.SHIFTR(trailz + lostBits) .IAND(frac.MASKR(4 * wholeNybbles)) .Hexadecimal()}; std::size_t field = wholeNybbles; if (fracHex.size() < field) { result += std::string(field - fracHex.size(), '0'); } result += fracHex; } if (lostBits > 0) { result += frac.SHIFTR(trailz) .IAND(frac.MASKR(lostBits)) .SHIFTL(4 - lostBits) .Hexadecimal(); } } result += 'p'; int exponent = Exponent() - exponentBias; result += Integer<32>{exponent}.SignedDecimal(); return result; } } template class Real<Integer<16>, 11>; template class Real<Integer<32>, 24>; template class Real<Integer<64>, 53>; template class Real<Integer<80>, 64, false>; template class Real<Integer<128>, 112>; } // namespace Fortran::evaluate::value
//#include <algorithm> //#include <bitset> //#include <cassert> //#include <cctype> //#include <climits> //#include <cmath> //#include <cstdio> //#include <cstdlib> //#include <cstring> //#include <fstream> //#include <iostream> //#include <iomanip> //#include <iterator> //#include <list> //#include <map> //#include <numeric> //#include <queue> //#include <set> //#include <sstream> //#include <stack> //#include <string> //#include <utility> //#include <vector> #include <bits/stdc++.h> using namespace std; //#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getF(n) scanf("%lf",&n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define ranL(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a)) #define ranI(a, b) ((((ll)rand() * rand()) % ((b) - (a) + 1)) + (a)) #define ranF(a, b) (((double)rand()/RAND_MAX)*((b) - (a)) + (a)) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define setInf(ar) memset(ar,126,sizeof ar) #define ff first #define ss second #define sf scanf #define pf printf typedef long long ll; typedef unsigned long long ull; typedef vector < int > vi; typedef vector < vi > vii; typedef pair < int, int> pii; #define FMT(...) (sprintf(CRTBUFF, __VA_ARGS__)?CRTBUFF:0) char CRTBUFF[30000]; #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; const double EPS = 1e-9; const int INF = 0x3f3f3f3f; const double PI = 2.0 * acos(0.0); ll MIN() { return INF; } template <typename T, typename... Args > inline T MIN(T a, Args... args) { return min(a, (T)MIN(args...)); } ll MAX() { return -INF; } template <typename T, typename... Args > inline T MAX(T a, Args... args) { return max(a, (T)MAX(args...)); } // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out ///****************** template ends here **************** int EQ(double d) { if ( fabs(d) < EPS ) return 0; return d > EPS ? 1 : -1 ; } inline double sqr(double x) { return x*x; } struct point { double x,y; point() {} point(double _x,double _y): x(_x),y(_y) {}; bool operator==(point a)const { return EQ(a.x-x)==0&&EQ(a.y-y)==0; } bool operator<(point a)const { return EQ(a.x-x)==0?EQ(y-a.y)<0:x<a.x; } double len() { return hypot(x,y); } double len2() { return x*x+y*y; } /// Eucladian distance double distance(point p) { return hypot(x-p.x,y-p.y); } point add(point p) { return point(x+p.x,y+p.y); } point operator+(const point &p) const { return point(x+p.x,y+p.y); } point sub(point p) { return point(x-p.x,y-p.y); } point operator-(const point &p) const { return point(x-p.x,y-p.y); } point mul(double b) { return point(x*b,y*b); } point operator*(double b) const { return point(x*b,y*b); } point div(double b) { return point(x/b,y/b); } point operator/(double b) const { return point(x/b,y/b); } double dot(point p) { return x*p.x+y*p.y; } double cross(point p) { return x*p.y-y*p.x; } double rad(point a,point b) { point p=*this; return fabs(atan2(fabs(a.sub(p).cross(b.sub(p))),a.sub(p).dot(b.sub(p)))); } /// মূলবিন্দু (0,0) থেকে r দুরত্তে নতুন একটি বিন্দু তৈরী করে যা (০,০) এবং বর্তমান বিন্দুর সাথে co-linear point trunc(double r) { double l=len(); if (!EQ(l))return *this; r/=l; return point(x*r,y*r); } ///rotate this point counter clockwise on the basis of point p point rotate(point p,double angle) { point v=this->sub(p); double c=cos(angle),s=sin(angle); return point(p.x+v.x*c-v.y*s, p.y+v.x*s+v.y*c); } point rotleft() { return point(-y,x); } point rotright() { return point(y,-x); } /// Point in rectangle or not /// rectangle : a = leftDown , b = rightTop , c is in the rectangle or not // remove = (eql sign) if strictly in box needed bool in_box(point a,point b) { point c = *this; double lox = min(a.x, b.x), hix = max(a.x, b.x); double loy = min(a.y, b.y), hiy = max(a.y, b.y); return c.x >= lox && c.x <= hix && c.y >= loy && c.y <= hiy; } }; /// -1 -> Right Turn /// 1 -> Left Turn /// 0 -> Straight Line / Co-linear int turn( point O , point A , point B) { // double res = (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x); if( res < 0 ) return -1 ; // O->A->B is a right turn if( res > 0 ) return 1 ; // O->A->B is a left turn return 0; // O->A->B is a straight line / co-linear } //Find if C is between A and B or B and A bool pointBetween ( point a, point b, point c ) { if ( min(a.x,b.x) <= c.x && c.x <= max(a.x,b.x) && min(a.y,b.y) <= c.y && c.y <= max(a.y,b.y) ) return true; else return false; } struct line { point a,b; line() {} line(point _a,point _b) { a=_a; b=_b; } bool operator==(line v) { return (a==v.a)&&(b==v.b); } ///inclination angle /// The angle between the line and x-axis, line(point p,double angle) { a=p; if (EQ(angle-PI/2)==0) { b=a.add(point(0,1)); } else { b=a.add(point(1,tan(angle))); } } /// ax+by+c=0 line(double _a,double _b,double _c) { if (EQ(_a)==0) { a=point(0,-_c/_b); b=point(1,-_c/_b); } else if (EQ(_b)==0) { a=point(-_c/_a,0); b=point(-_c/_a,1); } else { a=point(0,-_c/_b); b=point(1,(-_c-_a)/_b); } } void adjust() { if (b<a)swap(a,b); } double length() { return a.distance(b); } /// Straight tilt(inclination angle) angle 0 <= angle <180 double angle() { double k=atan2(b.y-a.y,b.x-a.x); if (EQ(k)<0)k+=PI; if (EQ(k-PI)==0)k-=PI; return k; } /** Points and line segments between 1 Counter clockwise 2 in a clockwise 3 parallel **/ int relation(point p) { int c=EQ(p.sub(a).cross(b.sub(a))); if (c<0)return 1; if (c>0)return 2; return 3; } bool pointonseg(point p) { return EQ(p.sub(a).cross(b.sub(a)))==0&&EQ(p.sub(a).dot(p.sub(b)))<=0; } bool parallel(line v) { return EQ(b.sub(a).cross(v.b.sub(v.a)))==0; } /// If the point is int / ll use the below one, in the last of this page bool segmentIntersection ( line l ) { point c = l.a; point d = l.b; ll s1 = turn( a, b, c ); ll s2 = turn( a, b, d ); ll s3 = turn( c, d, a ); ll s4 = turn( c, d, b ); if(s1 != s2 && s3 != s4) return true; if ( s1 == 0 && pointBetween ( a, b, c ) ) return true; else if ( s2 == 0 && pointBetween ( a, b, d ) ) return true; else if ( s3 == 0 && pointBetween ( c, d, a ) ) return true; else if ( s4 == 0 && pointBetween ( c, d, b ) ) return true; return false; } /** Need to be tested these 2 coincides 1 Normal Intersects 0 Not intersect/disjoint **/ int segCrossSeg(line v) { int d1=EQ(b.sub(a).cross(v.a.sub(a))); int d2=EQ(b.sub(a).cross(v.b.sub(a))); int d3=EQ(v.b.sub(v.a).cross(a.sub(v.a))); int d4=EQ(v.b.sub(v.a).cross(b.sub(v.a))); if ((d1^d2)==-2&&(d3^d4)==-2)return 2; return (d1==0&&EQ(v.a.sub(a).dot(v.a.sub(b)))<=0|| d2==0&&EQ(v.b.sub(a).dot(v.b.sub(b)))<=0|| d3==0&&EQ(a.sub(v.a).dot(a.sub(v.b)))<=0|| d4==0&&EQ(b.sub(v.a).dot(b.sub(v.b)))<=0); } /// Use this one bool lineCrossSegD(line v) { point p = crossPoint(v); return pointBetween(a, b, p); } /** 2 norms intersect 1 non-standard intersection 0 disjoint / not intersect **/ int lineCrossSeg(line v) { //*this seg, v line int d1=EQ(b.sub(a).cross(v.a.sub(a))); int d2=EQ(b.sub(a).cross(v.b.sub(a))); if ((d1^d2)==-2)return 2; return (d1==0||d2==0); } /** 0 Parallel 1 coincides 2 intersect **/ int lineCrossLine(line v) { if ((*this).parallel(v)) { return v.relation(a)==3; } return 2; } point crossPoint(line v) { double a1=v.b.sub(v.a).cross(a.sub(v.a)); double a2=v.b.sub(v.a).cross(b.sub(v.a)); return point((a.x*a2-b.x*a1)/(a2-a1),(a.y*a2-b.y*a1)/(a2-a1)); } double disPointToLine(point p) { return fabs(p.sub(a).cross(b.sub(a)))/length(); } /// To get only the minimum distance double disPointToSeg(point p) { if (EQ(p.sub(b).dot(a.sub(b)))<0||EQ(p.sub(a).dot(b.sub(a)))<0) { return min(p.distance(a),p.distance(b)); } return disPointToLine(p); } /// To get the minimum distance & point call it double disPointToSeg(point p, point &res) { if (EQ(p.sub(b).dot(a.sub(b)))<0||EQ(p.sub(a).dot(b.sub(a)))<0) { double pa = p.distance(a); double pb = p.distance(b); if(pa+EPS < pb) { res = a; return pa; } else { res = b; return pb; } } res = lineProg(p); return disPointToLine(p); } /// Intersection point between Perpendicular line from p and this line /// Have to check before if there is any intersection or not point lineProg(point p) { return a.add(b.sub(a).mul(b.sub(a).dot(p.sub(a))/b.sub(a).len2())); } point symmetryPoint(point p) { point q=lineProg(p); return point(2*q.x-p.x,2*q.y-p.y); } }; int main() { #ifdef dipta007 //READ("in.txt"); //WRITE("out.txt"); #endif // dipta007 ios_base::sync_with_stdio(0);cin.tie(0); int t; cin >> t; FOR(ci,1,t) { int n; point aladin; cin >> n >> aladin.x; aladin.y = 0; point prev; cin >> prev.x >> prev.y; line l; double res = 0.0; FOR(i,1,n-1) { point p; cin >> p.x >> p.y; if(i > 1) { //trace(i, p.x, p.y, l.a.x, l.a.y, l.b.x, l.b.y, turn(l.a, l.b, p)); if(turn(l.a, l.b, p) == 1) { point intersect; intersect = l.crossPoint(line(prev, p)); res += intersect.distance(p); trace(i, res, intersect.x, intersect.y, l.a.x, l.a.y, l.b.x, l.b.y, prev.x, prev.y, p.x, p.y); l = line(aladin, p); } } else { if(p.y != prev.y)res += prev.distance(p); l = line(aladin, p); trace(prev.x, prev.y, p.x, p.y); trace(i, res); } prev = p; } cout << "Case " << ci << ": "; cout << setprecision(12) << fixed; cout << res << endl; } return 0; }
// Copyright(c) 2020 Ken Okabe // This software is released under the MIT License, see LICENSE. #include "gtest/gtest.h" extern "C" { #include "null_command.h" } TEST(NullCommandTest, DoHasNoEffect) { Command c = nullCommand->GetInstance(); c->Do(c); } TEST(NullCommandTest, DeleteHasNoEffect) { Command c = nullCommand->GetInstance(); c->Delete(&c); }
/* * Ths code in this file is part of tcptrack. For more information see * http://www.rhythm.cx/~steve/devel/tcptrack * * Copyright (C) Steve Benson - 2003 * * tcptrack 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, or (at your * option) any later version. * * tcptrack 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #define _BSD_SOURCE 1 #define _REENTRANT #include <stdlib.h> #include <list> #include "SortedIterator.h" #include "TCContainer.h" SortedIterator::SortedIterator( TCContainer *c ) { numcons = c->numConnections(); cons = (TCPConnection **) malloc(numcons*sizeof(TCPConnection *)); // fill up the array with pointers to the connections int index=0; for( tccmap::iterator i=c->conhash2.begin(); i!=c->conhash2.end(); i++ ) { cons[index]=(*i).second; ++index; } cur=0; } // this method does the actual work of sorting // it should be called from a thread that can afford to do that work. void SortedIterator::sort() { if( numcons > 1 ) qsort(cons,numcons,sizeof(TCPConnection *),compare); } // get the next connection and advance our current location. // returns NULL if there are no more connections. TCPConnection * SortedIterator::getNext() { if( cur >= numcons ) return NULL; else return cons[cur++]; } void SortedIterator::rewind() { cur=0; } SortedIterator::~SortedIterator() { free(cons); } ///////////////////////////////////////////// // this is a callback function used from qsort in sort(). // it performs the comparison of the TCPConnection objects. int compare(const void *c1, const void *c2) { TCPConnection * con1; TCPConnection * con2; con1=* (TCPConnection **) c1; con2=* (TCPConnection **) c2; if( con1->getPayloadBytesPerSecond() > con2->getPayloadBytesPerSecond() ) return -1; else if( con1->getPayloadBytesPerSecond() < con2->getPayloadBytesPerSecond() ) return 1; else { if( con1->getIdleSeconds() < con2->getIdleSeconds() ) return -1; else if( con1->getIdleSeconds() > con2->getIdleSeconds() ) return 1; else return 0; } }
#include "\z\havoc\addons\medical\script_component.hpp"
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_utils_ArrayBufferView #include <lime/utils/ArrayBufferView.h> #endif #ifndef INCLUDED_lime_utils_TAError #include <lime/utils/TAError.h> #endif #ifndef INCLUDED_lime_utils__UInt8Array_UInt8Array_Impl_ #include <lime/utils/_UInt8Array/UInt8Array_Impl_.h> #endif #ifndef INCLUDED_openfl__Vector_FloatVector #include <openfl/_Vector/FloatVector.h> #endif #ifndef INCLUDED_openfl__Vector_IVector #include <openfl/_Vector/IVector.h> #endif #ifndef INCLUDED_openfl__Vector_IntVector #include <openfl/_Vector/IntVector.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_128_subarray,"lime.utils._UInt8Array.UInt8Array_Impl_","subarray",0x5b71e6e2,"lime.utils._UInt8Array.UInt8Array_Impl_.subarray","lime/utils/UInt8Array.hx",128,0x1e0ae96b) HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_133_fromBytes,"lime.utils._UInt8Array.UInt8Array_Impl_","fromBytes",0x90b0cfb8,"lime.utils._UInt8Array.UInt8Array_Impl_.fromBytes","lime/utils/UInt8Array.hx",133,0x1e0ae96b) HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_138_toBytes,"lime.utils._UInt8Array.UInt8Array_Impl_","toBytes",0xcd11ee47,"lime.utils._UInt8Array.UInt8Array_Impl_.toBytes","lime/utils/UInt8Array.hx",138,0x1e0ae96b) HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_143_toString,"lime.utils._UInt8Array.UInt8Array_Impl_","toString",0x8c5f6375,"lime.utils._UInt8Array.UInt8Array_Impl_.toString","lime/utils/UInt8Array.hx",143,0x1e0ae96b) HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_146_get_length,"lime.utils._UInt8Array.UInt8Array_Impl_","get_length",0x2ee09bb8,"lime.utils._UInt8Array.UInt8Array_Impl_.get_length","lime/utils/UInt8Array.hx",146,0x1e0ae96b) HX_LOCAL_STACK_FRAME(_hx_pos_56a8ecc5c2b3800c_90_boot,"lime.utils._UInt8Array.UInt8Array_Impl_","boot",0xada6be7b,"lime.utils._UInt8Array.UInt8Array_Impl_.boot","lime/utils/UInt8Array.hx",90,0x1e0ae96b) namespace lime{ namespace utils{ namespace _UInt8Array{ void UInt8Array_Impl__obj::__construct() { } Dynamic UInt8Array_Impl__obj::__CreateEmpty() { return new UInt8Array_Impl__obj; } void *UInt8Array_Impl__obj::_hx_vtable = 0; Dynamic UInt8Array_Impl__obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< UInt8Array_Impl__obj > _hx_result = new UInt8Array_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool UInt8Array_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2b2398dd; } int UInt8Array_Impl__obj::BYTES_PER_ELEMENT; ::lime::utils::ArrayBufferView UInt8Array_Impl__obj::subarray( ::lime::utils::ArrayBufferView this1,int begin, ::Dynamic end){ HX_GC_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_128_subarray) HXDLIN( 128) ::Dynamic end1 = end; HXDLIN( 128) if (::hx::IsNull( end1 )) { HXDLIN( 128) end1 = this1->length; } HXDLIN( 128) int len = (( (int)(end1) ) - begin); HXDLIN( 128) int byte_offset = ((begin * this1->bytesPerElement) + this1->byteOffset); HXDLIN( 128) ::lime::utils::ArrayBufferView view; HXDLIN( 128) switch((int)(this1->type)){ case (int)0: { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("subarray on a blank ArrayBufferView",39,87,fd,19))); } break; case (int)1: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,1); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,1); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,1); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,1); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,1); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Int8Array",40,53,da,77))); } } } } } HXDLIN( 128) view = this2; } break; case (int)2: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,2); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,2); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,2); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,2); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,2); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Int16Array",95,b2,95,a7))); } } } } } HXDLIN( 128) view = this2; } break; case (int)3: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,3); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,3); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,3); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,3); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,3); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Int32Array",9b,2e,53,61))); } } } } } HXDLIN( 128) view = this2; } break; case (int)4: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,4); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85))); } } } } } HXDLIN( 128) view = this2; } break; case (int)5: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,5); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,5); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,5); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,5); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,5); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt8ClampedArray",8d,06,77,13))); } } } } } HXDLIN( 128) view = this2; } break; case (int)6: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,6); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,6); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,6); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,6); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,6); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt16Array",0a,c7,2d,d5))); } } } } } HXDLIN( 128) view = this2; } break; case (int)7: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,7); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,7); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,7); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,7); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,7); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt32Array",10,43,eb,8e))); } } } } } HXDLIN( 128) view = this2; } break; case (int)8: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::FloatVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,8); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4))); } } } } } HXDLIN( 128) view = this2; } break; case (int)9: { HXDLIN( 128) ::Dynamic elements = null(); HXDLIN( 128) ::haxe::io::Bytes buffer = this1->buffer; HXDLIN( 128) ::cpp::VirtualArray array = null(); HXDLIN( 128) ::openfl::_Vector::FloatVector vector = null(); HXDLIN( 128) ::lime::utils::ArrayBufferView view1 = null(); HXDLIN( 128) ::Dynamic byteoffset = byte_offset; HXDLIN( 128) if (::hx::IsNull( byteoffset )) { HXDLIN( 128) byteoffset = 0; } HXDLIN( 128) ::lime::utils::ArrayBufferView this2; HXDLIN( 128) if (::hx::IsNotNull( elements )) { HXDLIN( 128) this2 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,9); } else { HXDLIN( 128) if (::hx::IsNotNull( array )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,9); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( vector )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,9); HXDLIN( 128) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = array->get_length(); HXDLIN( 128) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->copyFromArray(array,null()); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( view1 )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,9); HXDLIN( 128) ::haxe::io::Bytes srcData = view1->buffer; HXDLIN( 128) int srcLength = view1->length; HXDLIN( 128) int srcByteOffset = view1->byteOffset; HXDLIN( 128) int srcElementSize = view1->bytesPerElement; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) if ((view1->type == _this->type)) { HXDLIN( 128) int srcLength = srcData->length; HXDLIN( 128) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 128) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 128) _this->buffer = this1; HXDLIN( 128) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 128) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 128) _this->byteOffset = 0; HXDLIN( 128) _this->length = srcLength; HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) if (::hx::IsNotNull( buffer )) { HXDLIN( 128) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,9); HXDLIN( 128) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 128) if ((in_byteOffset < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) int bufferByteLength = buffer->length; HXDLIN( 128) int elementSize = _this->bytesPerElement; HXDLIN( 128) int newByteLength = bufferByteLength; HXDLIN( 128) if (::hx::IsNull( len )) { HXDLIN( 128) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 128) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 128) if ((newByteLength < 0)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 128) newByteLength = (len * _this->bytesPerElement); HXDLIN( 128) int newRange = (in_byteOffset + newByteLength); HXDLIN( 128) if ((newRange > bufferByteLength)) { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 128) _this->buffer = buffer; HXDLIN( 128) _this->byteOffset = in_byteOffset; HXDLIN( 128) _this->byteLength = newByteLength; HXDLIN( 128) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 128) this2 = _this; } else { HXDLIN( 128) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Float64Array",8f,de,6b,1e))); } } } } } HXDLIN( 128) view = this2; } break; } HXDLIN( 128) return view; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(UInt8Array_Impl__obj,subarray,return ) ::lime::utils::ArrayBufferView UInt8Array_Impl__obj::fromBytes( ::haxe::io::Bytes bytes, ::Dynamic __o_byteOffset, ::Dynamic len){ ::Dynamic byteOffset = __o_byteOffset; if (::hx::IsNull(__o_byteOffset)) byteOffset = 0; HX_GC_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_133_fromBytes) HXDLIN( 133) ::Dynamic elements = null(); HXDLIN( 133) ::cpp::VirtualArray array = null(); HXDLIN( 133) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 133) ::lime::utils::ArrayBufferView view = null(); HXDLIN( 133) ::Dynamic byteoffset = byteOffset; HXDLIN( 133) if (::hx::IsNull( byteoffset )) { HXDLIN( 133) byteoffset = 0; } HXDLIN( 133) ::lime::utils::ArrayBufferView this1; HXDLIN( 133) if (::hx::IsNotNull( elements )) { HXDLIN( 133) this1 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,4); } else { HXDLIN( 133) if (::hx::IsNotNull( array )) { HXDLIN( 133) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 133) _this->byteOffset = 0; HXDLIN( 133) _this->length = array->get_length(); HXDLIN( 133) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 133) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 133) _this->buffer = this2; HXDLIN( 133) _this->copyFromArray(array,null()); HXDLIN( 133) this1 = _this; } else { HXDLIN( 133) if (::hx::IsNotNull( vector )) { HXDLIN( 133) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 133) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 133) _this->byteOffset = 0; HXDLIN( 133) _this->length = array->get_length(); HXDLIN( 133) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 133) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 133) _this->buffer = this2; HXDLIN( 133) _this->copyFromArray(array,null()); HXDLIN( 133) this1 = _this; } else { HXDLIN( 133) if (::hx::IsNotNull( view )) { HXDLIN( 133) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 133) ::haxe::io::Bytes srcData = view->buffer; HXDLIN( 133) int srcLength = view->length; HXDLIN( 133) int srcByteOffset = view->byteOffset; HXDLIN( 133) int srcElementSize = view->bytesPerElement; HXDLIN( 133) int elementSize = _this->bytesPerElement; HXDLIN( 133) if ((view->type == _this->type)) { HXDLIN( 133) int srcLength = srcData->length; HXDLIN( 133) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 133) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 133) _this->buffer = this1; HXDLIN( 133) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 133) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 133) _this->byteOffset = 0; HXDLIN( 133) _this->length = srcLength; HXDLIN( 133) this1 = _this; } else { HXDLIN( 133) if (::hx::IsNotNull( bytes )) { HXDLIN( 133) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 133) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 133) if ((in_byteOffset < 0)) { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 133) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 133) int bufferByteLength = bytes->length; HXDLIN( 133) int elementSize = _this->bytesPerElement; HXDLIN( 133) int newByteLength = bufferByteLength; HXDLIN( 133) if (::hx::IsNull( len )) { HXDLIN( 133) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 133) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 133) if ((newByteLength < 0)) { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 133) newByteLength = (( (int)(len) ) * _this->bytesPerElement); HXDLIN( 133) int newRange = (in_byteOffset + newByteLength); HXDLIN( 133) if ((newRange > bufferByteLength)) { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 133) _this->buffer = bytes; HXDLIN( 133) _this->byteOffset = in_byteOffset; HXDLIN( 133) _this->byteLength = newByteLength; HXDLIN( 133) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 133) this1 = _this; } else { HXDLIN( 133) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85))); } } } } } HXDLIN( 133) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(UInt8Array_Impl__obj,fromBytes,return ) ::haxe::io::Bytes UInt8Array_Impl__obj::toBytes( ::lime::utils::ArrayBufferView this1){ HX_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_138_toBytes) HXDLIN( 138) return this1->buffer; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(UInt8Array_Impl__obj,toBytes,return ) ::String UInt8Array_Impl__obj::toString( ::lime::utils::ArrayBufferView this1){ HX_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_143_toString) HXDLIN( 143) if (::hx::IsNotNull( this1 )) { HXDLIN( 143) return ((((HX_("UInt8Array [byteLength:",d6,2f,a0,d4) + this1->byteLength) + HX_(", length:",a0,04,67,ef)) + this1->length) + HX_("]",5d,00,00,00)); } else { HXDLIN( 143) return null(); } HXDLIN( 143) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(UInt8Array_Impl__obj,toString,return ) int UInt8Array_Impl__obj::get_length( ::lime::utils::ArrayBufferView this1){ HX_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_146_get_length) HXDLIN( 146) return this1->length; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(UInt8Array_Impl__obj,get_length,return ) UInt8Array_Impl__obj::UInt8Array_Impl__obj() { } bool UInt8Array_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 7: if (HX_FIELD_EQ(inName,"toBytes") ) { outValue = toBytes_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"subarray") ) { outValue = subarray_dyn(); return true; } if (HX_FIELD_EQ(inName,"toString") ) { outValue = toString_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"fromBytes") ) { outValue = fromBytes_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"get_length") ) { outValue = get_length_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *UInt8Array_Impl__obj_sMemberStorageInfo = 0; static ::hx::StaticInfo UInt8Array_Impl__obj_sStaticStorageInfo[] = { {::hx::fsInt,(void *) &UInt8Array_Impl__obj::BYTES_PER_ELEMENT,HX_("BYTES_PER_ELEMENT",a6,04,1d,cc)}, { ::hx::fsUnknown, 0, null()} }; #endif static void UInt8Array_Impl__obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(UInt8Array_Impl__obj::BYTES_PER_ELEMENT,"BYTES_PER_ELEMENT"); }; #ifdef HXCPP_VISIT_ALLOCS static void UInt8Array_Impl__obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(UInt8Array_Impl__obj::BYTES_PER_ELEMENT,"BYTES_PER_ELEMENT"); }; #endif ::hx::Class UInt8Array_Impl__obj::__mClass; static ::String UInt8Array_Impl__obj_sStaticFields[] = { HX_("BYTES_PER_ELEMENT",a6,04,1d,cc), HX_("subarray",19,54,81,07), HX_("fromBytes",a1,f2,20,72), HX_("toBytes",f0,54,1c,8a), HX_("toString",ac,d0,6e,38), HX_("get_length",af,04,8f,8f), ::String(null()) }; void UInt8Array_Impl__obj::__register() { UInt8Array_Impl__obj _hx_dummy; UInt8Array_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.utils._UInt8Array.UInt8Array_Impl_",c5,4a,c5,12); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &UInt8Array_Impl__obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = UInt8Array_Impl__obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(UInt8Array_Impl__obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< UInt8Array_Impl__obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = UInt8Array_Impl__obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = UInt8Array_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = UInt8Array_Impl__obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void UInt8Array_Impl__obj::__boot() { { HX_STACKFRAME(&_hx_pos_56a8ecc5c2b3800c_90_boot) HXDLIN( 90) BYTES_PER_ELEMENT = 1; } } } // end namespace lime } // end namespace utils } // end namespace _UInt8Array
// // HAPWiFiHelper.hpp // Homekit // // Created on: 08.08.2017 // Author: michael // #ifndef HAPWIFIHELPER_HPP_ #define HAPWIFIHELPER_HPP_ #include <esp_wps.h> #include <Arduino.h> #include <WiFi.h> #include <WiFiMulti.h> #include <DNSServer.h> #include <functional> #include <vector> #include "HTTPServer.hpp" #include "HAPGlobals.hpp" #include "HAPConfig.hpp" #if HAP_PIXEL_INDICATOR_ENABLED #include "HAPIndicatorPixelColors.hpp" #endif using namespace httpsserver; enum HAP_WIFI_MODE { HAP_WIFI_MODE_AP = 0x00, // 0 HAP_WIFI_MODE_MULTI = 0x01, // 1 HAP_WIFI_MODE_WPS = 0x02, // 2 HAP_WIFI_MODE_SMARTCONFIG = 0x03, // 3 HAP_WIFI_MODE_BLE_PROV = 0x04, // 4 HAP_WIFI_MODE_AP_PROV = 0x05, // 5 }; class HAPWiFiHelper { public: HAPWiFiHelper(); ~HAPWiFiHelper(); static void begin(HAPConfig* config, std::function<bool(bool)> callbackBegin, const char* hostname); static void connect(enum HAP_WIFI_MODE mode); static bool captiveInitialized(); static void handle(); inline static bool isProvisioned(){ return _isProvisioned; } #if HAP_PIXEL_INDICATOR_ENABLED // static uint32_t getColorForMode(enum HAP_WIFI_MODE mode); // static RgbColor getColorForMode(enum HAP_WIFI_MODE mode); static CRGB getColorForMode(enum HAP_WIFI_MODE mode); #endif static HAP_WIFI_MODE getNextMode(); static HAP_WIFI_MODE getNextMode(enum HAP_WIFI_MODE mode); static HAP_WIFI_MODE getCurrentMode(); private: #if HAP_PROVISIONING_ENABLE_BLE == 0 static void eventHandler(WiFiEvent_t event); #else static void eventHandlerBLEProv(system_event_t *sys_event, wifi_prov_event_t *prov_event); #endif static void startWPS(); static void startCaptivePortal(); static void stopCaptivePortal(); static void connectMulti(); static void handleRootGet(HTTPRequest * req, HTTPResponse * res); static void handleRootPost(HTTPRequest * req, HTTPResponse * res); static void rootKeyProcessor(const String& key, HTTPResponse * res); static esp_wps_config_t _wpsConfig; static WiFiMulti _wifiMulti; static enum HAP_WIFI_MODE _mode; static HAPConfig* _config; static uint8_t _errorCount; static DNSServer* _dnsServer; static HTTPServer* _webserver; static bool _captiveInitialized; static bool _isProvisioned; static std::function<bool(bool)> _callbackBegin; }; #endif /* HAPWIFIHELPER_HPP_ */
/** * \file PnlWdbeSilRec_blks.cpp * job handler for job PnlWdbeSilRec (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWdbeSilRec::VecVDo ******************************************************************************/ uint PnlWdbeSilRec::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butminimizeclick") return BUTMINIMIZECLICK; if (s == "butregularizeclick") return BUTREGULARIZECLICK; return(0); }; string PnlWdbeSilRec::VecVDo::getSref( const uint ix ) { if (ix == BUTMINIMIZECLICK) return("ButMinimizeClick"); if (ix == BUTREGULARIZECLICK) return("ButRegularizeClick"); return(""); }; /****************************************************************************** class PnlWdbeSilRec::ContInf ******************************************************************************/ PnlWdbeSilRec::ContInf::ContInf( const string& TxtRef ) : Block() { this->TxtRef = TxtRef; mask = {TXTREF}; }; void PnlWdbeSilRec::ContInf::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfWdbeSilRec"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["TxtRef"] = TxtRef; }; void PnlWdbeSilRec::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfWdbeSilRec"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfWdbeSilRec"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "TxtRef", TxtRef); xmlTextWriterEndElement(wr); }; set<uint> PnlWdbeSilRec::ContInf::comm( const ContInf* comp ) { set<uint> items; if (TxtRef == comp->TxtRef) insert(items, TXTREF); return(items); }; set<uint> PnlWdbeSilRec::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTREF}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeSilRec::StatApp ******************************************************************************/ void PnlWdbeSilRec::StatApp::writeJSON( Json::Value& sup , string difftag , const bool initdoneDetail , const bool initdone1NPeripheral , const bool initdoneSil1NUnit , const bool initdone1NBank , const bool initdoneFwd1NController , const bool initdone1NTarget , const bool initdoneRef1NCommand , const bool initdoneRef1NError , const bool initdoneHk1NVector , const bool initdoneHk1NModule ) { if (difftag.length() == 0) difftag = "StatAppWdbeSilRec"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["initdoneDetail"] = initdoneDetail; me["initdone1NPeripheral"] = initdone1NPeripheral; me["initdoneSil1NUnit"] = initdoneSil1NUnit; me["initdone1NBank"] = initdone1NBank; me["initdoneFwd1NController"] = initdoneFwd1NController; me["initdone1NTarget"] = initdone1NTarget; me["initdoneRef1NCommand"] = initdoneRef1NCommand; me["initdoneRef1NError"] = initdoneRef1NError; me["initdoneHk1NVector"] = initdoneHk1NVector; me["initdoneHk1NModule"] = initdoneHk1NModule; }; void PnlWdbeSilRec::StatApp::writeXML( xmlTextWriter* wr , string difftag , bool shorttags , const bool initdoneDetail , const bool initdone1NPeripheral , const bool initdoneSil1NUnit , const bool initdone1NBank , const bool initdoneFwd1NController , const bool initdone1NTarget , const bool initdoneRef1NCommand , const bool initdoneRef1NError , const bool initdoneHk1NVector , const bool initdoneHk1NModule ) { if (difftag.length() == 0) difftag = "StatAppWdbeSilRec"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemAppWdbeSilRec"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "initdoneDetail", initdoneDetail); writeBoolAttr(wr, itemtag, "sref", "initdone1NPeripheral", initdone1NPeripheral); writeBoolAttr(wr, itemtag, "sref", "initdoneSil1NUnit", initdoneSil1NUnit); writeBoolAttr(wr, itemtag, "sref", "initdone1NBank", initdone1NBank); writeBoolAttr(wr, itemtag, "sref", "initdoneFwd1NController", initdoneFwd1NController); writeBoolAttr(wr, itemtag, "sref", "initdone1NTarget", initdone1NTarget); writeBoolAttr(wr, itemtag, "sref", "initdoneRef1NCommand", initdoneRef1NCommand); writeBoolAttr(wr, itemtag, "sref", "initdoneRef1NError", initdoneRef1NError); writeBoolAttr(wr, itemtag, "sref", "initdoneHk1NVector", initdoneHk1NVector); writeBoolAttr(wr, itemtag, "sref", "initdoneHk1NModule", initdoneHk1NModule); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWdbeSilRec::StatShr ******************************************************************************/ PnlWdbeSilRec::StatShr::StatShr( const uint ixWdbeVExpstate , const ubigint jrefDetail , const ubigint jref1NPeripheral , const ubigint jrefSil1NUnit , const ubigint jref1NBank , const ubigint jrefFwd1NController , const ubigint jref1NTarget , const ubigint jrefRef1NCommand , const ubigint jrefRef1NError , const ubigint jrefHk1NVector , const ubigint jrefHk1NModule , const bool ButRegularizeActive ) : Block() { this->ixWdbeVExpstate = ixWdbeVExpstate; this->jrefDetail = jrefDetail; this->jref1NPeripheral = jref1NPeripheral; this->jrefSil1NUnit = jrefSil1NUnit; this->jref1NBank = jref1NBank; this->jrefFwd1NController = jrefFwd1NController; this->jref1NTarget = jref1NTarget; this->jrefRef1NCommand = jrefRef1NCommand; this->jrefRef1NError = jrefRef1NError; this->jrefHk1NVector = jrefHk1NVector; this->jrefHk1NModule = jrefHk1NModule; this->ButRegularizeActive = ButRegularizeActive; mask = {IXWDBEVEXPSTATE, JREFDETAIL, JREF1NPERIPHERAL, JREFSIL1NUNIT, JREF1NBANK, JREFFWD1NCONTROLLER, JREF1NTARGET, JREFREF1NCOMMAND, JREFREF1NERROR, JREFHK1NVECTOR, JREFHK1NMODULE, BUTREGULARIZEACTIVE}; }; void PnlWdbeSilRec::StatShr::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrWdbeSilRec"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["srefIxWdbeVExpstate"] = VecWdbeVExpstate::getSref(ixWdbeVExpstate); me["scrJrefDetail"] = Scr::scramble(jrefDetail); me["scrJref1NPeripheral"] = Scr::scramble(jref1NPeripheral); me["scrJrefSil1NUnit"] = Scr::scramble(jrefSil1NUnit); me["scrJref1NBank"] = Scr::scramble(jref1NBank); me["scrJrefFwd1NController"] = Scr::scramble(jrefFwd1NController); me["scrJref1NTarget"] = Scr::scramble(jref1NTarget); me["scrJrefRef1NCommand"] = Scr::scramble(jrefRef1NCommand); me["scrJrefRef1NError"] = Scr::scramble(jrefRef1NError); me["scrJrefHk1NVector"] = Scr::scramble(jrefHk1NVector); me["scrJrefHk1NModule"] = Scr::scramble(jrefHk1NModule); me["ButRegularizeActive"] = ButRegularizeActive; }; void PnlWdbeSilRec::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrWdbeSilRec"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrWdbeSilRec"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "srefIxWdbeVExpstate", VecWdbeVExpstate::getSref(ixWdbeVExpstate)); writeStringAttr(wr, itemtag, "sref", "scrJrefDetail", Scr::scramble(jrefDetail)); writeStringAttr(wr, itemtag, "sref", "scrJref1NPeripheral", Scr::scramble(jref1NPeripheral)); writeStringAttr(wr, itemtag, "sref", "scrJrefSil1NUnit", Scr::scramble(jrefSil1NUnit)); writeStringAttr(wr, itemtag, "sref", "scrJref1NBank", Scr::scramble(jref1NBank)); writeStringAttr(wr, itemtag, "sref", "scrJrefFwd1NController", Scr::scramble(jrefFwd1NController)); writeStringAttr(wr, itemtag, "sref", "scrJref1NTarget", Scr::scramble(jref1NTarget)); writeStringAttr(wr, itemtag, "sref", "scrJrefRef1NCommand", Scr::scramble(jrefRef1NCommand)); writeStringAttr(wr, itemtag, "sref", "scrJrefRef1NError", Scr::scramble(jrefRef1NError)); writeStringAttr(wr, itemtag, "sref", "scrJrefHk1NVector", Scr::scramble(jrefHk1NVector)); writeStringAttr(wr, itemtag, "sref", "scrJrefHk1NModule", Scr::scramble(jrefHk1NModule)); writeBoolAttr(wr, itemtag, "sref", "ButRegularizeActive", ButRegularizeActive); xmlTextWriterEndElement(wr); }; set<uint> PnlWdbeSilRec::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ixWdbeVExpstate == comp->ixWdbeVExpstate) insert(items, IXWDBEVEXPSTATE); if (jrefDetail == comp->jrefDetail) insert(items, JREFDETAIL); if (jref1NPeripheral == comp->jref1NPeripheral) insert(items, JREF1NPERIPHERAL); if (jrefSil1NUnit == comp->jrefSil1NUnit) insert(items, JREFSIL1NUNIT); if (jref1NBank == comp->jref1NBank) insert(items, JREF1NBANK); if (jrefFwd1NController == comp->jrefFwd1NController) insert(items, JREFFWD1NCONTROLLER); if (jref1NTarget == comp->jref1NTarget) insert(items, JREF1NTARGET); if (jrefRef1NCommand == comp->jrefRef1NCommand) insert(items, JREFREF1NCOMMAND); if (jrefRef1NError == comp->jrefRef1NError) insert(items, JREFREF1NERROR); if (jrefHk1NVector == comp->jrefHk1NVector) insert(items, JREFHK1NVECTOR); if (jrefHk1NModule == comp->jrefHk1NModule) insert(items, JREFHK1NMODULE); if (ButRegularizeActive == comp->ButRegularizeActive) insert(items, BUTREGULARIZEACTIVE); return(items); }; set<uint> PnlWdbeSilRec::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWDBEVEXPSTATE, JREFDETAIL, JREF1NPERIPHERAL, JREFSIL1NUNIT, JREF1NBANK, JREFFWD1NCONTROLLER, JREF1NTARGET, JREFREF1NCOMMAND, JREFREF1NERROR, JREFHK1NVECTOR, JREFHK1NMODULE, BUTREGULARIZEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeSilRec::Tag ******************************************************************************/ void PnlWdbeSilRec::Tag::writeJSON( const uint ixWdbeVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagWdbeSilRec"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWdbeVLocale == VecWdbeVLocale::ENUS) { me["Cpt"] = "Silicon device"; }; }; void PnlWdbeSilRec::Tag::writeXML( const uint ixWdbeVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagWdbeSilRec"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemWdbeSilRec"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWdbeVLocale == VecWdbeVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Silicon device"); }; xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWdbeSilRec::DpchAppDo ******************************************************************************/ PnlWdbeSilRec::DpchAppDo::DpchAppDo() : DpchAppWdbe(VecWdbeVDpch::DPCHAPPWDBESILRECDO) { ixVDo = 0; }; string PnlWdbeSilRec::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeSilRec::DpchAppDo::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["DpchAppWdbeSilRecDo"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (me.isMember("srefIxVDo")) {ixVDo = VecVDo::getIx(me["srefIxVDo"].asString()); add(IXVDO);}; } else { }; }; void PnlWdbeSilRec::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWdbeSilRecDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlWdbeSilRec::DpchEngData ******************************************************************************/ PnlWdbeSilRec::DpchEngData::DpchEngData( const ubigint jref , ContInf* continf , StatShr* statshr , const set<uint>& mask ) : DpchEngWdbe(VecWdbeVDpch::DPCHENGWDBESILRECDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTINF, STATAPP, STATSHR, TAG}; else this->mask = mask; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; }; string PnlWdbeSilRec::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTINF)) ss.push_back("continf"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeSilRec::DpchEngData::merge( DpchEngWdbe* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(STATAPP)) add(STATAPP); if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(TAG)) add(TAG); }; void PnlWdbeSilRec::DpchEngData::writeJSON( const uint ixWdbeVLocale , Json::Value& sup ) { Json::Value& me = sup["DpchEngWdbeSilRecData"] = Json::Value(Json::objectValue); if (has(JREF)) me["scrJref"] = Scr::scramble(jref); if (has(CONTINF)) continf.writeJSON(me); if (has(STATAPP)) StatApp::writeJSON(me); if (has(STATSHR)) statshr.writeJSON(me); if (has(TAG)) Tag::writeJSON(ixWdbeVLocale, me); }; void PnlWdbeSilRec::DpchEngData::writeXML( const uint ixWdbeVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngWdbeSilRecData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wdbe"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTINF)) continf.writeXML(wr); if (has(STATAPP)) StatApp::writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(TAG)) Tag::writeXML(ixWdbeVLocale, wr); xmlTextWriterEndElement(wr); };
/** * @file decode.cpp WebRTC Acoustic Echo Cancellation (AEC) -- Decode * * Copyright (C) 2010 Creytiv.com */ #include <re.h> #include <rem.h> #include <baresip.h> #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include "aec.h" struct aec_dec { struct aufilt_dec_st af; /* inheritance */ struct aec *aec; }; static void dec_destructor(void *arg) { struct aec_dec *st = (struct aec_dec *)arg; list_unlink(&st->af.le); mem_deref(st->aec); } int webrtc_aec_decode_update(struct aufilt_dec_st **stp, void **ctx, const struct aufilt *af, struct aufilt_prm *prm, const struct audio *au) { struct aec_dec *st; int err; if (!stp || !af || !prm) return EINVAL; switch (prm->fmt) { case AUFMT_S16LE: case AUFMT_FLOAT: break; default: warning("webrtc_aec: dec: unsupported sample format (%s)\n", aufmt_name((enum aufmt)prm->fmt)); return ENOTSUP; } if (*stp) return 0; st = (struct aec_dec *)mem_zalloc(sizeof(*st), dec_destructor); if (!st) return ENOMEM; err = webrtc_aec_alloc(&st->aec, ctx, prm); if (err) goto out; out: if (err) mem_deref(st); else *stp = (struct aufilt_dec_st *)st; return err; } static int decode_float(struct aec_dec *dec, const float *sampv, size_t sampc) { struct aec *aec = dec->aec; const float *farend = (const float *)sampv; size_t i; int r; int err = 0; pthread_mutex_lock(&aec->mutex); for (i = 0; i < sampc; i += aec->subframe_len) { r = WebRtcAec_BufferFarend(aec->inst, farend + i, aec->subframe_len); if (r != 0) { warning("webrtc_aec: decode: WebRtcAec_BufferFarend" " error (%d)\n", r); err = EPROTO; goto out; } } out: pthread_mutex_unlock(&aec->mutex); return err; } int webrtc_aec_decode(struct aufilt_dec_st *st, struct auframe *af) { struct aec_dec *dec = (struct aec_dec *)st; float *flt; int err = 0; if (!st || !af) return EINVAL; /* convert samples to float if needed */ switch (af->fmt) { case AUFMT_S16LE: flt = (float *)mem_alloc(af->sampc * sizeof(float), NULL); if (!flt) return ENOMEM; auconv_from_s16(AUFMT_FLOAT, flt, (int16_t *)af->sampv, af->sampc); err = decode_float(dec, flt, af->sampc); mem_deref(flt); break; case AUFMT_FLOAT: err = decode_float(dec, (float *)af->sampv, af->sampc); break; default: return ENOTSUP; } return err; }
/** * @file methods/ann/visitor/deterministic_set_visitor.hpp * @author Marcus Edel * * This file provides an abstraction for the Deterministic() function for * different layers and automatically directs any parameter to the right layer * type. * * 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_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_HPP #define MLPACK_METHODS_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_HPP #include <mlpack/methods/ann/layer/layer_traits.hpp> #include <boost/variant.hpp> namespace mlpack { namespace ann { /** * DeterministicSetVisitor set the deterministic parameter given the * deterministic value. */ class DeterministicSetVisitor : public boost::static_visitor<void> { public: //! Set the deterministic parameter given the current deterministic value. DeterministicSetVisitor(const bool deterministic = true); //! Set the deterministic parameter. template<typename LayerType> void operator()(LayerType* layer) const; void operator()(MoreTypes layer) const; private: //! The deterministic parameter. const bool deterministic; //! Set the deterministic parameter if the module implements the //! Deterministic() and Model() function. template<typename T> typename std::enable_if< HasDeterministicCheck<T, bool&(T::*)(void)>::value && HasModelCheck<T>::value, void>::type LayerDeterministic(T* layer) const; //! Set the deterministic parameter if the module implements the //! Model() function. template<typename T> typename std::enable_if< !HasDeterministicCheck<T, bool&(T::*)(void)>::value && HasModelCheck<T>::value, void>::type LayerDeterministic(T* layer) const; //! Set the deterministic parameter if the module implements the //! Deterministic() function. template<typename T> typename std::enable_if< HasDeterministicCheck<T, bool&(T::*)(void)>::value && !HasModelCheck<T>::value, void>::type LayerDeterministic(T* layer) const; //! Do not set the deterministic parameter if the module doesn't implement the //! Deterministic() or Model() function. template<typename T> typename std::enable_if< !HasDeterministicCheck<T, bool&(T::*)(void)>::value && !HasModelCheck<T>::value, void>::type LayerDeterministic(T* layer) const; }; } // namespace ann } // namespace mlpack // Include implementation. #include "deterministic_set_visitor_impl.hpp" #endif
#include <iostream> using namespace std; int main() { int A, B, C, D, diferenca; cin >> A >> B >> C >> D; diferenca = ((A * B) - (C * D)); cout << "DIFERENCA = " << diferenca << endl; return 0; }
#include "State.hpp" State::State() : newstate(0) { } State::~State() { }
double Solution::findMedianSortedArrays(const vector<int> &A, const vector<int> &B) { int m = A.size(), n = B.size(); if (m > n) return findMedianSortedArrays(B, A); int imin, imax, i, j; imin = 0; imax = m; while (imin <= imax) { i = (imin + imax)/2; j = (m+n+1)/2 - i; if (j > 0 && i < m && B[j - 1] > A[i]) imin = i + 1; else if (i > 0 && j < n && A[i - 1] > B[j]) imax = i - 1; else { int median1 = 0, median2 = 0; if (i == 0) median1 = B[j - 1]; else if (j == 0) median1 = A[i - 1]; else median1 = max(A[i - 1], B[j - 1]); if ((m+n) % 2 == 1) return 1.0 * median1; if (i == m) median2 = B[j]; else if (j == n) median2 = A[i]; else median2 = min(A[i], B[j]); return 1.0 * (median1 + median2) / 2.0; } } return -1.0; }
/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame 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. * */ #pragma once #include "SDK/Core/AFPlatform.hpp" namespace ark { //will modify to enum class with C++ mordern standard enum ARK_APP_TYPE { ARK_APP_DEFAULT = 0, //none //cluster level ARK_APP_MASTER = 1, //master ARK_APP_DIR = 2, //dir ARK_APP_LOG = 3, //log ARK_APP_ROUTER = 4, //router, world & cluster middle layer ARK_PROC_OSS = 5, //oss //ARK_PROC_CLUTER_RANK = 6, //cluster rank //ARK_PROC_CLUSTER_MAIL = 7, //cluster mail //ARK_PROC_CLUSTER_PUB = 8, //cluster public ARK_APP_CLUSTER_MAX = 99, //max of cluster //world level ARK_APP_WORLD = 100, //world ARK_APP_GAME = 101, //game ARK_APP_LOGIN = 102, //login ARK_APP_PROXY = 103, //proxy ARK_APP_DB = 104, //dbproxy //ARK_APP_RANK = 105, //rank //ARK_APP_PUB = 106, //public //ARK_APP_CS_PROXY = 107, //cs_proxy, produce cross-server things ARK_APP_WORLD_MAX = 199, //max of world //db ARK_APP_REDIS = 200, //redis server ARK_APP_MYSQL = 201, //mysql server ARK_APP_MAX = 255, //max of all processes }; }
#ifndef SPROUT_FUNCTIONAL_POLYMORPHIC_GREATER_EQUAL_HPP #define SPROUT_FUNCTIONAL_POLYMORPHIC_GREATER_EQUAL_HPP #include <utility> #include <sprout/config.hpp> #include <sprout/utility/forward.hpp> namespace sprout { // // greater_equal_t // greater_equal_ // struct greater_equal_t { public: template<typename T, typename U> SPROUT_CONSTEXPR decltype(std::declval<T>() >= std::declval<U>()) operator()(T&& x, U&& y) const SPROUT_NOEXCEPT_EXPR(SPROUT_NOEXCEPT_EXPR(std::declval<T>() >= std::declval<U>())) { return sprout::forward<T>(x) >= sprout::forward<U>(y); } }; namespace { SPROUT_STATIC_CONSTEXPR sprout::greater_equal_t greater_equal_{}; } // anonymous-namespace } // namespace sprout #endif // #ifndef SPROUT_FUNCTIONAL_POLYMORPHIC_GREATER_EQUAL_HPP
//+------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996 - 1996. // // File: clist.hxx // // Contents: Class to create and maintain a singly linked list. // // History: 28-Jun-96 MacM Created // //-------------------------------------------------------------------- #ifndef __CLIST_HXX__ #define __CLIST_HXX__ typedef struct _CSLIST_NODE { PVOID pvData; struct _CSLIST_NODE *pNext; } CSLIST_NODE, *PCSLIST_NODE; // // Free function callback typedef. This function will delete the memory saved // as the data in a list node on list destruction // typedef VOID (*FreeFunc)(PVOID); // // This function returns TRUE if the two items are the same, or FALSE if they // are not // typedef BOOL (*CompFunc)(PVOID, PVOID); //+--------------------------------------------------------------------------- // // Class: CSList // // Synopsis: Singly linked list class, single threaded // // Methods: Insert // InsertIfUnique // Find // Reset // NextData // Remove // QueryCount // //---------------------------------------------------------------------------- class CSList { public: CSList(FreeFunc pfnFree) : _pfnFree (pfnFree), _pHead (NULL), _pCurrent (NULL), _cItems (0) { }; inline ~CSList(); DWORD QueryCount(void) { return(_cItems);}; inline DWORD Insert(PVOID pvData); inline DWORD InsertIfUnique(PVOID pvData, CompFunc pfnComp); inline PVOID Find(PVOID pvData, CompFunc pfnComp); inline PVOID NextData(); VOID Reset() {_pCurrent = _pHead;}; inline DWORD Remove(PVOID pData); protected: PCSLIST_NODE _pHead; PCSLIST_NODE _pCurrent; DWORD _cItems; FreeFunc _pfnFree; }; //+------------------------------------------------------------------ // // Member: CSList::~CSList // // Synopsis: Destructor for the CSList class // // Arguments: None // // Returns: void // //+------------------------------------------------------------------ CSList::~CSList() { PCSLIST_NODE pNext = _pHead; // // We'll do this in 2 seperate, but almost identical loops, so that we // don't have to check for a null free pointer in every loop iteration. // if(_pfnFree != NULL) { while(pNext != NULL) { pNext = _pHead->pNext; (*_pfnFree)(_pHead->pvData); delete _pHead; _pHead = pNext; } } else { while(pNext != NULL) { pNext = _pHead->pNext; delete _pHead; _pHead = pNext; } } } //+------------------------------------------------------------------ // // Member: CSList::Insert // // Synopsis: Creates a new node at the begining of the list and // inserts it into the list // // // Arguments: [IN pvData] -- Data to insert // // Returns: ERROR_SUCCESS -- Everything worked // ERROR_NOT_ENOUGH_MEMORY A memory allocation failed // //+------------------------------------------------------------------ DWORD CSList::Insert(PVOID pvData) { DWORD dwErr = ERROR_SUCCESS; PCSLIST_NODE pNew = new CSLIST_NODE; if(pNew == NULL) { dwErr = ERROR_NOT_ENOUGH_MEMORY; } else { pNew->pvData = pvData; pNew->pNext = _pHead; _pHead = pNew; _cItems++; } return(dwErr); } //+------------------------------------------------------------------ // // Member: CSList::InsertIfUnique // // Synopsis: Creates a new node at the begining of the list and // inserts it into the list if the data does not already // exist in the list. If the data does exist, nothing // is done, but SUCCESS is returned // // // Arguments: [IN pvData] -- Data to insert // // Returns: ERROR_SUCCESS -- Everything worked // ERROR_NOT_ENOUGH_MEMORY A memory allocation failed // //+------------------------------------------------------------------ DWORD CSList::InsertIfUnique(PVOID pvData, CompFunc pfnComp) { DWORD dwErr = ERROR_SUCCESS; // // First, make sure it doesn't already exist, and then insert it // PCSLIST_NODE pWalk = _pHead; while(pWalk) { if((pfnComp)(pvData, pWalk->pvData) == TRUE) { break; } pWalk = pWalk->pNext; } if(pWalk == NULL) { dwErr = Insert(pvData); } return(dwErr); } //+------------------------------------------------------------------ // // Member: CSList::Find // // Synopsis: Locates the given data in the list, if it exists // // Arguments: [IN pvData] -- Data to insert // // Returns: ERROR_SUCCESS -- Everything worked // ERROR_NOT_ENOUGH_MEMORY A memory allocation failed // //+------------------------------------------------------------------ PVOID CSList::Find(PVOID pvData, CompFunc pfnComp) { PCSLIST_NODE pWalk = _pHead; while(pWalk) { if((pfnComp)(pvData, pWalk->pvData) == TRUE) { break; } pWalk = pWalk->pNext; } return(pWalk == NULL ? NULL : pWalk->pvData); } //+------------------------------------------------------------------ // // Member: CSList::NextData // // Synopsis: Returns the next data in the list // // // Arguments: None // // Returns: NULL -- No more items // Pointer to next data in list on success // //+------------------------------------------------------------------ PVOID CSList::NextData() { PVOID pvRet = NULL; if(_pCurrent != NULL) { pvRet = _pCurrent->pvData; _pCurrent = _pCurrent->pNext; } return(pvRet); } //+------------------------------------------------------------------ // // Member: CSList::Remove // // Synopsis: Removes the node that references the indicated data // // Arguments: pData -- The data in the node to remove // // Returns: ERROR_SUCCESS -- Success // ERROR_INVALID_PARAMETER Node not found // //+------------------------------------------------------------------ DWORD CSList::Remove(PVOID pData) { PCSLIST_NODE pWalk = _pHead; PCSLIST_NODE pPrev = NULL; DWORD dwErr = ERROR_INVALID_PARAMETER; while(pWalk) { if(pData == pWalk->pvData) { if(pPrev == NULL) { _pHead = pWalk->pNext; } else { pPrev->pNext = pWalk->pNext; } delete pWalk; dwErr = ERROR_SUCCESS; _cItems--; break; } pPrev = pWalk; pWalk = pWalk->pNext; } return(dwErr); } #endif // __CLIST_HXX__
//================================================================================================= /*! // \file src/mathtest/dmatdmatmult/M9x7aM7x9a.cpp // \brief Source file for the M9x7aM7x9a dense matrix/dense matrix multiplication math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'M9x7aM7x9a'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using M9x7a = blaze::StaticMatrix<TypeA,9UL,7UL>; using M7x9a = blaze::StaticMatrix<TypeA,7UL,9UL>; // Creator type definitions using CM9x7a = blazetest::Creator<M9x7a>; using CM7x9a = blazetest::Creator<M7x9a>; // Running the tests RUN_DMATDMATMULT_OPERATION_TEST( CM9x7a(), CM7x9a() ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************